diff --git a/pool/shard007/C++/0090774_completion_stub_factory.cc b/pool/shard007/C++/0090774_completion_stub_factory.cc new file mode 100644 index 0000000000000000000000000000000000000000..4fad3b4727ba4f4ce281db5e454b24ada2227c1c --- /dev/null +++ b/pool/shard007/C++/0090774_completion_stub_factory.cc @@ -0,0 +1,67 @@ +// Copyright 2022 Google LLC +// +// 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 +// +// https://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. + +// Generated by the Codegen C++ plugin. +// If you make any local changes, they will be lost. +// source: google/cloud/retail/v2/completion_service.proto + +#include "google/cloud/retail/internal/completion_stub_factory.h" +#include "google/cloud/retail/internal/completion_auth_decorator.h" +#include "google/cloud/retail/internal/completion_logging_decorator.h" +#include "google/cloud/retail/internal/completion_metadata_decorator.h" +#include "google/cloud/retail/internal/completion_stub.h" +#include "google/cloud/common_options.h" +#include "google/cloud/grpc_options.h" +#include "google/cloud/internal/algorithm.h" +#include "google/cloud/log.h" +#include "google/cloud/options.h" +#include +#include + +namespace google { +namespace cloud { +namespace retail_internal { +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN + +std::shared_ptr CreateDefaultCompletionServiceStub( + google::cloud::CompletionQueue cq, Options const& options) { + auto auth = google::cloud::internal::CreateAuthenticationStrategy( + std::move(cq), options); + auto channel = auth->CreateChannel(options.get(), + internal::MakeChannelArguments(options)); + auto service_grpc_stub = + google::cloud::retail::v2::CompletionService::NewStub(channel); + std::shared_ptr stub = + std::make_shared( + std::move(service_grpc_stub), + google::longrunning::Operations::NewStub(channel)); + + if (auth->RequiresConfigureContext()) { + stub = std::make_shared(std::move(auth), + std::move(stub)); + } + stub = std::make_shared(std::move(stub)); + if (internal::Contains(options.get(), "rpc")) { + GCP_LOG(INFO) << "Enabled logging for gRPC calls"; + stub = std::make_shared( + std::move(stub), options.get(), + options.get()); + } + return stub; +} + +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END +} // namespace retail_internal +} // namespace cloud +} // namespace google diff --git a/pool/shard007/C++/0090781_tutorialswidget.cpp b/pool/shard007/C++/0090781_tutorialswidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c5b3baccdb6552d2a16c17b1a442e3af66f4c07 --- /dev/null +++ b/pool/shard007/C++/0090781_tutorialswidget.cpp @@ -0,0 +1,219 @@ +#include "tutorialswidget.h" +#include "action.h" +#include "delegates.h" +#include "pixmap.h" +#include "theme.h" + +#include "tc/settings.h" + +#include "tc/tutorials/model.h" +#include "tc/tutorials/proxymodel.h" +#include "tc/tutorials/tutorial.h" + +#include +#include +#include +#include +#include + +namespace { +const QString WidgetGroup { "TutorialsWidget/" }; +const QString HeaderStateKey { WidgetGroup + "headerState" }; +} + +namespace tc { +namespace ui { + +class TutorialsWidgetPrivate : public QObject +{ + struct ColumnInfo { + int index { -1 }; + Action* hideAction { nullptr }; + }; + + Q_DECLARE_PUBLIC(TutorialsWidget) + TutorialsWidget* const q_ptr { nullptr }; + + QList m_dockToolBarAction; + QList m_appToolBarAction; + + QTreeView* m_view { nullptr }; + QMap m_columns; + QMenu* m_hideColumnsMenu { nullptr }; + + tutorials::Model* m_model { nullptr }; + tutorials::ProxyModel* m_proxyModel { nullptr }; + + explicit TutorialsWidgetPrivate(TutorialsWidget* ptr) + : q_ptr(ptr) + , m_proxyModel(new tutorials::ProxyModel(this)) { + setupUi(); + } + + void setupUi() { + Q_Q(TutorialsWidget); + + m_view = new QTreeView; + m_view->setFrameStyle(QFrame::NoFrame); + m_view->setSelectionMode(QAbstractItemView::ExtendedSelection); + m_view->setModel(m_proxyModel); + m_view->setSelectionBehavior(QAbstractItemView::SelectRows); + m_view->setSortingEnabled(true); + + m_view->setItemDelegateForColumn(tutorials::Model::Rating, new RatingDelegate(this)); + m_view->setItemDelegateForColumn(tutorials::Model::Size, new FileSizeDelegate(this)); + m_view->setItemDelegateForColumn(tutorials::Model::Duration, new DurationDelegate(this)); + + connect(m_view->selectionModel(), &QItemSelectionModel::selectionChanged, this, &TutorialsWidgetPrivate::onSelectionChanged); + + auto layout = new QVBoxLayout; + layout->setMargin(0); + layout->setSpacing(0); + layout->addWidget(m_view); + + q->setLayout(layout); + + q->setWindowTitle(tr("Tutorials")); + q->setWindowIcon(Pixmap::fromFont(Theme::MaterialFont, "\uE53B", Theme::MainToolBarIconSize, Theme::MainToolBarIconColor)); + + auto action = new Action(q); + action->set_instantPopup(true); + action->setIcon(Pixmap::fromFont(Theme::AwesomeFont, "\uF141", Theme::DockToolBarIconSize, Theme::DockToolBarIconColor)); + m_hideColumnsMenu = new QMenu(q); + action->setMenu(m_hideColumnsMenu); + + m_dockToolBarAction.append(action); + } + + QSet selectedTutorials() const { + QSet selection; + foreach (QModelIndex index, m_view->selectionModel()->selectedIndexes()) { + int row = m_proxyModel->mapToSource(index).row(); + selection << m_model->tutorial(row); + } + return selection; + } + + void onSelectionChanged(const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/) { + Q_Q(TutorialsWidget); + q->update_selection(selectedTutorials()); + } + + void setModel(tutorials::Model* model) { + Q_Q(TutorialsWidget); + + if (model == m_model) + return; + + m_model = model; + m_proxyModel->setSourceModel(m_model); + setColumnHideMenu(); + } + + void saveSettings(Settings &settings) const { + settings.setValue(HeaderStateKey, m_view->header()->saveState()); + } + + void loadSettings(const Settings &settings) { + m_view->header()->restoreState(settings.value(HeaderStateKey).toByteArray()); + restoreColumnHideMenuState(); + } + + void setColumnHideMenu() { + m_hideColumnsMenu->clear(); + m_columns.clear(); + + auto showAllAction = new Action(this); + showAllAction->setText(tr("All")); + showAllAction->setToolTip(tr("Show all columns")); + m_hideColumnsMenu->addAction(showAllAction); + m_hideColumnsMenu->addSeparator(); + + for (int i = 0; i < m_model->columns().size(); ++i) { + auto text = m_model->columns()[i]; + auto action = new Action(this); + action->setText(text); + action->setCheckable(true); + action->setChecked(true); + connect(action, &QAction::toggled, [=](bool value) { m_view->setColumnHidden(i, !value);} ); + m_columns[text] = { i, action}; + } + + connect(showAllAction, &Action::triggered, [=](){ + for(auto c: m_columns) { + if (!c.hideAction->isChecked()) + c.hideAction->setChecked(true); + } + }); + + auto keys = m_columns.keys(); + keys.sort(); + + for(auto k: keys) { + m_hideColumnsMenu->addAction(m_columns[k].hideAction); + } + } + + void restoreColumnHideMenuState() { + if (!m_model) + return; + + if (m_columns.size() != m_view->header()->count()) { + qWarning() << "failed to restore the state of the tutorials view menus"; + return; + } + + for (auto c: m_columns) { + c.hideAction->setChecked(!m_view->header()->isSectionHidden(c.index)); + } + } +}; + +TutorialsWidget::TutorialsWidget(QWidget *parent) + : DockableWidget(parent) + , d_ptr(new TutorialsWidgetPrivate(this)) +{ +} + +TutorialsWidget::~TutorialsWidget() +{ +} + +QList TutorialsWidget::dockToolBarActions() const +{ + Q_D(const TutorialsWidget); + return d->m_dockToolBarAction; +} + +QList TutorialsWidget::appToolBarActions() const +{ + Q_D(const TutorialsWidget); + return d->m_appToolBarAction; +} + +void TutorialsWidget::saveSettings(Settings &settings) const +{ + Q_D(const TutorialsWidget); + d->saveSettings(settings); +} + +void TutorialsWidget::loadSettings(const Settings &settings) +{ + Q_D(TutorialsWidget); + d->loadSettings(settings); +} + +void TutorialsWidget::setModel(tutorials::Model *model) +{ + Q_D(TutorialsWidget); + d->setModel(model); +} + +tutorials::ProxyModel *TutorialsWidget::proxyModel() const +{ + Q_D(const TutorialsWidget); + return d->m_proxyModel; +} + +} // namespace ui +} // namespace tc diff --git a/pool/shard007/C++/0090784_main.cpp b/pool/shard007/C++/0090784_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6271730d052808266aa63b17dd0ccddd0a9de410 --- /dev/null +++ b/pool/shard007/C++/0090784_main.cpp @@ -0,0 +1,27 @@ +#include + +using namespace std; + +void foo(int a1,int a2,int a3,int a4,int a5) +{ + cout << "foo:" + << a1 << "," << a2 << "," << a3 << "," << a4 << "," << a5 + << endl; +} + +int main() +{ + auto f = [](int a1){ + return [=](int a2){ + return [=](int a3){ + return [=](int a4){ + return [=](int a5){ + foo(a1,a2,a3,a4,a5); + }; + }; + }; + }; + }; + + f(1)(2)(3)(4)(5); +} diff --git a/pool/shard007/C++/0090790_MSResponse.cpp b/pool/shard007/C++/0090790_MSResponse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6c2b1c1ae6616646b466ef617a0f1f7e70455704 --- /dev/null +++ b/pool/shard007/C++/0090790_MSResponse.cpp @@ -0,0 +1,161 @@ +/* $Id: MSResponse.cpp 397613 2013-04-29 16:10:52Z grichenk $ + * =========================================================================== + * + * PUBLIC DOMAIN NOTICE + * National Center for Biotechnology Information + * + * This software/database is a "United States Government Work" under the + * terms of the United States Copyright Act. It was written as part of + * the author's official duties as a United States Government employee and + * thus cannot be copyrighted. This software/database is freely available + * to the public for use. The National Library of Medicine and the U.S. + * Government have not placed any restriction on its use or reproduction. + * + * Although all reasonable efforts have been taken to ensure the accuracy + * and reliability of the software and data, the NLM and the U.S. + * Government do not and cannot warrant the performance or results that + * may be obtained by using this software or data. The NLM and the U.S. + * Government disclaim all warranties, express or implied, including + * warranties of performance, merchantability or fitness for any particular + * purpose. + * + * Please cite the author in any work or product based on this material. + * + * =========================================================================== + * + * Author: ....... + * + * File Description: + * ....... + * + * Remark: + * This code was originally generated by application DATATOOL + * using the following specifications: + * 'omssa.asn'. + */ + +// standard includes +#include + +// generated includes +#include + +// generated classes + +BEGIN_NCBI_SCOPE + +BEGIN_objects_SCOPE // namespace ncbi::objects:: + +// destructor +CMSResponse::~CMSResponse(void) +{ +} + +/////////////////////////////////////////////////////////////////// +// interfaces implementation for Print .csv +/////////////////////////////////////////////////////////////////// +string CMSResponse::CSVString(const string& in) +{ + + string retval; + retval = NStr::Replace(in, "\"", "\"\""); + if(retval.find_first_of(",\"") < retval.size()) retval = "\"" + retval + "\""; + return retval; +} + +void CMSResponse::PrintCSV(ostream& os, CRef ModSet) +{ + if(!CanGetHitsets() ) return; + + os.precision(15); + + os << "Spectrum number, Filename/id, Peptide, E-value, Mass, gi, Accession, Start, Stop, Defline, Mods, Charge, Theo Mass, P-value, NIST score" << endl; + // read out hits + + CMSResponse::THitsets::const_iterator iHits; + iHits = GetHitsets().begin(); + double fMZ_scale = CanGetScale() ? GetScale() : 100.0; + for(; iHits != GetHitsets().end(); iHits++) + { + CRef< CMSHitSet > HitSet = *iHits; + if( HitSet-> CanGetError() && HitSet->GetError() == eMSHitError_notenuffpeaks) + { + continue; + } + + CRef< CMSHits > Hit; + CMSHitSet::THits::const_iterator iHit; + CMSHits::TPephits::const_iterator iPephit; + for(iHit = HitSet->GetHits().begin(); iHit != HitSet->GetHits().end(); iHit++) + { + string id; + if (HitSet->GetIds().begin() != HitSet->GetIds().end()) + id = *(HitSet->GetIds().begin()); + double NISTScore (0.0L); + if ((*iHit)->CanGetScores()) { + ITERATE(CMSHits::TScores, iNISTScore, (*iHit)->GetScores()) { + if((*iNISTScore)->GetName() == "NIST Score") + NISTScore = (*iNISTScore)->GetValue(); + } + } + + for(iPephit = (*iHit)->GetPephits().begin(); iPephit != (*iHit)->GetPephits().end(); iPephit++) + { + string PepString; + (*iHit)->MakePepString(PepString); + string ModString; + (*iHit)->MakeModString(ModString, ModSet); + string Accession(""); + if((*iPephit)->CanGetAccession()) + Accession = CSVString((*iPephit)->GetAccession()); + TGi Gi = ZERO_GI; + if((*iPephit)->CanGetGi()) + Gi = (*iPephit)->GetGi(); + os << HitSet->GetNumber() << "," << CSVString(id) << "," << + CSVString(PepString) << "," << + (*iHit)->GetEvalue() << "," << (*iHit)->GetMass()/fMZ_scale << "," << + Gi << "," << Accession << "," << + (*iPephit)->GetStart() + 1 << "," << (*iPephit)->GetStop() + 1 << "," << + CSVString((*iPephit)->GetDefline()) << "," << CSVString(ModString) << + "," << (*iHit)->GetCharge() << + "," << (*iHit)->GetTheomass()/fMZ_scale << + "," << (*iHit)->GetPvalue() << + "," << NISTScore << endl; + } + } + } +} +// ------------------------ END Print .csv --------------------------------- + + +void +CMSResponse::GetOidsBelowThreshold(TOidSet& OidSet, + const double Threshold) const +{ + ITERATE(THitsets, iHitSet, GetHitsets()) { + ITERATE(CMSHitSet::THits, iHit, (*iHitSet)->GetHits()) { + ITERATE(CMSHits::TPephits, iPepHit, (*iHit)->GetPephits()) { + if((*iHit)->GetEvalue() <= Threshold) { + OidSet.insert((*iPepHit)->GetOid()); + } + } + } + } +} + + +CRef +CMSResponse::FindHitSet(const int Number) const +{ + ITERATE(THitsets, iHitSet, GetHitsets()) { + if((*iHitSet)->GetNumber() == Number) return *iHitSet; + } + return null; +} + + +END_objects_SCOPE // namespace ncbi::objects:: + +END_NCBI_SCOPE + +/* Original file checksum: lines: 65, chars: 1890, CRC32: 485ecdcb */ diff --git a/pool/shard007/C++/0090805_cameraClient.cpp b/pool/shard007/C++/0090805_cameraClient.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f52c57de8328b39596fec23418c6cd9f73b16f71 --- /dev/null +++ b/pool/shard007/C++/0090805_cameraClient.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (C) 1997-2016 JDE Developers Team + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see http://www.gnu.org/licenses/. + * Authors : + * Aitor Martinez Fernandez + */ +#include +#include +#ifdef JDERROS +#include +#endif + +namespace Comm { + +CameraClient* +getCameraClient(Comm::Communicator* jdrc, std::string prefix){ + CameraClient* client = 0; + + + int server = jdrc->getConfig().asIntWithDefault(prefix+".Server", 0); + switch (server){ + case 0: + { + std::cout << "Camera disabled" << std::endl; + break; + } + case 1: + { + std::cout << "Receiving Image from ICE interfaces" << std::endl; + CameraIceClient* cl; + cl = new CameraIceClient(jdrc, prefix); + cl->start(); + client = (Comm::CameraClient*) cl; + break; + } + case 2: + { + #ifdef JDERROS + std::cout << "Receiving Image from ROS messages" << std::endl; + std::string nodeName; + nodeName = jdrc->getConfig().asStringWithDefault(prefix+".Name", "LaserNode"); + std::string topic; + topic = jdrc->getConfig().asStringWithDefault(prefix+".Topic", ""); + ListenerCamera* lc; + lc = new ListenerCamera(0, nullptr, nodeName, topic); + lc->start(); + client = (Comm::CameraClient*) lc; + #else + throw "ERROR: ROS is not available"; + #endif + + break; + } + default: + { + std::cerr << "Wrong " + prefix+".Server property" << std::endl; + break; + } + + } + + return client; + + +} + +}//NS \ No newline at end of file diff --git a/pool/shard007/C++/0090814_testMicroStats.cpp b/pool/shard007/C++/0090814_testMicroStats.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ee528c688ce38a3ea061b4de73149358e807567 --- /dev/null +++ b/pool/shard007/C++/0090814_testMicroStats.cpp @@ -0,0 +1,88 @@ +#include "MicroStats.h" +#include +#include + +#if defined(__GNUC__) && defined(__x86_64__) +#include +uint64_t now() { + return __rdtsc(); +} +#else +#include +uint64_t now() { + using std::chrono; + return duration_cast( + system_clock::now().time_since_epoch()).count(); +} +#endif + +template< uint32_t N > +void summary( const MicroStats& ms ) +{ + constexpr double sd2 = 0.022750131948178987; + constexpr double sd1 = 0.15865525393145702; + std::cout << "10pct:" << ms.percentile(10) + << " -2SD:" << ms.percentile(100*sd2) + << " -1SD:" << ms.percentile(100*sd1) + << " 50pct:" << ms.percentile(50) + << " +1SD:" << ms.percentile(100-100*sd1) + << " +2SD:" << ms.percentile(100-200*sd2) + << " 90pct:" << ms.percentile(90) + << " 99pct:" << ms.percentile(99) + << " Stdev:" << (ms.percentile(100-100*sd1) - ms.percentile(100*sd1))/2 + << " Stdev:" << (ms.percentile(100-100*sd2) - ms.percentile(100*sd2))/4 + << std::endl; +} + +int main( int argc, char* argv[] ) +{ + MicroStats<3> ms; + + // Single point distribution + for ( uint32_t j=0; j<1000; ++j ) { + ms.add( 1000 ); + } + summary( ms ); + ms.clear(); + + // Uniform distribution over [0,10000] + for ( uint32_t j=0; j<10000; ++j ) { + ms.add( j ); + } + summary( ms ); + ms.clear(); + + // Random distribution + MicroStats<4> tms; + std::default_random_engine generator; + std::normal_distribution distribution(50000.0,2500.0); + for ( uint32_t j=0; j<10000000; ++j ) { + double number = distribution(generator); + if ( number<0 ) number=0; + uint64_t unumber = ::llrint( number ); + uint64_t t0 = now(); + if ( t0>0 ) { + ms.add( unumber ); + uint64_t t1 = now(); + if ( t1>t0 ) tms.add( t1-t0 ); + } + } + summary( ms ); + ms.clear(); + + std::cout << "Cost of MicroStats (measure+bin)" << std::endl; + summary( tms ); + tms.clear(); + + + for ( uint32_t j=0; j<10000000; ++j ) { + uint64_t t0 = now(); + if ( t0>0 ) { + //asm __volatile__( "nop" ); + uint64_t t1 = now(); + if ( t1>t0 ) tms.add( t1-t0 ); + } + } + std::cout << "Cost of measuring only" << std::endl; + summary( tms ); +} diff --git a/pool/shard007/C++/0090817_mbed_pinmap_default.cpp b/pool/shard007/C++/0090817_mbed_pinmap_default.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1290b8d58ed3bb5f358f386613882129ab1f6388 --- /dev/null +++ b/pool/shard007/C++/0090817_mbed_pinmap_default.cpp @@ -0,0 +1,109 @@ +/* mbed Microcontroller Library + * Copyright (c) 2019 ARM Limited + * SPDX-License-Identifier: Apache-2.0 + * + * 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 +#include "hal/pinmap.h" +#include "platform/mbed_toolchain.h" +#include "platform/mbed_assert.h" +#include "device.h" +#include "hal/serial_api.h" +#include "hal/PinNameAliases.h" + +//*** Common form factors *** +#if defined (TARGET_FF_ARDUINO) || (TARGET_FF_ARDUINO_UNO) + +static const PinName ff_arduino_uno_pins[] = { + ARDUINO_UNO_D0, ARDUINO_UNO_D1, ARDUINO_UNO_D2, ARDUINO_UNO_D3, ARDUINO_UNO_D4, ARDUINO_UNO_D5, ARDUINO_UNO_D6, ARDUINO_UNO_D7, + ARDUINO_UNO_D8, ARDUINO_UNO_D9, ARDUINO_UNO_D10, ARDUINO_UNO_D11, ARDUINO_UNO_D12, ARDUINO_UNO_D13, ARDUINO_UNO_D14, ARDUINO_UNO_D15, + ARDUINO_UNO_A0, ARDUINO_UNO_A1, ARDUINO_UNO_A2, ARDUINO_UNO_A3, ARDUINO_UNO_A4, ARDUINO_UNO_A5 +}; + +static const char *ff_arduino_uno_names[] = { + "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", + "D8", "D9", "D10", "D11", "D12", "D13", "D14", "D15", + "A0", "A1", "A2", "A3", "A4", "A5" +}; + +static const PinList ff_arduino_uno_list = { + sizeof(ff_arduino_uno_pins) / sizeof(ff_arduino_uno_pins[0]), + ff_arduino_uno_pins +}; + +static_assert(sizeof(ff_arduino_uno_pins) / sizeof(ff_arduino_uno_pins[0]) == sizeof(ff_arduino_uno_names) / sizeof(ff_arduino_uno_names[0]), + "Arrays must have the same length"); + +const PinList *pinmap_ff_arduino_uno_pins() +{ + return &ff_arduino_uno_list; +} + +const char *pinmap_ff_arduino_uno_pin_to_string(PinName pin) +{ + if (pin == (PinName)NC) { + return "NC"; + } + for (size_t i = 0; i < ff_arduino_uno_list.count; i++) { + if (ff_arduino_uno_list.pins[i] == pin) { + return ff_arduino_uno_names[i]; + } + } + return "Unknown"; +} + +#endif // defined (TARGET_FF_ARDUINO) || (TARGET_FF_ARDUINO_UNO) + +//*** Default restricted pins *** +MBED_WEAK const PinList *pinmap_restricted_pins() +{ + static const PinName pins[] = { + CONSOLE_TX, CONSOLE_RX + }; + static const PinList pin_list = { + sizeof(pins) / sizeof(pins[0]), + pins + }; + return &pin_list; +} + +//*** Default restricted gpio pins *** +// GPIO pins are special case because there are no pin-maps for GPIO +MBED_WEAK const PinList *pinmap_gpio_restricted_pins() +{ + static const PinList pin_list = { + 0, + 0 + }; + return &pin_list; +} + +//*** Default restricted peripherals *** +#if DEVICE_SERIAL +MBED_WEAK const PeripheralList *pinmap_uart_restricted_peripherals() +{ + static const int stdio_uart = pinmap_peripheral(CONSOLE_TX, serial_tx_pinmap()); + + static const int peripherals[] = { + stdio_uart + }; + + static const PeripheralList peripheral_list = { + sizeof peripherals / sizeof peripherals[0], + peripherals + }; + return &peripheral_list; +} +#endif diff --git a/pool/shard007/C++/0090835_database.cpp b/pool/shard007/C++/0090835_database.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bef959bbf35ffedda7d904084d464b821df085ea --- /dev/null +++ b/pool/shard007/C++/0090835_database.cpp @@ -0,0 +1,62 @@ +#include "database.h" + +Database::Database(){ +//Database::Database(): Sqlite3_base(DEFAULT_DATABASE_PATH){ + debug("creating database"); +} + + +Database::~Database(){ + debug("destroying database.."); +} + +void Database::init_db(){ + debug("initializing database [%s]..",Sqlite3_base::get_database_path()); + remove_db(); // for clear for testing + + //create tables + //creat table for mids + exec_s(C_METAHEADS); + exec_s(C_CHUNKS); + exec_s(IDX_CHUNKS_BID); + exec_s(IDX_CHUNKS_BID_CID); +} + +void Database::get_all_metaheads(vector& metaheads){ + debug("getting all.."); + Result_ptr res = exec_q(Q_ALL_METAHEADS); + while(res->next()) { + Metahead tmp(res->get_id(2),res->get_string(1)); + metaheads.emplace_back(tmp); + } +} + +bool Database::get_metahead(const Id& mid, Metahead& metahead){ + debug("getting metahead.."); + Result_ptr res = exec_q(Q_METAHEAD,mid); + if(!res->next())return false; + metahead.mid = mid; + metahead.tags = res->get_string(0); + metahead.bid = res->get_id(1); + return true; +} + +void Database::get_mids_by_tag_pattern(const string& pattern, vector& mids){ + Result_ptr res = exec_q(Q_MIDS_BY_TAG_PATTERN,pattern); + while(res->next()) mids.emplace_back(res->get_id(0)); +} + +bool Database::get_chunk(const Id &bid, const Id &cid, size_t &size, size_t &slot){ + Result_ptr res = exec_q(Q_CHUNK, bid, cid); + if(!res->next()) return false; + size = res->get_size_t(0); + slot = res->get_size_t(1); + return true; +} + +void Database::get_random_metaheads(const int n, vector& metaheads){ + Result_ptr res = exec_q(Q_RANDOM_METAHEADS, n); + while(res->next()) { + metaheads.emplace_back(res->get_id(2), res->get_string(1)); + } +} diff --git a/pool/shard007/C++/0090838_main.cpp b/pool/shard007/C++/0090838_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9a24a6496292b8367878dc25afebcbec303af720 --- /dev/null +++ b/pool/shard007/C++/0090838_main.cpp @@ -0,0 +1,109 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt Charts module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 or (at your option) any later version +** approved by the KDE Free Qt Foundation. The licenses are as published by +** the Free Software Foundation and appearing in the file LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QT_CHARTS_USE_NAMESPACE + +int main(int argc, char *argv[]) +{ + QApplication a(argc, argv); + qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime())); + + //![1] + QLineSeries *series = new QLineSeries(); + //![1] + + //![2] + // data from http://www.swpc.noaa.gov/ftpdir/weekly/RecentIndices.txt + // http://www.swpc.noaa.gov/ftpdir/weekly/README + // http://www.weather.gov/disclaimer + QFile sunSpots(":sun"); + if (!sunSpots.open(QIODevice::ReadOnly | QIODevice::Text)) { + return 1; + } + + QTextStream stream(&sunSpots); + while (!stream.atEnd()) { + QString line = stream.readLine(); + if (line.startsWith("#") || line.startsWith(":")) + continue; + QStringList values = line.split(" ", QString::SkipEmptyParts); + QDateTime momentInTime; + momentInTime.setDate(QDate(values[0].toInt(), values[1].toInt() , 15)); + series->append(momentInTime.toMSecsSinceEpoch(), values[2].toDouble()); + } + sunSpots.close(); + //![2] + + //![3] + QChart *chart = new QChart(); + chart->addSeries(series); + chart->legend()->hide(); + chart->setTitle("Sunspots count (by Space Weather Prediction Center)"); + //![3] + + //![4] + QDateTimeAxis *axisX = new QDateTimeAxis; + axisX->setTickCount(10); + axisX->setFormat("MMM yyyy"); + axisX->setTitleText("Date"); + chart->addAxis(axisX, Qt::AlignBottom); + series->attachAxis(axisX); + + QValueAxis *axisY = new QValueAxis; + axisY->setLabelFormat("%i"); + axisY->setTitleText("Sunspots count"); + chart->addAxis(axisY, Qt::AlignLeft); + series->attachAxis(axisY); + //![4] + + //![5] + QChartView *chartView = new QChartView(chart); + chartView->setRenderHint(QPainter::Antialiasing); + //![5] + + //![6] + QMainWindow window; + window.setCentralWidget(chartView); + window.resize(820, 600); + window.show(); + //![6] + + return a.exec(); +} diff --git a/pool/shard007/C++/0090839_gtype.cpp b/pool/shard007/C++/0090839_gtype.cpp new file mode 100644 index 0000000000000000000000000000000000000000..591c09ee9ae302584ee669793edea9a2af3dd2b0 --- /dev/null +++ b/pool/shard007/C++/0090839_gtype.cpp @@ -0,0 +1,236 @@ +/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil; -*- */ +/* + * Copyright (c) 2008 litl, LLC + * Copyright (c) 2012 Red Hat, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include + +#include "gtype.h" + +#include +#include +#include +#include + +GWKJS_DEFINE_PROTO_ABSTRACT("GIRepositoryGType", gtype, 0); + +/* priv_from_js adds a "*", so this returns "void *" */ +GWKJS_DEFINE_PRIV_FROM_JS(void, gwkjs_gtype_class); + +static GQuark +gwkjs_get_gtype_wrapper_quark(void) +{ + static gsize once_init = 0; + static GQuark value = 0; + if (g_once_init_enter(&once_init)) { + value = g_quark_from_string("gwkjs-gtype-wrapper"); + g_once_init_leave(&once_init, 1); + } + return value; +} + +static void +gwkjs_gtype_finalize(JSObjectRef obj) +{ + GType gtype = GPOINTER_TO_SIZE(JSObjectGetPrivate(obj)); + + /* proto doesn't have a private set */ + if (G_UNLIKELY(gtype == 0)) + return; + + g_type_set_qdata(gtype, gwkjs_get_gtype_wrapper_quark(), NULL); +} + +//static JSBool +//to_string_func(JSContextRef context, +// unsigned argc, +// jsval *vp) +//{ +// JS::CallReceiver rec = JS::CallReceiverFromVp(vp); +// JSObjectRef obj = JSVAL_TO_OBJECT(rec.thisv()); +// +// GType gtype; +// gchar *strval; +// JSBool ret; +// jsval retval; +// +// gtype = GPOINTER_TO_SIZE(priv_from_js(context, obj)); +// +// if (gtype == 0) +// strval = g_strdup("[object GType prototype]"); +// else +// strval = g_strdup_printf("[object GType for '%s']", +// g_type_name(gtype)); +// ret = gwkjs_string_from_utf8(context, strval, -1, &retval); +// if (ret) +// rec.rval().set(retval); +// g_free(strval); +// return ret; +//} +// +//static JSBool +//get_name_func (JSContextRef context, +// JS::HandleObject obj, +// JS::HandleId id, +// JS::MutableHandleValue vp) +//{ +// GType gtype; +// JSBool ret; +// jsval retval; +// JS::CallReceiver rec = JS::CallReceiverFromVp(vp.address()); +// +// gtype = GPOINTER_TO_SIZE(priv_from_js(context, obj)); +// +// if (gtype == 0) { +// rec.rval().set(JSVAL_NULL); +// return TRUE; +// } else { +// ret = gwkjs_string_from_utf8(context, g_type_name(gtype), -1, &retval); +// if (ret) +// rec.rval().set(retval); +// return ret; +// } +//} +// +///* Properties */ +//JSPropertySpec gwkjs_gtype_proto_props[] = { +// { "name", 0, +// JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_SHARED, +// JSOP_WRAPPER((JSPropertyOp)get_name_func), +// JSOP_WRAPPER(JS_StrictPropertyStub) }, +// { NULL }, +//}; +// +///* Functions */ +//JSFunctionSpec gwkjs_gtype_proto_funcs[] = { +// { "toString", JSOP_WRAPPER((JSNative)to_string_func), 0, 0 }, +// { NULL } +//}; + + +JSObjectRef +gwkjs_gtype_create_gtype_wrapper (JSContextRef context, + GType gtype) +{ + JSObjectRef object; + JSObjectRef global; + + + /* put constructor for GIRepositoryGType() in the global namespace */ + global = gwkjs_get_import_global(context); + gwkjs_gtype_create_proto(context, global, "GIRepositoryGType", NULL); + + object = (JSObjectRef) g_type_get_qdata(gtype, gwkjs_get_gtype_wrapper_quark()); + if (object != NULL) + goto out; + + object = JSObjectMake(context, gwkjs_gtype_class_ref, NULL); + if (object == NULL) + goto out; + + JSObjectSetPrivate(object, GSIZE_TO_POINTER(gtype)); + g_type_set_qdata(gtype, gwkjs_get_gtype_wrapper_quark(), object); + + out: + return object; +} + +static GType +_gwkjs_gtype_get_actual_gtype (JSContextRef context, + JSObjectRef object, + int recurse) +{ + gwkjs_throw(context, " _gwkjs_gtype_get_actual_gtype not implemented"); + return G_TYPE_INVALID; +//TODO: implement +// GType gtype = G_TYPE_INVALID; +// jsval gtype_val = JSVAL_VOID; +// +// JS_BeginRequest(context); +// if (JS_InstanceOf(context, object, &gwkjs_gtype_class, NULL)) { +// gtype = GPOINTER_TO_SIZE(priv_from_js(context, object)); +// goto out; +// } +// +// /* OK, we don't have a GType wrapper object -- grab the "$gtype" +// * property on that and hope it's a GType wrapper object */ +// if (!JS_GetProperty(context, object, "$gtype", >ype_val) || +// !JSVAL_IS_OBJECT(gtype_val)) { +// +// /* OK, so we're not a class. But maybe we're an instance. Check +// for "constructor" and recurse on that. */ +// if (!JS_GetProperty(context, object, "constructor", >ype_val)) +// goto out; +// } +// +// if (recurse > 0 && JSVAL_IS_OBJECT(gtype_val)) +// gtype = _gwkjs_gtype_get_actual_gtype(context, JSVAL_TO_OBJECT(gtype_val), recurse - 1); +// +// out: +// JS_EndRequest(context); +// return gtype; +} + +GType +gwkjs_gtype_get_actual_gtype (JSContextRef context, + JSObjectRef object) +{ + /* 2 means: recurse at most three times (including this + call). + The levels are calculated considering that, in the + worst case we need to go from instance to class, from + class to GType object and from GType object to + GType value. + */ + + return _gwkjs_gtype_get_actual_gtype(context, object, 2); +} + +//JSBool +//gwkjs_typecheck_gtype (JSContextRef context, +// JSObjectRef obj, +// JSBool throw_error) +//{ +// return do_base_typecheck(context, obj, throw_error); +//} + +const char * +gwkjs_get_names_from_gtype_and_gi_info(GType gtype, + GIBaseInfo *info, + const char **constructor_name) +{ + const char *ns; + /* ns is only used to set the JSClass->name field (exposed by + * Object.prototype.toString). + * We can safely set "unknown" if there is no info, as in that case + * the name is globally unique (it's a GType name). */ + if (info) { + ns = g_base_info_get_namespace((GIBaseInfo*) info); + if (constructor_name) + *constructor_name = g_base_info_get_name((GIBaseInfo*) info); + } else { + ns = "unknown"; + if (constructor_name) + *constructor_name = g_type_name(gtype); + } + return ns; +} diff --git a/pool/shard007/C++/0090840_modifyconstraintteacheractivitytagmaxhourscontinuouslyform.cpp b/pool/shard007/C++/0090840_modifyconstraintteacheractivitytagmaxhourscontinuouslyform.cpp new file mode 100644 index 0000000000000000000000000000000000000000..02b30b7dc3ad54181b73d0f4343f750580810de6 --- /dev/null +++ b/pool/shard007/C++/0090840_modifyconstraintteacheractivitytagmaxhourscontinuouslyform.cpp @@ -0,0 +1,129 @@ +/*************************************************************************** + modifyconstraintteacheractivitytagmaxhourscontinuouslyform.cpp - description + ------------------- + begin : 2009 + copyright : (C) 2009 by Lalescu Liviu + email : Please see https://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address) + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software: you can redistribute it and/or modify * + * it under the terms of the GNU Affero General Public License as * + * published by the Free Software Foundation, either version 3 of the * + * License, or (at your option) any later version. * + * * + ***************************************************************************/ + +#include + +#include "modifyconstraintteacheractivitytagmaxhourscontinuouslyform.h" +#include "timeconstraint.h" + +ModifyConstraintTeacherActivityTagMaxHoursContinuouslyForm::ModifyConstraintTeacherActivityTagMaxHoursContinuouslyForm(QWidget* parent, ConstraintTeacherActivityTagMaxHoursContinuously* ctr): QDialog(parent) +{ + setupUi(this); + + okPushButton->setDefault(true); + + connect(okPushButton, SIGNAL(clicked()), this, SLOT(ok())); + connect(cancelPushButton, SIGNAL(clicked()), this, SLOT(cancel())); + + centerWidgetOnScreen(this); + restoreFETDialogGeometry(this); + + QSize tmp1=teachersComboBox->minimumSizeHint(); + Q_UNUSED(tmp1); + QSize tmp4=activityTagsComboBox->minimumSizeHint(); + Q_UNUSED(tmp4); + + this->_ctr=ctr; + + weightLineEdit->setText(CustomFETString::number(ctr->weightPercentage)); + + updateMaxHoursSpinBox(); + + maxHoursSpinBox->setValue(ctr->maxHoursContinuously); + + teachersComboBox->clear(); + int i=0, j=-1; + for(int k=0; kaddItem(tch->name); + if(tch->name==this->_ctr->teacherName) + j=i; + } + assert(j>=0); + teachersComboBox->setCurrentIndex(j); + + j=-1; + activityTagsComboBox->clear(); + for(int k=0; kaddItem(at->name); + if(at->name==this->_ctr->activityTagName) + j=k; + } + assert(j>=0); + activityTagsComboBox->setCurrentIndex(j); + + constraintChanged(); +} + +ModifyConstraintTeacherActivityTagMaxHoursContinuouslyForm::~ModifyConstraintTeacherActivityTagMaxHoursContinuouslyForm() +{ + saveFETDialogGeometry(this); +} + +void ModifyConstraintTeacherActivityTagMaxHoursContinuouslyForm::updateMaxHoursSpinBox(){ + maxHoursSpinBox->setMinimum(1); + maxHoursSpinBox->setMaximum(gt.rules.nHoursPerDay); +} + +void ModifyConstraintTeacherActivityTagMaxHoursContinuouslyForm::constraintChanged() +{ +} + +void ModifyConstraintTeacherActivityTagMaxHoursContinuouslyForm::ok() +{ + double weight; + QString tmp=weightLineEdit->text(); + weight_sscanf(tmp, "%lf", &weight); + if(weight<0.0 || weight>100.0){ + QMessageBox::warning(this, tr("FET information"), + tr("Invalid weight (percentage)")); + return; + } + + int max_hours=maxHoursSpinBox->value(); + + QString teacher_name=teachersComboBox->currentText(); + int teacher_ID=gt.rules.searchTeacher(teacher_name); + if(teacher_ID<0){ + QMessageBox::warning(this, tr("FET warning"), + tr("Invalid teacher")); + return; + } + + QString activityTagName=activityTagsComboBox->currentText(); + int ati=gt.rules.searchActivityTag(activityTagName); + if(ati<0){ + QMessageBox::warning(this, tr("FET warning"), tr("Invalid activity tag")); + return; + } + + this->_ctr->weightPercentage=weight; + this->_ctr->maxHoursContinuously=max_hours; + this->_ctr->teacherName=teacher_name; + this->_ctr->activityTagName=activityTagName; + + gt.rules.internalStructureComputed=false; + setRulesModifiedAndOtherThings(>.rules); + + this->close(); +} + +void ModifyConstraintTeacherActivityTagMaxHoursContinuouslyForm::cancel() +{ + this->close(); +} diff --git a/pool/shard007/C++/0090846_LoadFrame.cc b/pool/shard007/C++/0090846_LoadFrame.cc new file mode 100644 index 0000000000000000000000000000000000000000..c0fb022869f44dcec12e8583b335a64a83a10ad5 --- /dev/null +++ b/pool/shard007/C++/0090846_LoadFrame.cc @@ -0,0 +1,107 @@ +/************************************************************************* + * * + * Copyright (c) 2011 Hirokazu Odaka * + * * + * This program is free software: you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation, either version 3 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program. If not, see . * + * * + *************************************************************************/ + +#include "LoadFrame.hh" +#include +#include "FrameData.hh" +#include "ConstructDetector.hh" +#include "DetectorSystem.hh" +#include "VRealDetectorUnit.hh" + +using namespace anlnext; + +namespace comptonsoft { + +LoadFrame::LoadFrame() +{ +} + +ANLStatus LoadFrame::mod_define() +{ + define_parameter("byte_order", &mod_class::byte_order_); + define_parameter("odd_row_pixel_shift", &mod_class::odd_row_pixel_shift_); + define_parameter("start_position", &mod_class::start_position_); + define_parameter("read_direction_x", &mod_class::read_direction_x_); + define_parameter("detector_id", &mod_class::detector_id_); + define_parameter("files", &mod_class::files_); + + return AS_OK; +} + +ANLStatus LoadFrame::mod_initialize() +{ + ConstructDetector* detectorOwner; + get_module_NC("ConstructDetector", &detectorOwner); + VRealDetectorUnit* detector = detectorOwner->getDetectorManager()->getDetectorByID(detector_id_); + if (detector == nullptr) { + std::cout << "Detector " << detector_id_ << " does not exist." << std::endl; + return AS_QUIT; + } + + if (detector->hasFrameData()) { + frame_ = detector->getFrameData(); + frame_->setByteOrder(byte_order_); + frame_->setOddRowPixelShift(odd_row_pixel_shift_); + frame_->setStartPosition(FrameData::CornerID(start_position_)); + frame_->setReadDirectionX(read_direction_x_); + } + else { + std::cout << "Detector does not have a frame." << std::endl; + return AS_QUIT; + } + + return AS_OK; +} + +ANLStatus LoadFrame::mod_analyze() +{ + if (isDone()) { + return AS_QUIT; + } + + const std::size_t fileIndex = get_loop_index(); + const std::string filename = files_[fileIndex]; + std::cout << "[LoadFrame] filename: " << filename << std::endl; + + frame_->setFrameID(fileIndex); + bool status = frame_->load(filename); + if (!status) { + return AS_ERROR; + } + + return AS_OK; +} + +void LoadFrame::addFile(const std::string& filename) +{ + files_.push_back(filename); +} + +bool LoadFrame::hasFile(const std::string& filename) const +{ + return (std::find(files_.begin(), files_.end(), filename) != files_.end()); +} + +bool LoadFrame::isDone() const +{ + const std::size_t fileIndex = get_loop_index(); + return (fileIndex == files_.size()); +} + +} /* namespace comptonsoft */ diff --git a/pool/shard007/C++/0090851_References.cpp b/pool/shard007/C++/0090851_References.cpp new file mode 100644 index 0000000000000000000000000000000000000000..37160cdd1bb1e4f80bde1b4643af8bc808a6eef5 --- /dev/null +++ b/pool/shard007/C++/0090851_References.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +namespace facebook { +namespace jni { + +JniLocalScope::JniLocalScope(JNIEnv* env, jint capacity) + : env_(env) { + hasFrame_ = false; + auto pushResult = env->PushLocalFrame(capacity); + FACEBOOK_JNI_THROW_EXCEPTION_IF(pushResult < 0); + hasFrame_ = true; +} + +JniLocalScope::~JniLocalScope() { + if (hasFrame_) { + env_->PopLocalFrame(nullptr); + } +} + +namespace internal { + +// Default implementation always returns true. +// Platform-specific sources can override this. +bool doesGetObjectRefTypeWork() __attribute__ ((weak)); +bool doesGetObjectRefTypeWork() { + return true; +} + +} + +} +} diff --git a/pool/shard007/C++/0090868_cuoidmap.cc b/pool/shard007/C++/0090868_cuoidmap.cc new file mode 100644 index 0000000000000000000000000000000000000000..bae5cf44d797e85deb8d1380aa3e001aecf981d9 --- /dev/null +++ b/pool/shard007/C++/0090868_cuoidmap.cc @@ -0,0 +1,198 @@ +/*************************************************************************** +** (C) 2006 by Sanjay Nair +** sanjaysn usc edu +****************************************************************************/ + +#include "cglobal.h" +#include +#include "cuoidmap.h" +#include "cmutexlocker.h" +#include "cexception.h" +#include "cutil.h" + +/*! + Constructs a uoid map +*/ +CUoidMap::CUoidMap() {} + +/*! + Deletes the uoid map +*/ +CUoidMap::~CUoidMap() {} + +/*! + Adds a uoid to the uoid list. + Returns true if the item is added. Else false. + If in the list, it throws exception +*/ +bool CUoidMap::add( + const UCharBuffer &b, const string &nodeid, uint curTime) +{ + errorIfInvalidBuffer(b); + return add(CUtil::getHexStr(b), nodeid, curTime); +} + +/*! + Adds a uoid to the uoid list. + Returns true if the item is added. Else false. + If in the list, it throws exception +*/ +bool CUoidMap::add( + const string &uoid, const string &nodeid, uint curTime) +{ + bool bAdded = false; + CMutexLocker m(&_mutex); + if (! contains_p(uoid)) { + add_p(uoid, nodeid, curTime); + bAdded = true; + } + return bAdded; +} + +/*! + \internal +*/ +void CUoidMap::add_p( + const string &uoid, const string &nodeid, uint curTime) +{ + errorIfItemPresent(uoid); + _uMap[uoid] = nodeid; + + if (_tMap.find(curTime) == _tMap.end()) { + StringVector v; + _tMap[curTime] = v; + } + StringVector *sv = &(_tMap[curTime]); + sv->push_back(uoid); +} + +/*! + Returns true if the list contains the uoid +*/ +bool CUoidMap::contains(const UCharBuffer &b) +{ + errorIfInvalidBuffer(b); + return contains(CUtil::getHexStr(b)); +} + +/*! + Returns true if the list contains the uoid +*/ +bool CUoidMap::contains(const string &uoid) +{ + CMutexLocker m(&_mutex); + return contains_p(uoid); +} + +/*! + \internal + Will not lock the object +*/ +bool CUoidMap::contains_p(const string &uoid) const +{ + return (_uMap.find(uoid) != _uMap.end()); +} + +/*! + Returns nodeid if it is in the list. + Otherwise throws exception +*/ +string CUoidMap::getNodeId(const UCharBuffer &b) +{ + errorIfInvalidBuffer(b); + return getNodeId(CUtil::getHexStr(b)); +} + +/*! + Returns nodeid if it is in the list. + Otherwise throws exception. +*/ +string CUoidMap::getNodeId(const string &uoid) +{ + CMutexLocker m(&_mutex); + errorIfItemNotPresent(uoid); + return _uMap[uoid]; +} + +/*! + Cleans up the expired items that're + in the uoid map. +*/ +void CUoidMap::cleanupExpired(uint curTime, uint duration) +{ + CMutexLocker m(&_mutex); + + if (_tMap.size() > 0) { + TimeUoidMap::iterator it; + + for (it=_tMap.begin(); it != _tMap.end(); it++) { + uint pastTime = it->first; + if (CUtil::isElapsed(pastTime, curTime, duration)) { + cleanupExpired_p(it->second); + _tMap.erase(it); + } else { + break; + } + } + } +} + +/*! + Cleans up the items in the time map +*/ +void CUoidMap::cleanupExpired_p(const StringVector &p) +{ + if (p.size() > 0) { + for (uint i=0; i +#include + +#include + +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +namespace Aws +{ +namespace MediaConnect +{ +namespace Model +{ + +SetSourceRequest::SetSourceRequest() : + m_decryptionHasBeenSet(false), + m_descriptionHasBeenSet(false), + m_entitlementArnHasBeenSet(false), + m_ingestPort(0), + m_ingestPortHasBeenSet(false), + m_maxBitrate(0), + m_maxBitrateHasBeenSet(false), + m_maxLatency(0), + m_maxLatencyHasBeenSet(false), + m_nameHasBeenSet(false), + m_protocol(Protocol::NOT_SET), + m_protocolHasBeenSet(false), + m_streamIdHasBeenSet(false), + m_vpcInterfaceNameHasBeenSet(false), + m_whitelistCidrHasBeenSet(false) +{ +} + +SetSourceRequest::SetSourceRequest(JsonView jsonValue) : + m_decryptionHasBeenSet(false), + m_descriptionHasBeenSet(false), + m_entitlementArnHasBeenSet(false), + m_ingestPort(0), + m_ingestPortHasBeenSet(false), + m_maxBitrate(0), + m_maxBitrateHasBeenSet(false), + m_maxLatency(0), + m_maxLatencyHasBeenSet(false), + m_nameHasBeenSet(false), + m_protocol(Protocol::NOT_SET), + m_protocolHasBeenSet(false), + m_streamIdHasBeenSet(false), + m_vpcInterfaceNameHasBeenSet(false), + m_whitelistCidrHasBeenSet(false) +{ + *this = jsonValue; +} + +SetSourceRequest& SetSourceRequest::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("decryption")) + { + m_decryption = jsonValue.GetObject("decryption"); + + m_decryptionHasBeenSet = true; + } + + if(jsonValue.ValueExists("description")) + { + m_description = jsonValue.GetString("description"); + + m_descriptionHasBeenSet = true; + } + + if(jsonValue.ValueExists("entitlementArn")) + { + m_entitlementArn = jsonValue.GetString("entitlementArn"); + + m_entitlementArnHasBeenSet = true; + } + + if(jsonValue.ValueExists("ingestPort")) + { + m_ingestPort = jsonValue.GetInteger("ingestPort"); + + m_ingestPortHasBeenSet = true; + } + + if(jsonValue.ValueExists("maxBitrate")) + { + m_maxBitrate = jsonValue.GetInteger("maxBitrate"); + + m_maxBitrateHasBeenSet = true; + } + + if(jsonValue.ValueExists("maxLatency")) + { + m_maxLatency = jsonValue.GetInteger("maxLatency"); + + m_maxLatencyHasBeenSet = true; + } + + if(jsonValue.ValueExists("name")) + { + m_name = jsonValue.GetString("name"); + + m_nameHasBeenSet = true; + } + + if(jsonValue.ValueExists("protocol")) + { + m_protocol = ProtocolMapper::GetProtocolForName(jsonValue.GetString("protocol")); + + m_protocolHasBeenSet = true; + } + + if(jsonValue.ValueExists("streamId")) + { + m_streamId = jsonValue.GetString("streamId"); + + m_streamIdHasBeenSet = true; + } + + if(jsonValue.ValueExists("vpcInterfaceName")) + { + m_vpcInterfaceName = jsonValue.GetString("vpcInterfaceName"); + + m_vpcInterfaceNameHasBeenSet = true; + } + + if(jsonValue.ValueExists("whitelistCidr")) + { + m_whitelistCidr = jsonValue.GetString("whitelistCidr"); + + m_whitelistCidrHasBeenSet = true; + } + + return *this; +} + +JsonValue SetSourceRequest::Jsonize() const +{ + JsonValue payload; + + if(m_decryptionHasBeenSet) + { + payload.WithObject("decryption", m_decryption.Jsonize()); + + } + + if(m_descriptionHasBeenSet) + { + payload.WithString("description", m_description); + + } + + if(m_entitlementArnHasBeenSet) + { + payload.WithString("entitlementArn", m_entitlementArn); + + } + + if(m_ingestPortHasBeenSet) + { + payload.WithInteger("ingestPort", m_ingestPort); + + } + + if(m_maxBitrateHasBeenSet) + { + payload.WithInteger("maxBitrate", m_maxBitrate); + + } + + if(m_maxLatencyHasBeenSet) + { + payload.WithInteger("maxLatency", m_maxLatency); + + } + + if(m_nameHasBeenSet) + { + payload.WithString("name", m_name); + + } + + if(m_protocolHasBeenSet) + { + payload.WithString("protocol", ProtocolMapper::GetNameForProtocol(m_protocol)); + } + + if(m_streamIdHasBeenSet) + { + payload.WithString("streamId", m_streamId); + + } + + if(m_vpcInterfaceNameHasBeenSet) + { + payload.WithString("vpcInterfaceName", m_vpcInterfaceName); + + } + + if(m_whitelistCidrHasBeenSet) + { + payload.WithString("whitelistCidr", m_whitelistCidr); + + } + + return payload; +} + +} // namespace Model +} // namespace MediaConnect +} // namespace Aws diff --git a/pool/shard007/C++/0090876_align_py.cpp b/pool/shard007/C++/0090876_align_py.cpp new file mode 100644 index 0000000000000000000000000000000000000000..27f0d2d9c885559970a4b17648abc19fd75cae33 --- /dev/null +++ b/pool/shard007/C++/0090876_align_py.cpp @@ -0,0 +1,99 @@ +#include "Python.h" +#include "align.h" + + +/* The function doc string */ +PyDoc_STRVAR(aligner3d__doc__, +"From a list of lists of xyz positions, the \n\ +number of equivalent positions, the RMSD and the dRMSD.\n\ + :param xyzs: list of lists of tuples of (x, y, z ) coordinates.\n\ + :param dcutoff: distance cutoff to consider 2 particles as equivalent \n\ + in position (nm)\n\ + :param nmodels: number of models or list of lists passed as first argument\n\ + :param verbose: prints the distance of each model to average model (in stderr)\n\ + :param getavg: return a list for each x, y, z coordinates, representing the average model\n\ +\n\ + :returns: the index of the model that is found to be the centroid\n\ +"); + + +static PyObject* aligner3d_wrapper(PyObject* self, PyObject* args) +{ + PyObject *py_xs1; + PyObject *py_ys1; + PyObject *py_zs1; + PyObject *py_xs2; + PyObject *py_ys2; + PyObject *py_zs2; + PyObject *py_zeros; + int size; + + if (!PyArg_ParseTuple(args, "OOOOOOOi", &py_xs1, &py_ys1, &py_zs1, + &py_xs2, &py_ys2, &py_zs2, &py_zeros, &size)) + return NULL; + + float **xyz1; + float **xyz2; + int zeros[size]; + int i; + + + xyz1 = new float*[size]; + xyz2 = new float*[size]; + for(int i=0; i +#include +#include +#include +#include +#include + +namespace psi { + +void PSIO::read(unsigned int unit, const char *key, char *buffer, ULI size, + psio_address start, psio_address *end) { + psio_ud *this_unit; + psio_tocentry *this_entry; + psio_address start_toc, start_data, end_data; /* global addresses */ + ULI tocentry_size; + + this_unit = &(psio_unit[unit]); + + /* Find the entry in the TOC */ + this_entry = tocscan(unit, key); + + tocentry_size = sizeof(psio_tocentry) - 2*sizeof(psio_tocentry *); + + if (this_entry == NULL) { + fprintf(stderr, "PSIO_ERROR: Can't find TOC Entry %s\n", key); + psio_error(unit, PSIO_ERROR_NOTOCENT); + } else { + + /* Compute the global starting page and offset for the data */ + start_toc = this_entry->sadd; + start_data = psio_get_address(start_toc, tocentry_size); + start_data = psio_get_global_address(start_data, start); + + /* Make sure the block starts and ends within the entry */ + if (start_data.page > this_entry->eadd.page) + psio_error(unit, PSIO_ERROR_BLKSTART); + else if ((start_data.page == this_entry->eadd.page) &&(start_data.offset + > this_entry->eadd.offset)) + psio_error(unit, PSIO_ERROR_BLKSTART); + + end_data = psio_get_address(start_data, size); + if ((end_data.page > this_entry->eadd.page)) + psio_error(unit, PSIO_ERROR_BLKEND); + else if ((end_data.page == this_entry->eadd.page) &&(end_data.offset + > this_entry->eadd.offset)) + psio_error(unit, PSIO_ERROR_BLKEND); + + /* Update end (an entry-relative address) for the caller */ + *end = psio_get_address(start, size); + } + + /* Now read the actual data from the unit */ + rw(unit, buffer, start_data, size, 0); + +#ifdef PSIO_STATS + psio_readlen[unit] += size; +#endif +} + + /*! + ** PSIO_READ(): Reads data from within a TOC entry from a PSI file. + ** + ** \param unit = The PSI unit number used to identify the file to all + ** read and write functions. + ** \param key = The TOC keyword identifying the desired entry. + ** \param buffer = The buffer to store the data as it is read. + ** \param size = The number of bytes to read. + ** \param start = The entry-relative starting page/offset of the desired data. + ** \param end = A pointer to the entry-relative page/offset for the next + ** byte after the end of the read request. + ** + ** \ingroup PSIO + */ + + int psio_read(unsigned int unit, const char *key, char *buffer, ULI size, + psio_address start, psio_address *end) { + _default_psio_lib_->read(unit, key, buffer, size, start, end); + return 1; + } + +} + diff --git a/pool/shard007/C++/0090878_file_system_helper.cc b/pool/shard007/C++/0090878_file_system_helper.cc new file mode 100644 index 0000000000000000000000000000000000000000..79186e4cbbf3821f78c8299cc20596f2f214645a --- /dev/null +++ b/pool/shard007/C++/0090878_file_system_helper.cc @@ -0,0 +1,130 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "tensorflow/core/platform/file_system_helper.h" + +#include +#include +#include + +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/core/threadpool.h" +#include "tensorflow/core/lib/io/path.h" +#include "tensorflow/core/lib/strings/str_util.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/file_system.h" +#include "tensorflow/core/platform/platform.h" + +namespace tensorflow { +namespace internal { + +namespace { + +constexpr int kNumThreads = 8; + +// Run a function in parallel using a ThreadPool, but skip the ThreadPool +// on the iOS platform due to its problems with more than a few threads. +void ForEach(int first, int last, const std::function& f) { +#if TARGET_OS_IPHONE + for (int i = first; i < last; i++) { + f(i); + } +#else + int num_threads = std::min(kNumThreads, last - first); + thread::ThreadPool threads(Env::Default(), "ForEach", num_threads); + for (int i = first; i < last; i++) { + threads.Schedule([f, i] { f(i); }); + } +#endif +} + +} // namespace + +Status GetMatchingPaths(FileSystem* fs, Env* env, const string& pattern, + std::vector* results) { + results->clear(); + // Find the fixed prefix by looking for the first wildcard. + string fixed_prefix = pattern.substr(0, pattern.find_first_of("*?[\\")); + string eval_pattern = pattern; + std::vector all_files; + string dir(io::Dirname(fixed_prefix)); + // If dir is empty then we need to fix up fixed_prefix and eval_pattern to + // include . as the top level directory. + if (dir.empty()) { + dir = "."; + fixed_prefix = io::JoinPath(dir, fixed_prefix); + eval_pattern = io::JoinPath(dir, pattern); + } + + // Setup a BFS to explore everything under dir. + std::deque dir_q; + dir_q.push_back(dir); + Status ret; // Status to return. + // children_dir_status holds is_dir status for children. It can have three + // possible values: OK for true; FAILED_PRECONDITION for false; CANCELLED + // if we don't calculate IsDirectory (we might do that because there isn't + // any point in exploring that child path). + std::vector children_dir_status; + while (!dir_q.empty()) { + string current_dir = dir_q.front(); + dir_q.pop_front(); + std::vector children; + Status s = fs->GetChildren(current_dir, &children); + // In case PERMISSION_DENIED is encountered, we bail here. + if (s.code() == tensorflow::error::PERMISSION_DENIED) { + continue; + } + ret.Update(s); + if (children.empty()) continue; + // This IsDirectory call can be expensive for some FS. Parallelizing it. + children_dir_status.resize(children.size()); + ForEach(0, children.size(), + [fs, ¤t_dir, &children, &fixed_prefix, + &children_dir_status](int i) { + const string child_path = io::JoinPath(current_dir, children[i]); + // In case the child_path doesn't start with the fixed_prefix then + // we don't need to explore this path. + if (!str_util::StartsWith(child_path, fixed_prefix)) { + children_dir_status[i] = Status(tensorflow::error::CANCELLED, + "Operation not needed"); + } else { + children_dir_status[i] = fs->IsDirectory(child_path); + } + }); + for (int i = 0; i < children.size(); ++i) { + const string child_path = io::JoinPath(current_dir, children[i]); + // If the IsDirectory call was cancelled we bail. + if (children_dir_status[i].code() == tensorflow::error::CANCELLED) { + continue; + } + // If the child is a directory add it to the queue. + if (children_dir_status[i].ok()) { + dir_q.push_back(child_path); + } + all_files.push_back(child_path); + } + } + + // Match all obtained files to the input pattern. + for (const auto& f : all_files) { + if (env->MatchPath(f, eval_pattern)) { + results->push_back(f); + } + } + return ret; +} + +} // namespace internal +} // namespace tensorflow diff --git a/pool/shard007/C++/0090889_LocalizationManager.cpp b/pool/shard007/C++/0090889_LocalizationManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..37c1057623a5e373cccc27990bff045354590b7b --- /dev/null +++ b/pool/shard007/C++/0090889_LocalizationManager.cpp @@ -0,0 +1,192 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "editor-support/cocostudio/LocalizationManager.h" +#include "platform/CCPlatformMacros.h" +#include "platform/CCFileUtils.h" +#include "editor-support/cocostudio/CSLanguageDataBinary_generated.h" + +using namespace cocostudio; +using namespace cocos2d; + +static JsonLocalizationManager* _sharedJsonLocalizationManager = nullptr; + +ILocalizationManager* JsonLocalizationManager::getInstance() +{ + if (!_sharedJsonLocalizationManager) + { + _sharedJsonLocalizationManager = new (std::nothrow) JsonLocalizationManager(); + } + + return _sharedJsonLocalizationManager; +} + +void JsonLocalizationManager::destroyInstance() +{ + if (_sharedJsonLocalizationManager != nullptr) + { + delete _sharedJsonLocalizationManager; + _sharedJsonLocalizationManager = nullptr; + } +} + +JsonLocalizationManager::JsonLocalizationManager() + :languageData(nullptr) +{ +} + +JsonLocalizationManager::~JsonLocalizationManager() +{ + CC_SAFE_DELETE(languageData); +} + +bool JsonLocalizationManager::initLanguageData(std::string file) +{ + bool result = false; + + std::string data = FileUtils::getInstance()->getStringFromFile(file); + if (!data.empty()) + { + if (!languageData) + languageData = new rapidjson::Document; + languageData->Parse(data.c_str()); + if (languageData->IsObject()) + result = true; + else + CC_SAFE_DELETE(languageData); + } + + return result; +} + +std::string JsonLocalizationManager::getLocalizationString(std::string key) +{ + std::string result = key; + + if (languageData && languageData->HasMember(key.c_str()) && + (*languageData)[key.c_str()].IsString()) + result = (*languageData)[key.c_str()].GetString(); + + return result; +} + + + +static BinLocalizationManager* _sharedBinLocalizationManager = nullptr; + +ILocalizationManager* BinLocalizationManager::getInstance() +{ + if (!_sharedBinLocalizationManager) + { + _sharedBinLocalizationManager = new (std::nothrow) BinLocalizationManager(); + } + + return _sharedBinLocalizationManager; +} + +void BinLocalizationManager::destroyInstance() +{ + if (_sharedBinLocalizationManager != nullptr) + { + delete _sharedBinLocalizationManager; + _sharedBinLocalizationManager = nullptr; + } +} + +BinLocalizationManager::BinLocalizationManager() +{ +} + +BinLocalizationManager::~BinLocalizationManager() +{ +} + +bool BinLocalizationManager::initLanguageData(std::string file) +{ + bool result = false; + languageData.clear(); + + Data buf = FileUtils::getInstance()->getDataFromFile(file); + if (!buf.isNull()) + { + auto lanSet = flatbuffers::GetLanguageSet(buf.getBytes()); + if (lanSet && lanSet->languageItems()->size() > 0) + { + result = true; + auto items = lanSet->languageItems(); + int count = items->size(); + for (int i = 0; i < count; i++) + { + auto it = items->Get(i); + std::string key = it->key()->c_str(); + std::string value = it->value()->c_str(); + if (!key.empty()) + languageData[key] = value; + } + } + } + + return result; +} + +std::string BinLocalizationManager::getLocalizationString(std::string key) +{ + std::string result = key; + + if (!languageData.empty()) + { + auto it = languageData.find(key); + if (it != languageData.end()) + result = it->second; + } + + return result; +} + + + +static bool isCurrentBinManager = true; +static ILocalizationManager* _sharedLocalizationManager = nullptr; + +ILocalizationManager* LocalizationHelper::getCurrentManager() +{ + if (!_sharedLocalizationManager) + { + _sharedLocalizationManager = BinLocalizationManager::getInstance(); + isCurrentBinManager = true; + } + + return _sharedLocalizationManager; +} + +void LocalizationHelper::setCurrentManager(ILocalizationManager* manager, bool isBinary) +{ + _sharedLocalizationManager = manager; + isCurrentBinManager = isBinary; +} + +bool LocalizationHelper::isBinManager() +{ + return isCurrentBinManager; +} \ No newline at end of file diff --git a/pool/shard007/C++/0090896_mkl_batch_matmul_op.cc b/pool/shard007/C++/0090896_mkl_batch_matmul_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..fbba4116e3b655b90b390d95da468ee91dc0ee90 --- /dev/null +++ b/pool/shard007/C++/0090896_mkl_batch_matmul_op.cc @@ -0,0 +1,252 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// See docs in ../ops/math_ops.cc. + +// This file uses oneDNN library for acceleration of Batch Matrix-Matrix +// Multiplication (MatMul) operations. We currently register this kernel only +// for oneDNN supported data types (float, bfloat16). The maximum number of +// dimensions (rank) for output tensor is 12 in oneDNN. If output tensor rank +// exceeds 12, we fall back to Eigen library based kernel. + +#define EIGEN_USE_THREADS + +#if defined(INTEL_MKL) + +#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/register_types.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/type_traits.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/kernels/batch_matmul_op_impl.h" +#include "tensorflow/core/kernels/fill_functor.h" +#include "tensorflow/core/kernels/mkl/mkl_matmul_ops_common.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/util/matmul_bcast.h" +#include "tensorflow/core/util/mkl_util.h" + +namespace tensorflow { + +typedef Eigen::ThreadPoolDevice CPUDevice; + +// The third parameter v2_bcast is set to true if we are using V2 otherwise +// we set it to false. +template +class BatchMatMulMkl : public OpKernel { + public: + explicit BatchMatMulMkl(OpKernelConstruction* context) + : OpKernel(context), eigen_batch_mm_v2_(context) { + OP_REQUIRES_OK(context, context->GetAttr("adj_x", &adj_x_)); + OP_REQUIRES_OK(context, context->GetAttr("adj_y", &adj_y_)); + } + + virtual ~BatchMatMulMkl() {} + + void Compute(OpKernelContext* ctx) override { + const Tensor& lhs = ctx->input(0); + const Tensor& rhs = ctx->input(1); + + if (!v2_bcast) { + // Using V1, so check to make sure lhs and rhs dimensions are correct and + // no broadcasting is needed. + OP_REQUIRES(ctx, lhs.dims() == rhs.dims(), + errors::InvalidArgument("lhs and rhs has different ndims: ", + lhs.shape().DebugString(), " vs. ", + rhs.shape().DebugString())); + const int ndims = lhs.dims(); + OP_REQUIRES( + ctx, ndims >= 2, + errors::InvalidArgument("lhs and rhs ndims must be >= 2: ", ndims)); + for (int i = 0; i < ndims - 2; ++i) { + OP_REQUIRES(ctx, lhs.dim_size(i) == rhs.dim_size(i), + errors::InvalidArgument( + "lhs.dim(", i, ") and rhs.dim(", i, + ") must be the same: ", lhs.shape().DebugString(), + " vs ", rhs.shape().DebugString())); + } + } else { + OP_REQUIRES( + ctx, lhs.dims() >= 2, + errors::InvalidArgument("In[0] ndims must be >= 2: ", lhs.dims())); + OP_REQUIRES( + ctx, rhs.dims() >= 2, + errors::InvalidArgument("In[1] ndims must be >= 2: ", rhs.dims())); + } + + // lhs and rhs can have different dimensions + const auto ndims_lhs = lhs.dims(); + const auto ndims_rhs = rhs.dims(); + + // Get broadcast info + MatMulBCast bcast(lhs.shape().dim_sizes(), rhs.shape().dim_sizes()); + OP_REQUIRES( + ctx, bcast.IsValid(), + errors::InvalidArgument( + "In[0] and In[1] must have compatible batch dimensions: ", + lhs.shape().DebugString(), " vs. ", rhs.shape().DebugString())); + + TensorShape out_shape = bcast.output_batch_shape(); + + auto lhs_rows = lhs.dim_size(ndims_lhs - 2); + auto lhs_cols = lhs.dim_size(ndims_lhs - 1); + auto rhs_rows = rhs.dim_size(ndims_rhs - 2); + auto rhs_cols = rhs.dim_size(ndims_rhs - 1); + + if (adj_x_) std::swap(lhs_rows, lhs_cols); + if (adj_y_) std::swap(rhs_rows, rhs_cols); + OP_REQUIRES(ctx, lhs_cols == rhs_rows, + errors::InvalidArgument( + "lhs mismatch rhs shape: ", lhs_cols, " vs. ", rhs_rows, + ": ", lhs.shape().DebugString(), " ", + rhs.shape().DebugString(), " ", adj_x_, " ", adj_y_)); + + out_shape.AddDim(lhs_rows); + out_shape.AddDim(rhs_cols); + // The maximum number of dimensions for a tensor in DNNL is 12. + OP_REQUIRES( + ctx, out_shape.dims() <= 12, + errors::InvalidArgument( + "Rank of output tensor must be <= 12, but is ", out_shape.dims(), + ". Current implementation supports upto rank 12 tensors.")); + + Tensor* out = nullptr; + OP_REQUIRES_OK(ctx, ctx->allocate_output(0, out_shape, &out)); + if (out->NumElements() == 0) { + return; + } + if (lhs.NumElements() == 0 || rhs.NumElements() == 0) { + functor::SetZeroFunctor f; + f(ctx->eigen_device(), out->flat()); + return; + } + + // Compute parameters for DNNL matmul primitive. + auto params = CreateMatMulParams(lhs.shape(), rhs.shape(), out_shape); + // Create or retrieve matmul primitive from cache. + MklMatMulPrimitive* matmul_prim = + MklMatMulPrimitiveFactory::Get( + *params, false /* value for do_not_cache */); + // Execute matmul primitive. + std::shared_ptr cpu_stream; + cpu_stream.reset(CreateStream(ctx, matmul_prim->GetEngine())); + matmul_prim->Execute(lhs.flat().data(), rhs.flat().data(), + out->flat().data(), cpu_stream); + } + + private: + bool adj_x_; + bool adj_y_; + BatchMatMulV2Op eigen_batch_mm_v2_; + + using dims = dnnl::memory::dims; + + // This method makes the rank (ndims) of input same as the output by adding + // new axes to the input. For example, if input shape is [a, b, c, d] and + // output shape is [e, f, g, h, i, j], then the reshaped input would have a + // shape of [1, 1, a, b, c, d]. + void ExpandInputDimsToOutputShape(const TensorShape& input_shape, + const TensorShape& output_shape, + dims* reshaped_dims) { + auto ndims_input = input_shape.dims(); + auto ndims_output = output_shape.dims(); + auto dim_offset = ndims_output - ndims_input; + DCHECK(dim_offset > 0); + reshaped_dims->clear(); + reshaped_dims->resize(ndims_output, 1); + auto input_dims = input_shape.dim_sizes(); + for (int dim_idx = 0; dim_idx < ndims_input; ++dim_idx) + reshaped_dims->at(dim_idx + dim_offset) = input_dims[dim_idx]; + } + + std::unique_ptr CreateMatMulParams( + const TensorShape& lhs_shape, const TensorShape& rhs_shape, + const TensorShape& out_shape) { + const auto ndims_lhs = lhs_shape.dims(); + const auto ndims_rhs = rhs_shape.dims(); + const auto ndims_out = out_shape.dims(); + auto lhs_dims = TFShapeToMklDnnDims(lhs_shape); + auto rhs_dims = TFShapeToMklDnnDims(rhs_shape); + auto out_dims = TFShapeToMklDnnDims(out_shape); + + // DNNL matmul_primitive requires ranks of inputs and output to be same. + // Create dnnl::memory::dims for inputs and output of same rank. + // It is assumed here that MatMulBCast object creates output_batch_shape as + // a conforming superset of input batch shapes, i.e., ndims_out >= + // ndims_lhs and ndims_out >= ndims_rhs. + if (ndims_lhs < ndims_out) { + ExpandInputDimsToOutputShape(lhs_shape, out_shape, &lhs_dims); + } + if (ndims_rhs < ndims_out) { + ExpandInputDimsToOutputShape(rhs_shape, out_shape, &rhs_dims); + } + + using dim = dnnl::memory::dim; + dim m; // number of rows in x + dim k; // number of columns in x + dim n; // number of columns in y + auto lhs_strides = CalculateTFStrides(lhs_dims); + auto rhs_strides = CalculateTFStrides(rhs_dims); + auto out_strides = CalculateTFStrides(out_dims); + + if (adj_x_) { + int m_idx = ndims_out - 1; + int k_idx = ndims_out - 2; + m = lhs_dims[m_idx]; + k = lhs_dims[k_idx]; + std::swap(lhs_dims[m_idx], lhs_dims[k_idx]); + lhs_strides[m_idx] = m; + lhs_strides[k_idx] = 1; + } + + if (adj_y_) { + int k_idx = ndims_out - 1; + int n_idx = ndims_out - 2; + k = rhs_dims[k_idx]; + n = rhs_dims[n_idx]; + std::swap(rhs_dims[k_idx], rhs_dims[n_idx]); + rhs_strides[k_idx] = k; + rhs_strides[n_idx] = 1; + } + return std::make_unique( + lhs_dims, rhs_dims, out_dims, lhs_strides, rhs_strides, out_strides); + } +}; + +#define REGISTER_BATCH_MATMUL_MKL(TYPE) \ + REGISTER_KERNEL_BUILDER(Name("_MklBatchMatMul") \ + .Device(DEVICE_CPU) \ + .TypeConstraint("T") \ + .Label(mkl_op_registry::kMklNameChangeOpLabel), \ + BatchMatMulMkl) + +#define REGISTER_BATCH_MATMUL_MKL_V2(TYPE) \ + REGISTER_KERNEL_BUILDER(Name("_MklBatchMatMulV2") \ + .Device(DEVICE_CPU) \ + .TypeConstraint("T") \ + .Label(mkl_op_registry::kMklNameChangeOpLabel), \ + BatchMatMulMkl) +#ifdef ENABLE_MKL +TF_CALL_float(REGISTER_BATCH_MATMUL_MKL); +TF_CALL_float(REGISTER_BATCH_MATMUL_MKL_V2); +TF_CALL_bfloat16(REGISTER_BATCH_MATMUL_MKL); +TF_CALL_bfloat16(REGISTER_BATCH_MATMUL_MKL_V2); +#endif // ENABLE_MKL + +} // end namespace tensorflow +#endif diff --git a/pool/shard007/C++/0090899_update_data_provider.cc b/pool/shard007/C++/0090899_update_data_provider.cc new file mode 100644 index 0000000000000000000000000000000000000000..8436f5c79a9fa205ce8714758cf0fef933023ee0 --- /dev/null +++ b/pool/shard007/C++/0090899_update_data_provider.cc @@ -0,0 +1,172 @@ +// 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. + +#include "extensions/browser/updater/update_data_provider.h" + +#include + +#include "base/base64.h" +#include "base/bind.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/strings/string_util.h" +#include "base/task/thread_pool.h" +#include "components/crx_file/crx_verifier.h" +#include "components/update_client/utils.h" +#include "content/public/browser/browser_task_traits.h" +#include "content/public/browser/browser_thread.h" +#include "crypto/sha2.h" +#include "extensions/browser/content_verifier.h" +#include "extensions/browser/extension_prefs.h" +#include "extensions/browser/extension_registry.h" +#include "extensions/browser/extension_system.h" +#include "extensions/browser/extensions_browser_client.h" +#include "extensions/browser/install/crx_install_error.h" +#include "extensions/browser/updater/manifest_fetch_data.h" +#include "extensions/common/extension.h" +#include "extensions/common/extension_urls.h" +#include "extensions/common/verifier_formats.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +namespace extensions { + +namespace { + +using UpdateClientCallback = UpdateDataProvider::UpdateClientCallback; + +void InstallUpdateCallback(content::BrowserContext* context, + const std::string& extension_id, + const std::string& public_key, + const base::FilePath& unpacked_dir, + bool install_immediately, + UpdateClientCallback update_client_callback) { + // Note that error codes are converted into custom error codes, which are all + // based on a constant (see ToInstallerResult). This means that custom codes + // from different embedders may collide. However, for any given extension ID, + // there should be only one embedder, so this should be OK from Omaha. + ExtensionSystem::Get(context)->InstallUpdate( + extension_id, public_key, unpacked_dir, install_immediately, + base::BindOnce( + [](UpdateClientCallback callback, + const absl::optional& error) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + update_client::CrxInstaller::Result result(0); + if (error.has_value()) { + int detail = + error->type() == + CrxInstallErrorType::SANDBOXED_UNPACKER_FAILURE + ? static_cast(error->sandbox_failure_detail()) + : static_cast(error->detail()); + result = update_client::ToInstallerResult(error->type(), detail); + } + std::move(callback).Run(result); + }, + std::move(update_client_callback))); +} + +} // namespace + +UpdateDataProvider::UpdateDataProvider(content::BrowserContext* browser_context) + : browser_context_(browser_context) {} + +UpdateDataProvider::~UpdateDataProvider() = default; + +void UpdateDataProvider::Shutdown() { + browser_context_ = nullptr; +} + +std::vector> +UpdateDataProvider::GetData(bool install_immediately, + const ExtensionUpdateDataMap& update_crx_component, + const std::vector& ids) { + std::vector> data; + if (!browser_context_) + return data; + const ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context_); + const ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(browser_context_); + for (const auto& id : ids) { + const Extension* extension = registry->GetInstalledExtension(id); + data.push_back(extension + ? absl::make_optional() + : absl::nullopt); + if (!extension) + continue; + DCHECK_NE(0u, update_crx_component.count(id)); + const ExtensionUpdateData& extension_data = update_crx_component.at(id); + auto& crx_component = data.back(); + std::string pubkey_bytes; + base::Base64Decode(extension->public_key(), &pubkey_bytes); + crx_component->pk_hash.resize(crypto::kSHA256Length, 0); + crypto::SHA256HashString(pubkey_bytes, crx_component->pk_hash.data(), + crx_component->pk_hash.size()); + crx_component->app_id = + update_client::GetCrxIdFromPublicKeyHash(crx_component->pk_hash); + if (extension_data.is_corrupt_reinstall) { + crx_component->version = base::Version("0.0.0.0"); + } else { + crx_component->version = extension->version(); + crx_component->fingerprint = extension->DifferentialFingerprint(); + } + crx_component->allows_background_download = false; + bool allow_dev = extension_urls::GetWebstoreUpdateUrl() != + extension_urls::GetDefaultWebstoreUpdateUrl(); + crx_component->requires_network_encryption = !allow_dev; + crx_component->crx_format_requirement = + extension->from_webstore() ? GetWebstoreVerifierFormat(allow_dev) + : GetPolicyVerifierFormat(); + crx_component->installer = base::MakeRefCounted( + id, extension->path(), install_immediately, + base::BindRepeating(&UpdateDataProvider::RunInstallCallback, this)); + if (!ExtensionsBrowserClient::Get()->IsExtensionEnabled(id, + browser_context_)) { + int disabled_reasons = extension_prefs->GetDisableReasons(id); + if (disabled_reasons == extensions::disable_reason::DISABLE_NONE || + disabled_reasons >= extensions::disable_reason::DISABLE_REASON_LAST) { + crx_component->disabled_reasons.push_back(0); + } + for (int enum_value = 1; + enum_value < extensions::disable_reason::DISABLE_REASON_LAST; + enum_value <<= 1) { + if (disabled_reasons & enum_value) + crx_component->disabled_reasons.push_back(enum_value); + } + } + crx_component->install_source = extension_data.is_corrupt_reinstall + ? "reinstall" + : extension_data.install_source; + crx_component->install_location = + ManifestFetchData::GetSimpleLocationString(extension->location()); + } + return data; +} + +void UpdateDataProvider::RunInstallCallback( + const std::string& extension_id, + const std::string& public_key, + const base::FilePath& unpacked_dir, + bool install_immediately, + UpdateClientCallback update_client_callback) { + VLOG(3) << "UpdateDataProvider::RunInstallCallback " << extension_id << " " + << public_key; + + if (!browser_context_) { + base::ThreadPool::PostTask( + FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::BindOnce(base::GetDeletePathRecursivelyCallback(), unpacked_dir)); + content::GetUIThreadTaskRunner({})->PostTask( + FROM_HERE, + base::BindOnce(std::move(update_client_callback), + update_client::CrxInstaller::Result( + update_client::InstallError::GENERIC_ERROR))); + return; + } + + content::GetUIThreadTaskRunner({})->PostTask( + FROM_HERE, + base::BindOnce(InstallUpdateCallback, browser_context_, extension_id, + public_key, unpacked_dir, install_immediately, + std::move(update_client_callback))); +} + +} // namespace extensions diff --git a/pool/shard007/C++/0090904_font.cpp b/pool/shard007/C++/0090904_font.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c771cc4ba8e9f669aec410fe4e76cd18cce47d1 --- /dev/null +++ b/pool/shard007/C++/0090904_font.cpp @@ -0,0 +1,84 @@ +#include "font.h" + +#include + +//Local includes +#include "json.h" +#include "FS.h" + +typedef std::string fontName_t; +typedef std::string fontPath_t; + +typedef std::pair fontPair_t; + +typedef std::map fonts_t; +typedef std::map fontRenders_t; + +fonts_t fonts; //font name:font path +fontRenders_t fontRenders; //font name, size: font + + +int GE_Font_Init() +{ + int ttferror = TTF_Init(); + if (ttferror < 0) + { + //TODO: Handle error... + printf("TTF_Init error %d\n",ttferror); + return ttferror; + } + return 0; +} +void GE_Font_LoadFromList(std::string list) +{ + std::string parrentPath = filesystem::get_parrent_directory(list); + std::string buffer = filesystem::read_all_from_file(list); + Json::Value root; + GE_ReadJson(buffer,&root); + Json::Value spritelist = root["fontlist"]; + for (unsigned int i = 0; i < spritelist.size(); i++) + { + fontPath_t path = parrentPath+"/"+spritelist[i].asString(); + fontName_t name = filesystem::get_base_filename(filesystem::get_filename_without_extension(path)); + printf("Font name %s\n",name.c_str()); + fonts.insert(std::make_pair(name,path)); + } +} +std::optional GE_Font_GetFont(std::string name, unsigned int size) +{ + //fontPath_t font = *(fonts.find(name)); + fontRenders_t::iterator fontIt = fontRenders.find(fontPair_t(name,size)); + if (fontIt == fontRenders.end()) + { + fonts_t::iterator pathIt = fonts.find(name); + if (pathIt == fonts.end()) + { + return {}; + } + GE_Font font = {TTF_OpenFont((pathIt->second).c_str(), size),size}; + if (!(font.font)) + { + printf("TTF_OpenFont: %s\n", TTF_GetError()); + return {}; + } + fontRenders.insert(std::make_pair(fontPair_t(name,size),font)); + + return {font}; + } + return {fontIt->second}; +} +void GE_Font_Shutdown() +{ + fontRenders_t::iterator it; + while (true) + { + it = fontRenders.begin(); + if (it == fontRenders.end()) + { + break; + } + TTF_CloseFont(it->second.font); + fontRenders.erase(it); + } + TTF_Quit(); +} diff --git a/pool/shard007/C++/0090905_bazaarsettings.cpp b/pool/shard007/C++/0090905_bazaarsettings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..74aee6333390edd02bee185b3baa998c0dfeca6d --- /dev/null +++ b/pool/shard007/C++/0090905_bazaarsettings.cpp @@ -0,0 +1,64 @@ +/************************************************************************** +** +** Copyright (c) 2013 Hugues Delorme +** Contact: http://www.qt-project.org/legal +** +** This file is part of Qt Creator. +** +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +****************************************************************************/ +#include "bazaarsettings.h" +#include "constants.h" + +#include + +namespace Bazaar { +namespace Internal { + +const QLatin1String BazaarSettings::diffIgnoreWhiteSpaceKey("diffIgnoreWhiteSpace"); +const QLatin1String BazaarSettings::diffIgnoreBlankLinesKey("diffIgnoreBlankLines"); +const QLatin1String BazaarSettings::logVerboseKey("logVerbose"); +const QLatin1String BazaarSettings::logForwardKey("logForward"); +const QLatin1String BazaarSettings::logIncludeMergesKey("logIncludeMerges"); +const QLatin1String BazaarSettings::logFormatKey("logFormat"); + +BazaarSettings::BazaarSettings() +{ + setSettingsGroup(QLatin1String(Constants::BAZAAR)); + // Override default binary path + declareKey(binaryPathKey, QLatin1String(Constants::BAZAARDEFAULT)); + declareKey(diffIgnoreWhiteSpaceKey, false); + declareKey(diffIgnoreBlankLinesKey, false); + declareKey(logVerboseKey, false); + declareKey(logForwardKey, false); + declareKey(logIncludeMergesKey, false); + declareKey(logFormatKey, QLatin1String("long")); +} + +bool BazaarSettings::sameUserId(const BazaarSettings &other) const +{ + return stringValue(userNameKey) == other.stringValue(userNameKey) + && stringValue(userEmailKey) == other.stringValue(userEmailKey); +} + +} // namespace Internal +} // namespace Bazaar diff --git a/pool/shard007/C++/0090913_dockey.cc b/pool/shard007/C++/0090913_dockey.cc new file mode 100644 index 0000000000000000000000000000000000000000..cc3b93d895d6cfa9ee3fc1d143b90b48c7d299d2 --- /dev/null +++ b/pool/shard007/C++/0090913_dockey.cc @@ -0,0 +1,113 @@ +/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ +/* + * Copyright 2018 Couchbase, Inc + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include + +std::string CollectionID::to_string() const { + std::stringstream sstream; + sstream << "0x" << std::hex << value; + return sstream.str(); +} + +bool CollectionID::isReserved(CollectionIDType value) { + return value >= System && value <= Reserved7; +} + +std::string ScopeID::to_string() const { + std::stringstream sstream; + sstream << "0x" << std::hex << value; + return sstream.str(); +} + +std::string DocKey::to_string() const { + // Get the sid of the key and add it to the string + auto [cid, key] = cb::mcbp::unsigned_leb128::decode( + {data(), size()}); + + std::string_view remainingKey{reinterpret_cast(key.data()), + key.size()}; + if (getCollectionID().isSystem()) { + // Get the hex value of the type of system event + auto [systemEventID, keyWithoutEvent] = + cb::mcbp::unsigned_leb128::decode( + {key.data(), key.size()}); + // Get the cid or sid of the system event is for + auto [cidOrSid, keySuffix] = + cb::mcbp::unsigned_leb128::decode( + {keyWithoutEvent.data(), keyWithoutEvent.size()}); + // Get the string view to the remaining string part of the key + remainingKey = {reinterpret_cast(keySuffix.data()), + keySuffix.size()}; + return fmt::format(fmt("cid:{:#x}:{:#x}:{:#x}:{}"), + cid, + systemEventID, + cidOrSid, + remainingKey); + } else { + return fmt::format(fmt("cid:{:#x}:{}"), cid, remainingKey); + } +} + +CollectionID DocKey::getCollectionID() const { + if (encoding == DocKeyEncodesCollectionId::Yes) { + auto cid = cb::mcbp::unsigned_leb128::decode(buffer) + .first; + return cid; + } + return CollectionID::Default; +} + +// Inspect the leb128 key prefixes without doing a full leb decode +bool DocKey::isInSystemCollection() const { + if (encoding == DocKeyEncodesCollectionId::Yes) { + // Note: when encoding == Yes the size is 2 bytes at a minimum. This is + // as mcbp_validators will fail 0-byte logical keys, thus we always have + // at least 1 byte of collection and 1 byte of key so size() checks are + // not needed. System keys additionally never have empty logical keys. + // Finally we do not need to consider the Prepared namespace as system + // events are never created in that way. + return data()[0] == CollectionID::System; + } + return false; +} + +// Inspect the leb128 key prefixes without doing a full leb decode +bool DocKey::isInDefaultCollection() const { + if (encoding == DocKeyEncodesCollectionId::Yes) { + return data()[0] == CollectionID::Default; + } + return true; +} + +std::pair DocKey::getIdAndKey() const { + if (encoding == DocKeyEncodesCollectionId::Yes) { + return cb::mcbp::unsigned_leb128::decode(buffer); + } + return {CollectionID::Default, {data(), size()}}; +} + +DocKey DocKey::makeDocKeyWithoutCollectionID() const { + if (getEncoding() == DocKeyEncodesCollectionId::Yes) { + auto decoded = cb::mcbp::skip_unsigned_leb128(buffer); + return {decoded.data(), decoded.size(), DocKeyEncodesCollectionId::No}; + } + return *this; +} diff --git a/pool/shard007/C++/0090917_chanfix-misc.cc b/pool/shard007/C++/0090917_chanfix-misc.cc new file mode 100644 index 0000000000000000000000000000000000000000..bcf2a4283b564fac49c4a5281012be69b3ea462d --- /dev/null +++ b/pool/shard007/C++/0090917_chanfix-misc.cc @@ -0,0 +1,87 @@ +/** + * chanfix-misc.cc + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, + * USA. + */ + +#include +#include + +#include + +#include "Network.h" + +#include "chanfix.h" + +namespace gnuworld { + +namespace chanfix { + +using std::endl; + +void chanfix::log(const logging::loglevel& level, const char* format, ... ) +{ + char buf[1024] = {0}; + va_list list; + + va_start(list, format); + vsnprintf(buf, 1024, format, list); + va_end(list); + + log(level, std::string(buf)); +} + + +void chanfix::log(const logging::loglevel& level, + const std::string& message) +{ + if( 0 == (confLogLevel & level) ) { return; } + + /* Check our logging channel exists */ + Channel *logChannel = Network->findChannel(confConsoleChannel); + + if( !logChannel ) { + elog << "chanfix> ERROR: Unable to locate logging channel." + << endl; + return; + } + + Message(logChannel, message.c_str()); +} + + +void chanfix::setConsoleTopic() +{ + char buffer[512]; + sprintf(buffer, "Giving %u points per %us", + confPointsAuth, + confPeriod + ); + + std::stringstream newTopic; + newTopic << this->getCharYYXXX() + << " T " + << confConsoleChannel + << " :" + << buffer + << endl; + + this->Write(newTopic.str()); +} + +} // namespace chanfix + +} // namespace gnuworld diff --git a/pool/shard007/C++/0090925_SurfaceTask.cpp b/pool/shard007/C++/0090925_SurfaceTask.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c0b634644e8b36e4a6cc6a53e4477959b6c5c542 --- /dev/null +++ b/pool/shard007/C++/0090925_SurfaceTask.cpp @@ -0,0 +1,63 @@ +/******************************************************************************\ + + CAMotics is an Open-Source simulation and CAM software. + Copyright (C) 2011-2019 Joseph Coffland + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +\******************************************************************************/ + +#include "SurfaceTask.h" + +#include +#include + +#include +#include +#include +#include + +using namespace cb; +using namespace CAMotics; + + +SurfaceTask::SurfaceTask(const Simulation &sim) : + simRun(new SimulationRun(sim)) {} + + +SurfaceTask::SurfaceTask(const SmartPointer &simRun) : + simRun(simRun) {} + + +SurfaceTask::~SurfaceTask() {} + + +void SurfaceTask::run() { + double startTime = Timer::now(); + + surface = simRun->compute(*this); + + // Time + if (shouldQuit()) { + LOG_INFO(1, "Render aborted"); + return; + } + + // Done + double delta = Timer::now() - startTime; + unsigned triangles = surface->getTriangleCount(); + LOG_INFO(1, "Time: " << TimeInterval(delta) + << " Triangles: " << triangles + << " Triangles/sec: " << String::printf("%0.2f", triangles / delta)); +} diff --git a/pool/shard007/C++/0090928_Config.cpp b/pool/shard007/C++/0090928_Config.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9c7d297ec13858b2054298af9e90f9acf0ae3e09 --- /dev/null +++ b/pool/shard007/C++/0090928_Config.cpp @@ -0,0 +1,134 @@ +#include +#include +#include +#include + +#include "Config.h" + +Config::Config() +{ + this->err_message.clear(); +} + +Config::~Config() +{ + this->param.clear(); +} + +std::string +Config::trim(std::string &str) +{ + std::string result; + std::string::size_type left; + std::string::size_type right; + + left = str.find_first_not_of(" \t\v\r\n"); + if (left != std::string::npos) { + right = str.find_last_not_of(" \t\v\r\n"); + result = str.substr(left, right - left + 1); + } + + return result; +} + +int +Config::parse(const char *conffile) +{ + int ret = -1; + FILE *fp = NULL; + std::string key; + std::string value; + bool keyget = false; + bool comment_get = false; + + this->param.clear(); + + fp = fopen(conffile, "r"); + if (fp == NULL) { + err_message = "config open failed - "; + err_message.append(strerror(errno)); + err_message.append(" "); + err_message.append(conffile); + goto end; + } + + while (!feof(fp)) { + char buf = (char)fgetc(fp); + if (buf == '\r' || buf == '\n') { + if (keyget) { + param[trim(key)] = trim(value); + } + keyget = false; + comment_get = false; + key.clear(); + value.clear(); + } else { + if (buf == '#') { + comment_get = true; + } + if (comment_get == false) { + if (buf == '=') { + keyget = true; + } else { + if (keyget) { + value.push_back((char) buf); + } else { + key.push_back((char) buf); + } + } + } + } + } + + if (ferror(fp)) { + err_message = "config load error - "; + err_message.append(strerror(errno)); + goto end; + } + + ret = 0; + +end: + if (fp != NULL) { + fclose(fp); + } + + return ret; +} + +std::string +Config::get(const char *key) +{ + std::map::iterator itr = param.find(key); + if (itr != param.end()) { + return itr->second; + } else { + err_message = "key not found"; + return ""; + } +} + +size_t +Config::getParamCount(void) +{ + return this->param.size(); +} + +std::vector +Config::getKeys(void) +{ + std::vector result; + std::map::iterator itr = param.begin(); + while (itr != param.end()) { + result.push_back(itr->first); + itr++; + } + + return result; +} + +const char* +Config::getErrorMessage(void) +{ + return this->err_message.c_str(); +} diff --git a/pool/shard007/C++/0090936_diargimg.cc b/pool/shard007/C++/0090936_diargimg.cc new file mode 100644 index 0000000000000000000000000000000000000000..4ffbcb727212e210e4fb9426c47a3aed0b3641ae --- /dev/null +++ b/pool/shard007/C++/0090936_diargimg.cc @@ -0,0 +1,209 @@ +/* + * + * Copyright (C) 1996-2005, OFFIS + * + * This software and supporting documentation were developed by + * + * Kuratorium OFFIS e.V. + * Healthcare Information and Communication Systems + * Escherweg 2 + * D-26121 Oldenburg, Germany + * + * THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND OFFIS MAKES NO WARRANTY + * REGARDING THE SOFTWARE, ITS PERFORMANCE, ITS MERCHANTABILITY OR + * FITNESS FOR ANY PARTICULAR USE, FREEDOM FROM ANY COMPUTER DISEASES OR + * ITS CONFORMITY TO ANY SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND + * PERFORMANCE OF THE SOFTWARE IS WITH THE USER. + * + * Module: dcmimage + * + * Author: Joerg Riesmeier + * + * Purpose: DiARGBImage (Source) - UNTESTED !!! + * + * Last Update: $Author: braindead $ + * Update Date: $Date: 2007/04/24 09:53:47 $ + * CVS/RCS Revision: $Revision: 1.2 $ + * Status: $State: Exp $ + * + * CVS/RCS Log at end of file + * + */ + + +#include "dcmtk/config/osconfig.h" +#include "dcmtk/dcmdata/dctypes.h" +#include "dcmtk/dcmdata/dcdeftag.h" + +#include "dcmtk/dcmimage/diargimg.h" +#include "dcmtk/dcmimage/diargpxt.h" +#include "dcmtk/dcmimgle/diluptab.h" +#include "dcmtk/dcmimgle/diinpx.h" + + +/*----------------* + * constructors * + *----------------*/ + +DiARGBImage::DiARGBImage(const DiDocument *docu, + const EI_Status status) + : DiColorImage(docu, status, 4) +{ + if ((Document != NULL) && (InputData != NULL) && (ImageStatus == EIS_Normal)) + { + if (BitsStored <= MAX_TABLE_ENTRY_SIZE) // color depth <= 16 + { + DiLookupTable *palette[3]; // create color luts + palette[0] = new DiLookupTable(Document, DCM_RedPaletteColorLookupTableDescriptor, + DCM_RedPaletteColorLookupTableData, DcmTagKey(0,0), OFFalse /*ignoreDepth*/, &ImageStatus); + palette[1] = new DiLookupTable(Document, DCM_GreenPaletteColorLookupTableDescriptor, + DCM_GreenPaletteColorLookupTableData, DcmTagKey(0,0), OFFalse /*ignoreDepth*/, &ImageStatus); + palette[2] = new DiLookupTable(Document, DCM_BluePaletteColorLookupTableDescriptor, + DCM_BluePaletteColorLookupTableData, DcmTagKey(0,0), OFFalse /*ignoreDepth*/, &ImageStatus); + if ((ImageStatus == EIS_Normal) && (palette[0] != NULL) && (palette[1] != NULL) && (palette[2] != NULL)) + { + BitsPerSample = BitsStored; + for (int jj = 0; jj < 3; jj++) // determine maximum bit count + { + if (palette[jj]->getBits() > OFstatic_cast(Uint16, BitsPerSample)) + BitsPerSample = palette[jj]->getBits(); + } + /* number of pixels per plane */ + const unsigned long planeSize = OFstatic_cast(unsigned long, Columns) * OFstatic_cast(unsigned long, Rows); + switch (InputData->getRepresentation()) + { + case EPR_Uint8: + if (BitsPerSample <= 8) + InterData = new DiARGBPixelTemplate(Document, InputData, palette, ImageStatus, + planeSize, BitsStored); + else + InterData = new DiARGBPixelTemplate(Document, InputData, palette, ImageStatus, + planeSize, BitsStored); + break; + case EPR_Sint8: + if (BitsPerSample <= 8) + InterData = new DiARGBPixelTemplate(Document, InputData, palette, ImageStatus, + planeSize, BitsStored); + else + InterData = new DiARGBPixelTemplate(Document, InputData, palette, ImageStatus, + planeSize, BitsStored); + break; + case EPR_Uint16: + if (BitsPerSample <= 8) + InterData = new DiARGBPixelTemplate(Document, InputData, palette, ImageStatus, + planeSize, BitsStored); + else + InterData = new DiARGBPixelTemplate(Document, InputData, palette, ImageStatus, + planeSize, BitsStored); + break; + case EPR_Sint16: + if (BitsPerSample <= 8) + InterData = new DiARGBPixelTemplate(Document, InputData, palette, ImageStatus, + planeSize, BitsStored); + else + InterData = new DiARGBPixelTemplate(Document, InputData, palette, ImageStatus, + planeSize, BitsStored); + break; + default: + if (DicomImageClass::checkDebugLevel(DicomImageClass::DL_Warnings)) + { + ofConsole.lockCerr() << "WARNING: invalid value for inter-representation !"; + ofConsole.unlockCerr(); + } + } + deleteInputData(); // input data is no longer needed + checkInterData(); + } + delete palette[0]; // color luts are no longer needed + delete palette[1]; + delete palette[2]; + } + else // color depth > 16 + { + ImageStatus = EIS_InvalidValue; + if (DicomImageClass::checkDebugLevel(DicomImageClass::DL_Errors)) + { + ofConsole.lockCerr() << "ERROR: invalid value for 'BitsStored' (" << BitsStored << ") " + << "... exceeds maximum palette entry size of " << MAX_TABLE_ENTRY_SIZE << " bits !" << endl; + ofConsole.unlockCerr(); + } + } + } +} + + +/*--------------* + * destructor * + *--------------*/ + +DiARGBImage::~DiARGBImage() +{ +} + + +/* + * + * CVS/RCS Log: + * $Log: diargimg.cc,v $ + * Revision 1.2 2007/04/24 09:53:47 braindead + * - updated DCMTK to version 3.5.4 + * - merged Gianluca's WIN32 changes + * + * Revision 1.1.1.1 2006/07/19 09:16:44 pipelka + * - imported dcmtk354 sources + * + * + * Revision 1.17 2005/12/08 15:42:19 meichel + * Changed include path schema for all DCMTK header files + * + * Revision 1.16 2003/12/17 17:50:37 joergr + * Added new compatibility flag that allows to ignore the third value of LUT + * descriptors and to determine the bits per table entry automatically. + * + * Revision 1.15 2003/12/17 16:34:57 joergr + * Adapted type casts to new-style typecast operators defined in ofcast.h. + * + * Revision 1.14 2002/06/26 16:22:52 joergr + * Corrected decoding of multi-frame, planar images. + * + * Revision 1.13 2001/06/01 15:49:34 meichel + * Updated copyright header + * + * Revision 1.12 2000/04/28 12:40:02 joergr + * DebugLevel - global for the module - now derived from OFGlobal (MF-safe). + * + * Revision 1.11 2000/04/27 13:15:56 joergr + * Dcmimage library code now consistently uses ofConsole for error output. + * + * Revision 1.10 2000/03/08 16:21:55 meichel + * Updated copyright header. + * + * Revision 1.9 2000/03/03 14:07:54 meichel + * Implemented library support for redirecting error messages into memory + * instead of printing them to stdout/stderr for GUI applications. + * + * Revision 1.8 1999/04/28 13:18:21 joergr + * Introduced new scheme for the debug level variable: now each level can be + * set separately (there is no "include" relationship). + * + * Revision 1.7 1998/12/16 16:03:47 joergr + * Added explanation string to LUT class (retrieved from dataset). + * + * Revision 1.6 1998/12/14 17:09:44 joergr + * Added support for signed values as second entry in look-up tables + * (= first value mapped). + * + * Revision 1.5 1998/11/27 14:25:09 joergr + * Added copyright message. + * Renamed variable 'Status' to 'ImageStatus' because of possible conflicts + * with X windows systems. + * + * Revision 1.4 1998/07/01 08:39:34 joergr + * Minor changes to avoid compiler warnings (gcc 2.8.1 with additional + * options), e.g. add copy constructors. + * + * Revision 1.3 1998/05/11 14:52:25 joergr + * Added CVS/RCS header to each file. + * + * + */ diff --git a/pool/shard007/C++/0090940_HTMLMetaCharsetParser.cpp b/pool/shard007/C++/0090940_HTMLMetaCharsetParser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..26de6900178058e80b9795a01a0e79437088e82d --- /dev/null +++ b/pool/shard007/C++/0090940_HTMLMetaCharsetParser.cpp @@ -0,0 +1,129 @@ +/* + * Copyright (C) 2010 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: + * 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. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 "config.h" +#include "core/html/parser/HTMLMetaCharsetParser.h" + +#include "core/HTMLNames.h" +#include "core/html/parser/HTMLParserIdioms.h" +#include "core/html/parser/HTMLParserOptions.h" +#include "core/html/parser/HTMLTokenizer.h" +#include "wtf/text/TextEncodingRegistry.h" +#include "wtf/text/WTFString.h" + +using namespace WTF; + +namespace blink { + +using namespace HTMLNames; + +HTMLMetaCharsetParser::HTMLMetaCharsetParser() + : m_tokenizer(HTMLTokenizer::create(HTMLParserOptions(0))) + , m_assumedCodec(newTextCodec(Latin1Encoding())) + , m_inHeadSection(true) + , m_doneChecking(false) +{ +} + +HTMLMetaCharsetParser::~HTMLMetaCharsetParser() +{ +} + +bool HTMLMetaCharsetParser::processMeta() +{ + const HTMLToken::AttributeList& tokenAttributes = m_token.attributes(); + HTMLAttributeList attributes; + for (HTMLToken::AttributeList::const_iterator iter = tokenAttributes.begin(); iter != tokenAttributes.end(); ++iter) { + String attributeName = attemptStaticStringCreation(iter->name, Likely8Bit); + String attributeValue = StringImpl::create8BitIfPossible(iter->value); + attributes.append(std::make_pair(attributeName, attributeValue)); + } + + m_encoding = encodingFromMetaAttributes(attributes); + return m_encoding.isValid(); +} + +static const int bytesToCheckUnconditionally = 1024; // That many input bytes will be checked for meta charset even if section is over. + +bool HTMLMetaCharsetParser::checkForMetaCharset(const char* data, size_t length) +{ + if (m_doneChecking) + return true; + + ASSERT(!m_encoding.isValid()); + + // We still don't have an encoding, and are in the head. + // The following tags are allowed in : + // SCRIPT|STYLE|META|LINK|OBJECT|TITLE|BASE + + // We stop scanning when a tag that is not permitted in + // is seen, rather when is seen, because that more closely + // matches behavior in other browsers; more details in + // . + + // Additionally, we ignore things that looks like tags in , <script> + // and <noscript>; see <http://bugs.webkit.org/show_bug.cgi?id=4560>, + // <http://bugs.webkit.org/show_bug.cgi?id=12165> and + // <http://bugs.webkit.org/show_bug.cgi?id=12389>. + + // Since many sites have charset declarations after <body> or other tags + // that are disallowed in <head>, we don't bail out until we've checked at + // least bytesToCheckUnconditionally bytes of input. + + m_input.append(SegmentedString(m_assumedCodec->decode(data, length))); + + while (m_tokenizer->nextToken(m_input, m_token)) { + bool end = m_token.type() == HTMLToken::EndTag; + if (end || m_token.type() == HTMLToken::StartTag) { + String tagName = attemptStaticStringCreation(m_token.name(), Likely8Bit); + if (!end) { + m_tokenizer->updateStateFor(tagName); + if (threadSafeMatch(tagName, metaTag) && processMeta()) { + m_doneChecking = true; + return true; + } + } + + if (!threadSafeMatch(tagName, scriptTag) && !threadSafeMatch(tagName, noscriptTag) + && !threadSafeMatch(tagName, styleTag) && !threadSafeMatch(tagName, linkTag) + && !threadSafeMatch(tagName, metaTag) && !threadSafeMatch(tagName, objectTag) + && !threadSafeMatch(tagName, titleTag) && !threadSafeMatch(tagName, baseTag) + && (end || !threadSafeMatch(tagName, htmlTag)) && (end || !threadSafeMatch(tagName, headTag))) { + m_inHeadSection = false; + } + } + + if (!m_inHeadSection && m_input.numberOfCharactersConsumed() >= bytesToCheckUnconditionally) { + m_doneChecking = true; + return true; + } + + m_token.clear(); + } + + return false; +} + +} diff --git a/pool/shard007/C++/0090948_razorfen_downs.cpp b/pool/shard007/C++/0090948_razorfen_downs.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3dda965d188fdb81bac576b2053065901ece4d75 --- /dev/null +++ b/pool/shard007/C++/0090948_razorfen_downs.cpp @@ -0,0 +1,85 @@ +/* Copyright (C) 2006 - 2011 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* ScriptData +SDName: Razorfen_Downs +SD%Complete: 100 +SDComment: Support for Henry Stern(2 recipes) +SDCategory: Razorfen Downs +EndScriptData */ + +/* ContentData +npc_henry_stern +EndContentData */ + +#include "precompiled.h" + +/*### +# npc_henry_stern +####*/ + +enum +{ + SPELL_GOLDTHORN_TEA = 13028, + SPELL_TEACHING_GOLDTHORN_TEA = 13029, + SPELL_MIGHT_TROLLS_BLOOD_POTION = 3451, + SPELL_TEACHING_MIGHTY_TROLLS_BLOOD_POTION = 13030, + GOSSIP_TEXT_TEA_ANSWER = 2114, + GOSSIP_TEXT_POTION_ANSWER = 2115, +}; + +#define GOSSIP_ITEM_TEA "Teach me the cooking recipe" +#define GOSSIP_ITEM_POTION "Teach me the alchemy recipe" + +bool GossipHello_npc_henry_stern (Player* pPlayer, Creature* pCreature) +{ + if (pPlayer->GetBaseSkillValue(SKILL_COOKING) >= 175 && !pPlayer->HasSpell(SPELL_GOLDTHORN_TEA)) + pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_TEA, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); + + if (pPlayer->GetBaseSkillValue(SKILL_ALCHEMY) >= 180 && !pPlayer->HasSpell(SPELL_MIGHT_TROLLS_BLOOD_POTION)) + pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_POTION, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); + + pPlayer->SEND_GOSSIP_MENU(pPlayer->GetGossipTextId(pCreature), pCreature->GetGUID()); + return true; +} + +bool GossipSelect_npc_henry_stern (Player* pPlayer, Creature* pCreature, uint32 uiSender, uint32 uiAction) +{ + if (uiAction == GOSSIP_ACTION_INFO_DEF + 1) + { + pCreature->CastSpell(pPlayer, SPELL_TEACHING_GOLDTHORN_TEA, true); + pPlayer->SEND_GOSSIP_MENU(GOSSIP_TEXT_TEA_ANSWER, pCreature->GetGUID()); + } + + if (uiAction == GOSSIP_ACTION_INFO_DEF + 2) + { + pPlayer->SEND_GOSSIP_MENU(GOSSIP_TEXT_POTION_ANSWER, pCreature->GetGUID()); + pCreature->CastSpell(pPlayer, SPELL_TEACHING_MIGHTY_TROLLS_BLOOD_POTION, true); + } + + return true; +} + +void AddSC_razorfen_downs() +{ + Script* newscript; + + newscript = new Script; + newscript->Name = "npc_henry_stern"; + newscript->pGossipHello = &GossipHello_npc_henry_stern; + newscript->pGossipSelect = &GossipSelect_npc_henry_stern; + newscript->RegisterSelf(); +} diff --git a/pool/shard007/C++/0090956_9.cpp b/pool/shard007/C++/0090956_9.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f011ba9ecf935f168f54106e508d3e30bcdaea46 --- /dev/null +++ b/pool/shard007/C++/0090956_9.cpp @@ -0,0 +1,115 @@ +#include <cstdio> +#include <cstring> +#include <cstdlib> +#include <algorithm> +#include <cmath> +#include <set> +#include <map> +#include <cctype> +#include <vector> +#include <queue> +#include <stack> +#include <deque> +#include <string> +#include <iostream> +using namespace std; +typedef long long ll; +typedef unsigned long long ull; +#define foR for +#define for9 for +#define retunr return +#define reutrn return +#define reutnr return +const int inf = (1 << 31) - 1; +const ll INF = (1ll << 63) - 1; +const double PI = acos(-1.0); +const double eps = 1e-7; +const ll MOD = 1000000007ll; +const int maxn = 50001 + 100; +const int maxm = 1000000 + 100; +struct Edge +{ + int u; + int v; +}; +Edge edge[5010]; +int N, M, Q; +int fa[maxn]; +int Find(int x) +{ + if (fa[x] == x) + return x; + fa[x] = Find(fa[x]); + return fa[x]; +} +void Union(int a, int b) +{ + int u = Find(a); + int v = Find(b); + if (u != v) + { + fa[u] = v; + } +} +int vis[550]; +int main() +{ + int i, j, k, a, b, q; + while (scanf("%d %d", &N, &M) != EOF) + { + int tot = 0; + memset(vis, 0, sizeof(vis)); + for (i = 0; i < N; i++) + { + fa[i] = i; + } + for (i = 1; i <= M; i++) + { + scanf("%d %d", &a, &b); + Union(a, b); + edge[tot].u = a; + edge[tot++].v = b; + } + scanf("%d", &Q); + int num; + int res = 0; + for (i = 0; i < N; i++) + { + if (fa[i] == i) + res++; + } + for (q = 1; q <= Q; q++) + { + scanf("%d", &a); + vis[a] = 1; + for (i = 0; i < N; i++) + { + fa[i] = i; + } + for (i = 0; i < tot; i++) + { + if (vis[edge[i].u] || vis[edge[i].v]) + continue; + Union(edge[i].u, edge[i].v); + } + num = 0; + for (i = 0; i < N; i++) + { + if (fa[i] == i) + num++; + } + if (num > res + 1) + { + printf("Red Alert: City %d is lost!\n", a); + } + else + { + printf("City %d is lost.\n", a); + } + res = num; + } + if (Q == N) + printf("Game Over.\n"); + } + return 0; +} \ No newline at end of file diff --git a/pool/shard007/C++/0090959_run_settings_dialog.cpp b/pool/shard007/C++/0090959_run_settings_dialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9dc4d703fceedddccec34a2981773fbb7ce727e8 --- /dev/null +++ b/pool/shard007/C++/0090959_run_settings_dialog.cpp @@ -0,0 +1,98 @@ +/*************************************************************************/ +/* run_settings_dialog.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include "run_settings_dialog.h" + + +void RunSettingsDialog::popup_run_settings() { + + popup_centered(Size2( 300, 150 )); +} + +void RunSettingsDialog::set_custom_arguments(const String& p_arguments) { + + + arguments->set_text(p_arguments); +} +String RunSettingsDialog::get_custom_arguments() const { + + return arguments->get_text(); +} + + +void RunSettingsDialog::_bind_methods() { + + ObjectTypeDB::bind_method("_run_mode_changed",&RunSettingsDialog::_run_mode_changed); + //ObjectTypeDB::bind_method("_browse_selected_file",&RunSettingsDialog::_browse_selected_file); +} + +void RunSettingsDialog::_run_mode_changed(int idx) { + + if (idx==0) + arguments->set_editable(false); + else + arguments->set_editable(true); +} + +int RunSettingsDialog::get_run_mode() const { + + return run_mode->get_selected(); +} + +void RunSettingsDialog::set_run_mode(int p_run_mode) { + + run_mode->select(p_run_mode); + arguments->set_editable(p_run_mode); +} + +RunSettingsDialog::RunSettingsDialog() { + + /* SNAP DIALOG */ + + VBoxContainer *vbc = memnew( VBoxContainer ); + add_child(vbc); + set_child_rect(vbc); + + run_mode = memnew( OptionButton ); + vbc->add_margin_child("Run Mode:",run_mode); + run_mode->add_item("Current Scene"); + run_mode->add_item("Main Scene"); + run_mode->connect("item_selected",this,"_run_mode_changed"); + arguments = memnew( LineEdit ); + vbc->add_margin_child("Main Scene Arguments:",arguments); + arguments->set_editable(false); + + get_ok()->set_text("Close"); + //get_cancel()->set_text("Close"); + + arguments->set_text("-l $scene"); + + set_title("Scene Run Settings"); + + +} diff --git a/pool/shard007/C++/0090960_Log.cpp b/pool/shard007/C++/0090960_Log.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2be85caafa38ef01a3d1a9221d4131802c4c2502 --- /dev/null +++ b/pool/shard007/C++/0090960_Log.cpp @@ -0,0 +1,92 @@ +/* + * Log.cpp + * + * Created on: 13.05.2017 + * Author: felix + */ + +#include <iostream> +#include <common/Log.h> + +namespace Flix { + +Log* instance = new Log(); + +Log::Log(): + maxLevel(LogLevel::DEBUG) +{ +} + +Log::~Log() +{ +} + +void Log::log(LogLevel level, const std::string& message) +{ + if (level > maxLevel) { + return; + } + + std::cout << "[" << level << "] " << message << std::endl; +} + +void Log::error(const std::string& message) +{ + log(LogLevel::ERROR, message); +} + +void Log::warning(const std::string& message) +{ + log(LogLevel::WARNING, message); +} + +void Log::notice(const std::string& message) +{ + log(LogLevel::NOTICE, message); +} + +void Log::info(const std::string& message) +{ + log(LogLevel::INFO, message); +} + +void Log::debug(const std::string& message) +{ + log(LogLevel::DEBUG, message); +} + +void Log::setLogLevel(LogLevel maxLevel) +{ + this->maxLevel = maxLevel; +} + +Log* Log::getInstance(void) { + return instance; +} + +std::ostream& operator<<(std::ostream& stream, LogLevel level) +{ + switch (level) { + case LogLevel::ERROR: + stream << "E"; + break; + case LogLevel::WARNING: + stream << "W"; + break; + case LogLevel::NOTICE: + stream << "N"; + break; + case LogLevel::INFO: + stream << "I"; + break; + case LogLevel::DEBUG: + stream << "D"; + break; + default: + stream << "?"; + break; + } + return stream; +} + +} /* namespace Flix */ diff --git a/pool/shard007/C++/0090961_input_ime_api_nonchromeos.cc b/pool/shard007/C++/0090961_input_ime_api_nonchromeos.cc new file mode 100644 index 0000000000000000000000000000000000000000..9511f015971cd427dfc4a5f808727f35043a0f25 --- /dev/null +++ b/pool/shard007/C++/0090961_input_ime_api_nonchromeos.cc @@ -0,0 +1,73 @@ +// 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. + +// This file is for non-chromeos (win & linux) functions, such as +// chrome.input.ime.activate, chrome.input.ime.createWindow and +// chrome.input.ime.onSelectionChanged. +// TODO(azurewei): May refactor the code structure by using delegate or +// redesign the API to remove this platform-specific file in the future. + +#include "chrome/browser/extensions/api/input_ime/input_ime_api.h" + +#include "base/command_line.h" +#include "base/macros.h" +#include "chrome/common/chrome_switches.h" + +namespace { + +bool IsInputImeEnabled() { + return base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kEnableInputImeAPI); +} + +class ImeObserverNonChromeOS : public ui::ImeObserver { + public: + ImeObserverNonChromeOS(const std::string& extension_id, Profile* profile) + : ImeObserver(extension_id, profile) {} + + ~ImeObserverNonChromeOS() override {} + + private: + // ImeObserver overrides. + void DispatchEventToExtension( + extensions::events::HistogramValue histogram_value, + const std::string& event_name, + scoped_ptr<base::ListValue> args) override { + if (!IsInputImeEnabled()) { + return; + } + + scoped_ptr<extensions::Event> event( + new extensions::Event(histogram_value, event_name, std::move(args))); + event->restrict_to_browser_context = profile_; + extensions::EventRouter::Get(profile_) + ->DispatchEventToExtension(extension_id_, std::move(event)); + } + + std::string GetCurrentScreenType() override { + return "normal"; + } + + DISALLOW_COPY_AND_ASSIGN(ImeObserverNonChromeOS); +}; + +} // namespace + +namespace extensions { + +InputImeEventRouter::InputImeEventRouter(Profile* profile) + : InputImeEventRouterBase(profile) {} + +InputImeEventRouter::~InputImeEventRouter() {} + +void InputImeAPI::OnExtensionLoaded(content::BrowserContext* browser_context, + const Extension* extension) {} + +void InputImeAPI::OnExtensionUnloaded(content::BrowserContext* browser_context, + const Extension* extension, + UnloadedExtensionInfo::Reason reason) {} + +void InputImeAPI::OnListenerAdded(const EventListenerInfo& details) {} + +} // namespace extensions diff --git a/pool/shard007/C++/0090965_EigenDiffusion.cc b/pool/shard007/C++/0090965_EigenDiffusion.cc new file mode 100644 index 0000000000000000000000000000000000000000..ae362d09f9894ceaefa759dce5b4a8f079d55a16 --- /dev/null +++ b/pool/shard007/C++/0090965_EigenDiffusion.cc @@ -0,0 +1,86 @@ +//----------------------------------*-C++-*----------------------------------// +/** + * @file EigenDiffusion.cc + * @brief EigenDiffusion + * @author Jeremy Roberts + * @date Oct 26, 2012 + */ +//---------------------------------------------------------------------------// + +#include "EigenDiffusion.hh" +#include "MGDiffusionSolver.hh" + +namespace detran +{ + +//---------------------------------------------------------------------------// +template <class D> +EigenDiffusion<D>::EigenDiffusion(SP_mg_solver mg_solver) + : Base(mg_solver) +{ + // Extract diffusion solver pointer + MGDiffusionSolver<D>* mg_diff = + dynamic_cast<MGDiffusionSolver<D>*>(mg_solver->solver().bp()); + Insist(mg_diff, + "EigenDiffusion requires a multigroup diffusion solver"); + + // Get mesh and materials + d_mesh = d_mg_solver->mesh(); + d_material = d_mg_solver->material(); + + // Create operators and vectors + size_t problem_size = d_mesh->number_cells() * d_material->number_groups(); + d_phi = new callow::Vector(problem_size, 0.0); + d_work = new callow::Vector(problem_size, 1.0); + + // Get the loss operator and build the fission operator + d_M = mg_diff->lossoperator(); + d_F = new DiffusionGainOperator(d_input, d_material, d_mesh, d_adjoint); + + d_F->print_matlab("eigF.out"); + d_M->print_matlab("eigM.out"); + + + // Create callow eigensolver and set operators + SP_input db; + if (d_input->check("eigen_solver_db")) + db = d_input->template get<SP_input>("eigen_solver_db"); + d_eigensolver = Creator_T::Create(db); + d_eigensolver->set_operators(d_F, d_M, db); +} + +//---------------------------------------------------------------------------// +template <class D> +void EigenDiffusion<D>::solve() +{ + + // solve the system + d_eigensolver->solve(d_phi, d_work); + + // set the eigenvalue + d_state->set_eigenvalue(d_eigensolver->eigenvalue()); + + // fill the state flux vector + int k = 0; + for (int g = 0; g < d_material->number_groups(); g++) + for (int i = 0; i < d_mesh->number_cells(); i++, k++) + d_state->phi(g)[i] = (*d_phi)[k]; + + // update the fission source (for use in rates, etc.) + d_fissionsource->update(); + +} + +//---------------------------------------------------------------------------// +// EXPLICIT INSTANTIATIONS +//---------------------------------------------------------------------------// + +template class EigenDiffusion<_1D>; +template class EigenDiffusion<_2D>; +template class EigenDiffusion<_3D>; + +} // end namespace detran + +//---------------------------------------------------------------------------// +// end of file EigenDiffusion.cc +//---------------------------------------------------------------------------// diff --git a/pool/shard007/C++/0090968_luksan_vlcek_1.cpp b/pool/shard007/C++/0090968_luksan_vlcek_1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1fcb7409556daa2340bcf5e2dcefa4d7390319a6 --- /dev/null +++ b/pool/shard007/C++/0090968_luksan_vlcek_1.cpp @@ -0,0 +1,123 @@ +/***************************************************************************** + * Copyright (C) 2004-2013 The PaGMO development team, * + * Advanced Concepts Team (ACT), European Space Agency (ESA) * + * http://apps.sourceforge.net/mediawiki/pagmo * + * http://apps.sourceforge.net/mediawiki/pagmo/index.php?title=Developers * + * http://apps.sourceforge.net/mediawiki/pagmo/index.php?title=Credits * + * act@esa.int * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + *****************************************************************************/ + +#include <boost/integer_traits.hpp> +#include <boost/numeric/conversion/cast.hpp> +#include <cmath> +#include <stdexcept> +#include <string> +#include <vector> + +#include "../exceptions.h" +#include "../types.h" +#include "base.h" +#include "luksan_vlcek_1.h" + +static int __check__(int N){ + if (N - 2 >= boost::integer_traits<int>::const_max / 2) { + pagmo_throw(std::overflow_error,"overflow error"); + } + if (N <= 2) + { + pagmo_throw(value_error,"problem dimension needs to be at least 3"); + } + return N; +} + +namespace pagmo { namespace problem { +/// Constructor. +/** + * Construct the problem from its dimension. + * Setting cub=clb=0 creates an instance of the original Luksan Vlcek equality constrained problem, example 5.1. + * Using clb < cub allows the obtain a problem formulation with inequality constraints. + * + * @param[in] N problem dimension + * @param[in] clb lower bounds for the constraints. + * @param[in] cub upper bounds for the constraints. + * @throws value_error if N is smaller than 2, cub < clb + * + * @see L. Luksan and J. Vlcek, "Sparse and Parially Separable Test Problems for Unconstrained and Equality Constrained Optimization" + */ +luksan_vlcek_1::luksan_vlcek_1(int N, const double &clb, const double &cub):base(__check__(N),0,1,2*(__check__(N)-2),2*(__check__(N)-2)) +{ + + if (clb > cub) + { + pagmo_throw(value_error,"constraints lower bound is higher than the upper bound"); + } + set_lb(-5); + set_ub(5); + m_clb = decision_vector(boost::numeric_cast<decision_vector::size_type>(N-2),clb); + m_cub = decision_vector(boost::numeric_cast<decision_vector::size_type>(N-2),cub); +} + +/// Clone method. +base_ptr luksan_vlcek_1::clone() const +{ + return base_ptr(new luksan_vlcek_1(*this)); +} + +/// Implementation of the objective function. +void luksan_vlcek_1::objfun_impl(fitness_vector &f, const decision_vector &x) const +{ + f[0] = 0.; + for (pagmo::decision_vector::size_type i=0; i<x.size()-1; i++) + { + double a1 = x[i]*x[i]-x[i+1]; + double a2 = x[i] - 1.; + f[0] += 100.*a1*a1 + a2*a2; + } +} + +/// Implementation of the constraint function. +void luksan_vlcek_1::compute_constraints_impl(constraint_vector &c, const decision_vector &x) const +{ + for (pagmo::decision_vector::size_type i=0; i<x.size()-2; i++) + { + c[2 * i] = (3.*std::pow(x[i+1],3.) + 2.*x[i+2] - 5. + + std::sin(x[i+1]-x[i+2])*std::sin(x[i+1]+x[i+2]) + 4.*x[i+1] + - x[i]*std::exp(x[i]-x[i+1]) - 3.) - m_cub[i]; + c[2 * i + 1] = - (3.*std::pow(x[i+1],3.) + 2.*x[i+2] - 5. + + std::sin(x[i+1]-x[i+2])*std::sin(x[i+1]+x[i+2]) + 4.*x[i+1] + - x[i]*std::exp(x[i]-x[i+1]) - 3.) + m_clb[i]; + } +} + +/// Implementation of the sparsity structure: automated detection +void luksan_vlcek_1::set_sparsity(int &lenG, std::vector<int> &iGfun, std::vector<int> &jGvar) const +{ + //Initial point + decision_vector x0(get_dimension(),1); + //Numerical procedure + estimate_sparsity(x0, lenG, iGfun, jGvar); +} + +std::string luksan_vlcek_1::get_name() const +{ + return "Luksan-Vlcek 1"; +} + +} } + +BOOST_CLASS_EXPORT_IMPLEMENT(pagmo::problem::luksan_vlcek_1) diff --git a/pool/shard007/C++/0090977_ActuatorPwm.cpp b/pool/shard007/C++/0090977_ActuatorPwm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..307c84e4e29563905d2d9e91218726d9720bacb6 --- /dev/null +++ b/pool/shard007/C++/0090977_ActuatorPwm.cpp @@ -0,0 +1,128 @@ +#include "ActuatorInterfaces.h" +#include "ActuatorPwm.h" +#include "Ticks.h" +#include "ActuatorMutexDriver.h" + +ActuatorPwm::ActuatorPwm(ActuatorDigital* _target, uint16_t _period) : + ActuatorDriver(_target) { + periodStartTime = ticks.millis(); + periodLate = 0; + dutyLate = 0; + value = 0.0; + minVal = 0.0; + maxVal = 100.0; + target->setActive(false); + setPeriod(_period); + recalculate(); +} + +void ActuatorPwm::recalculate() { + recalculate(period_ms); +} + +void ActuatorPwm::recalculate(int32_t expectedPeriod) { + // shift by 6 makes calculation work for period up to 11 hours + dutyTime = int32_t(temp_long_t(value) << uint8_t(6)) * ((expectedPeriod + 50) / 100) >> 6; +} + +void ActuatorPwm::setValue(temp_t const& val) { + temp_t val_(val); + if (val_ <= minVal) { + val_ = minVal; + } + if (val_ >= maxVal) { + val_ = maxVal; + } + + if (value != val_) { + temp_t delta = val_ - value; + value = val_; + if(delta > temp_t(5.0)){ + // big positive change, go high immediately by starting a new period + dutyLate = 0; + periodLate = 0; + recalculate(); + periodStartTime = ticks.millis() - period_ms; + + } + else if(delta < temp_t(-5.0)){ + // big negative change, go to low part of period immediately + recalculate(); + periodStartTime = ticks.millis() - dutyTime + dutyLate; + } + else{ + recalculate(period_ms + periodLate); + } + } +} + +void ActuatorPwm::update() { + target->update(); + int32_t adjDutyTime = dutyTime - dutyLate; + int32_t currentTime = ticks.millis(); + int32_t elapsedTime = currentTime - periodStartTime; + + if (target->isActive()) { + if (elapsedTime >= adjDutyTime) { + // end of duty cycle + int32_t lowTime = period_ms - dutyTime; + if(periodLate >= lowTime){ + // built up low periods are higher then required low time, skip a low cycle + recalculate(); + periodLate -= lowTime; + // dutyLate -= (period_ms - dutyTime); + periodStartTime = currentTime; + } + else{ + target->setActive(false); + // check if turning the output off has succeeded (OnOff actuator could stay active due to time limit) + if (target->isActive()) { + return; // try next time + } + dutyLate += elapsedTime - dutyTime; + } + } + } + if (!target->isActive()) { // <- do not replace with else if + if (elapsedTime >= period_ms) { + // end of PWM cycle + if (adjDutyTime < 0) { + // skip going high for 1 period when previous periods built up + // more than one entire duty cycle (duty is ahead) + // subtract duty cycle form duty late accumulator + dutyLate = dutyLate - dutyTime; + } else { + if(dutyTime > 0){ + if(target->type() == ACTUATOR_TOGGLE_MUTEX){ + static_cast<ActuatorMutexDriver*>(target)->setActive(true, priority()); + } + else{ + target->setActive(true); + } + if (!target->isActive()) { + return; // try next time + } + } + } + periodLate = elapsedTime - period_ms; + // limit to half of the period + periodLate = (periodLate < period_ms / 2) ? periodLate : period_ms / 2; + // adjust next duty time to account for longer period due to infrequent updates + // low period was longer, increase high period (duty cycle) with same ratio + recalculate(period_ms + periodLate); + periodStartTime = currentTime; + } + } +} + +int8_t ActuatorPwm::priority(){ + int32_t adjDutyTime = dutyTime - dutyLate; + int32_t priority = (adjDutyTime*100)/period_ms; + if(priority > 127){ + priority = 127; + } + if(priority < 0){ + priority = 0; + } + return priority; +} diff --git a/pool/shard007/C++/0090985_unweightedVisibilityGraph.cpp b/pool/shard007/C++/0090985_unweightedVisibilityGraph.cpp new file mode 100644 index 0000000000000000000000000000000000000000..670d73bef0825f7b7aa044ffbe1ac69886bee367 --- /dev/null +++ b/pool/shard007/C++/0090985_unweightedVisibilityGraph.cpp @@ -0,0 +1,47 @@ +#include <Rcpp.h> +#include <vector> +#include <iostream> +using namespace Rcpp; +using namespace std; +//' Function to get the edgelist form a time series +//'@export +//'@param x a numeric vector convert from a time series +//'@return a edgelist dataframe without weights with 2 columns +// [[Rcpp::export]] +SEXP unweightVisibilityGraph(NumericVector x){ + vector<vector<int > > edgelist(0); + vector<int > temp(2,0); + vector<double > real(0); + for(int i=1;i!=x.size();i++){ + //numeric vertex label must start from 1 + temp[0]=i;//vertex label of i and it's neighbor is connected + temp[1]=i+1;//vertex label of the neighbor of i + edgelist.push_back(temp); + int j=i+2;//the next neighbor need evaluation + while(j<=x.size()){ + //the real values of the timeseires + for(int l=i+1;l!=j;l++){ + real.push_back(x[l-1]); + } + //the theoritical values of the timeseries + bool compare=true; + for(int k=i+1;k!=j;k++){ + double theory_temp=(x[j-1]+(x[i-1]-x[j-1])*(double(j-k)/double(j-i))); + if(real[k-i-1]>=theory_temp){ + compare=false; + break; + } + //cout<<theory_temp<<endl; + } + if(compare==true){ + temp[0]=i; + temp[1]=j; + edgelist.push_back(temp); + } + //clear the temp vector + real.clear(); + j++; + } + } + return wrap(edgelist); +} diff --git a/pool/shard007/C++/0090988_JobManifest.cpp b/pool/shard007/C++/0090988_JobManifest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ede38da972dbbd78c7a9059a439e1fb837a853bd --- /dev/null +++ b/pool/shard007/C++/0090988_JobManifest.cpp @@ -0,0 +1,78 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include <aws/s3control/model/JobManifest.h> +#include <aws/core/utils/xml/XmlSerializer.h> +#include <aws/core/utils/StringUtils.h> +#include <aws/core/utils/memory/stl/AWSStringStream.h> + +#include <utility> + +using namespace Aws::Utils::Xml; +using namespace Aws::Utils; + +namespace Aws +{ +namespace S3Control +{ +namespace Model +{ + +JobManifest::JobManifest() : + m_specHasBeenSet(false), + m_locationHasBeenSet(false) +{ +} + +JobManifest::JobManifest(const XmlNode& xmlNode) : + m_specHasBeenSet(false), + m_locationHasBeenSet(false) +{ + *this = xmlNode; +} + +JobManifest& JobManifest::operator =(const XmlNode& xmlNode) +{ + XmlNode resultNode = xmlNode; + + if(!resultNode.IsNull()) + { + XmlNode specNode = resultNode.FirstChild("Spec"); + if(!specNode.IsNull()) + { + m_spec = specNode; + m_specHasBeenSet = true; + } + XmlNode locationNode = resultNode.FirstChild("Location"); + if(!locationNode.IsNull()) + { + m_location = locationNode; + m_locationHasBeenSet = true; + } + } + + return *this; +} + +void JobManifest::AddToNode(XmlNode& parentNode) const +{ + Aws::StringStream ss; + if(m_specHasBeenSet) + { + XmlNode specNode = parentNode.CreateChildElement("Spec"); + m_spec.AddToNode(specNode); + } + + if(m_locationHasBeenSet) + { + XmlNode locationNode = parentNode.CreateChildElement("Location"); + m_location.AddToNode(locationNode); + } + +} + +} // namespace Model +} // namespace S3Control +} // namespace Aws diff --git a/pool/shard007/C++/0091001_group-objects-cmd.cpp b/pool/shard007/C++/0091001_group-objects-cmd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1a7baa63d134e31d5296b7c24c37b5917d7ea09a --- /dev/null +++ b/pool/shard007/C++/0091001_group-objects-cmd.cpp @@ -0,0 +1,162 @@ +// -*- coding: us-ascii-unix -*- +// Copyright 2012 Lukas Kemmer +// +// 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 <algorithm> +#include "commands/command.hh" +#include "commands/group-objects-cmd.hh" +#include "objects/objcomposite.hh" +#include "objects/object.hh" +#include "text/formatting.hh" +#include "util/iter.hh" +#include "util/object-util.hh" + +namespace faint{ + +class GroupObjectsCommand : public Command { +public: + GroupObjectsCommand(const objects_t& objects, const select_added& select) + : Command(CommandType::OBJECT), + m_group(create_composite_object(objects, Ownership::LOANER)), + m_objects(objects), + m_select(select.Get()) + {} + + ~GroupObjectsCommand(){ + delete m_group; + } + + void Do(CommandContext& context) override{ + // Initialize on the first run + if (m_objectDepths.empty()){ + for (const Object* obj : m_objects){ + m_objectDepths.push_back(context.GetObjectZ(obj)); + } + } + + // Traverse and remove objects, adding them instead as a group + int depth = 0; + for (int i = 0; i!= m_group->GetObjectCount(); i++){ + Object* obj = m_group->GetObject(i); + depth = std::max(depth, context.GetObjectZ(obj)); + context.Remove(obj); + } + context.Add(m_group, depth, select_added(m_select), deselect_old(false)); + } + + utf8_string Name() const override{ + return space_sep("Group", get_collective_type(m_objects)); + } + + void Undo(CommandContext& context) override{ + context.Remove(m_group); + for (size_t i = 0; i!= m_objects.size(); i++){ + context.Add(m_objects[i], m_objectDepths[i], select_added(false), + deselect_old(false)); + } + } + + // Necessary for returning the group as a Python-object when + // grouping via Python + Object* GetComposite(){ + return m_group; + } + +private: + Object* m_group; + std::vector<int> m_objectDepths; + objects_t m_objects; + bool m_select; +}; + +class UngroupObjectsCommand : public Command { +public: + UngroupObjectsCommand(const objects_t& objects, const select_added& select) + : Command(CommandType::OBJECT), + m_objects(objects), + m_select(select.Get()) + {} + + void Do(CommandContext& context) override{ + // Initialize object depths for Undo on the first run + if (m_objectDepths.empty()) { + for (const Object* obj : m_objects){ + m_objectDepths.push_back(context.GetObjectZ(obj)); + } + } + + // Traverse and ungroup all groups in the command + for (Object* group : m_objects){ + int numContained = group->GetObjectCount(); + const int depth = context.GetObjectZ(group); + // Add the contained objects + for (int j = 0; j != numContained; j++){ + Object* contained = group->GetObject(j); + context.Add(contained, depth + j, select_added(m_select), + deselect_old(false)); // Fixme: Causes loads of refresh-es for no good reason + } + // Remove the disbanded group + context.Remove(group); + } + } + + utf8_string Name() const override{ + return "Ungroup Objects"; + } + + void Undo(CommandContext& context) override{ + for (auto group : enumerate(m_objects)){ + int numContained = (*group)->GetObjectCount(); + if (numContained == 0){ + continue; + } + for (int j = 0; j != numContained; j++){ + context.Remove(group.item->GetObject(j)); + } + context.Add(group.item, m_objectDepths[to_size_t(group.num)], + select_added(m_select), deselect_old(true)); + } + } +private: + objects_t m_objects; + std::vector<int> m_objectDepths; + bool m_select; +}; + +static bool all_are_groups(const objects_t& objects){ + for (const Object* obj : objects){ + if (obj->GetObjectCount() == 0){ + return false; + } + } + return true; +} + +std::pair<Command*, Object*> group_objects_command(const objects_t& objects, + const select_added& select) +{ + assert(!objects.empty()); + GroupObjectsCommand* cmd = new GroupObjectsCommand(objects, select); + return std::make_pair(cmd, cmd->GetComposite()); +} + +Command* ungroup_objects_command(const objects_t& objects, + const select_added& select) +{ + assert(!objects.empty()); + assert(all_are_groups(objects)); + return new UngroupObjectsCommand(objects, select); +} + +} // namespace diff --git a/pool/shard007/C++/0091004_bmplib.cpp b/pool/shard007/C++/0091004_bmplib.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b8152c623417dee0aa8eebd60a204465b6f91145 --- /dev/null +++ b/pool/shard007/C++/0091004_bmplib.cpp @@ -0,0 +1,190 @@ +#ifdef _WIN32 +#include "boinc_win.h" +#else +#include "config.h" +#endif + +#include "bmplib.h" + +// Returns true for success -- false otherwise +bool DIB_BITMAP::set_size(int width, int height, int channels) +{ + + // If DIB_BITMAP has already been set -- clear it out first + FreeDIB_BMP(); + + // Create a temporary compatible device context + HDC temp_hdc = CreateCompatibleDC(NULL); + + // Error Check + if(!temp_hdc) + return false; + + bmp_width = width; // Set the width + bmp_height = height; // Set the height + bmp_channels = channels; // Set the channels (3 == 24-bit, 4 == 32-bit) + + // Set stride -- The stride is the TRUE number of bytes in a line of pixels + // Windows makes all the .bmps DWORD aligned (divisible evenly by 4) + // So if you bitmap say was 103x103 pixels, Windows would add 1 "padding byte" to it + // so in memory it would be 104x103 pixels. The "padding bytes" do not get blit (drawn) + // to the screen, they're just there so again everything is DWORD aligned which makes + // blitting (drawing to the screen) easier for the OS + bmp_stride = bmp_width * bmp_channels; + + while((bmp_stride % 4) != 0) // Ensure bmp_stride is DWORD aligned + bmp_stride++; + + BITMAPINFO bmp_info = {0}; + + // Initialize the parameters that we care about + bmp_info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); + bmp_info.bmiHeader.biWidth = width; + bmp_info.bmiHeader.biHeight = height; + bmp_info.bmiHeader.biPlanes = 1; // Always equal 1 + bmp_info.bmiHeader.biBitCount = channels * 8; + bmp_info.bmiHeader.biCompression = BI_RGB; // No compression + bmp_info.bmiHeader.biClrUsed = 0; // Always equals 0 with a 24 or 32-bit .bmp + + // Create a DIBSection -- This returns us two things, an HBITMAP handle and + // a memory pointer (pointer to the pixels) in surface_bits + hbitmap = CreateDIBSection(temp_hdc, &bmp_info, DIB_RGB_COLORS, + (void**)&surface_bits, 0, 0); + + // Release our temporary HDC + DeleteDC(temp_hdc); + + // Error Check -- Make sure the call to CreateDIBSection() DID NOT fail + if(!hbitmap) + return false; + + return true; // We're sized :) + +} // end of set_size(int width, int height, int channels) + +bool DIB_BITMAP::loadBMP(const char *file_name) +{ + // If DIB_BITMAP has already been set -- clear it out first + FreeDIB_BMP(); + + // Error Check -- Make sure they passed in a valid file name + if(!file_name) + return false; + + FILE *bmp_file = fopen(file_name, "rb"); + + // Error Check -- Make sure the file could be opened + if(!bmp_file) + return false; + + BITMAPFILEHEADER bmp_fileheader; + + // Read the BITMAPFILEHEADER + if(!fread(&bmp_fileheader, sizeof(BITMAPFILEHEADER), 1, bmp_file)) + { + fclose(bmp_file); + return false; + } + + // Check the type field to make sure we have a .bmp file + if(memcmp(&bmp_fileheader.bfType, "BM", 2)) + { + fclose(bmp_file); + return false; + } + + BITMAPINFOHEADER bmp_infoheader; + + // Read the BITMAPINFOHEADER. + if(!fread(&bmp_infoheader, sizeof(BITMAPINFOHEADER), 1, bmp_file)) + { + fclose(bmp_file); + return false; + } + + // We only support 24-bit and 32-bit .bmps so make sure that's what we have + if((bmp_infoheader.biBitCount != 24) && (bmp_infoheader.biBitCount != 32)) + { + fclose(bmp_file); + return false; + } + + // Set the size of our DIB_BITMAP, once we do this we're ready to store the pixel + // data in it + if(set_size(bmp_infoheader.biWidth,bmp_infoheader.biHeight,bmp_infoheader.biBitCount / 8) == false) + { + fclose(bmp_file); + return false; + } + + // Jump to the location where the pixel data is stored + if(fseek(bmp_file, bmp_fileheader.bfOffBits, SEEK_SET)) + { + fclose(bmp_file); + return false; + } + + unsigned int bytesPerLine = bmp_width * bmp_channels; // Bytes per line (number of bytes + // in a scan line) + + // Calculate how many "padding" bytes there are -- WE DO NOT want to read in the + // padding bytes (we will just skip over those) + // **Remember** Windows adds padding bytes to ensure ALL .bmps are DWORD aligned + // (divisible evenly by 4) + unsigned int padding = bmp_stride - bytesPerLine; + + // Loop over all the scan lines (all the rows of pixels in the image) + for(int y = bmp_height-1; y >= 0; y--) + { + // Get the "current" line pointer + uchar *LinePtr = getLinePtr(y); + + // Read the precise number of bytes that the scan line requires into the bitmap + if(!fread(LinePtr, bytesPerLine, 1, bmp_file)) + { + fclose(bmp_file); + return false; + } + + // Skip over any padding bytes. + if(fseek(bmp_file, padding, SEEK_CUR)) + { + fclose(bmp_file); + return false; + } + + } // end of for (int y = 0; y < bmp_infoheader.biHeight; y++) + + + fclose(bmp_file); + return true; // If we get here .bmp was read in successfully + +} // end of loadBMP(char *file_name, HDC hdc) + +// Returns the address in memory of the specified line. This gives you a pointer to at least +// width * channels bytes. Lines are numbered such that when the bitmap +// is displayed line zero is at the top. +uchar* DIB_BITMAP::getLinePtr(int which_line) +{ + return (surface_bits + bmp_stride * which_line); +} + +// Release the memory +void DIB_BITMAP::FreeDIB_BMP() +{ + // If we created an HBITMAP, delete it + if(hbitmap) + DeleteObject(hbitmap); + + // Zero out all data associated with DIB_BITMAP + hbitmap = NULL; + surface_bits = NULL; + bmp_width = bmp_height = bmp_channels = bmp_stride = 0; + return; +} + +// Deconstructor +DIB_BITMAP::~DIB_BITMAP() { FreeDIB_BMP(); } + + +const char *BOINC_RCSID_1051ce617a = "$Id: bmplib.cpp 16069 2008-09-26 18:20:24Z davea $"; diff --git a/pool/shard007/C++/0091007_SVGFilterPrimitiveStandardAttributes.cpp b/pool/shard007/C++/0091007_SVGFilterPrimitiveStandardAttributes.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2bd43f8e8926e59b5749f3e8235502cc69aea497 --- /dev/null +++ b/pool/shard007/C++/0091007_SVGFilterPrimitiveStandardAttributes.cpp @@ -0,0 +1,176 @@ +/* + * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org> + * Copyright (C) 2004, 2005, 2006 Rob Buis <buis@kde.org> + * Copyright (C) 2009 Dirk Schulze <krit@webkit.org> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "config.h" + +#if ENABLE(SVG) && ENABLE(FILTERS) +#include "SVGFilterPrimitiveStandardAttributes.h" + +#include "Attribute.h" +#include "FilterEffect.h" +#include "RenderSVGResourceFilterPrimitive.h" +#include "SVGElement.h" +#include "SVGElementInstance.h" +#include "SVGFilterBuilder.h" +#include "SVGLength.h" +#include "SVGNames.h" +#include "SVGUnitTypes.h" + +namespace WebCore { + +// Animated property definitions +DEFINE_ANIMATED_LENGTH(SVGFilterPrimitiveStandardAttributes, SVGNames::xAttr, X, x) +DEFINE_ANIMATED_LENGTH(SVGFilterPrimitiveStandardAttributes, SVGNames::yAttr, Y, y) +DEFINE_ANIMATED_LENGTH(SVGFilterPrimitiveStandardAttributes, SVGNames::widthAttr, Width, width) +DEFINE_ANIMATED_LENGTH(SVGFilterPrimitiveStandardAttributes, SVGNames::heightAttr, Height, height) +DEFINE_ANIMATED_STRING(SVGFilterPrimitiveStandardAttributes, SVGNames::resultAttr, Result, result) + +BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes) + REGISTER_LOCAL_ANIMATED_PROPERTY(x) + REGISTER_LOCAL_ANIMATED_PROPERTY(y) + REGISTER_LOCAL_ANIMATED_PROPERTY(width) + REGISTER_LOCAL_ANIMATED_PROPERTY(height) + REGISTER_LOCAL_ANIMATED_PROPERTY(result) + REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement) +END_REGISTER_ANIMATED_PROPERTIES + +SVGFilterPrimitiveStandardAttributes::SVGFilterPrimitiveStandardAttributes(const QualifiedName& tagName, Document* document) + : SVGElement(tagName, document) + , m_x(LengthModeWidth, "0%") + , m_y(LengthModeHeight, "0%") + , m_width(LengthModeWidth, "100%") + , m_height(LengthModeHeight, "100%") +{ + // Spec: If the x/y attribute is not specified, the effect is as if a value of "0%" were specified. + // Spec: If the width/height attribute is not specified, the effect is as if a value of "100%" were specified. + registerAnimatedPropertiesForSVGFilterPrimitiveStandardAttributes(); +} + +bool SVGFilterPrimitiveStandardAttributes::isSupportedAttribute(const QualifiedName& attrName) +{ + DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ()); + if (supportedAttributes.isEmpty()) { + supportedAttributes.add(SVGNames::xAttr); + supportedAttributes.add(SVGNames::yAttr); + supportedAttributes.add(SVGNames::widthAttr); + supportedAttributes.add(SVGNames::heightAttr); + supportedAttributes.add(SVGNames::resultAttr); + } + return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName); +} + +void SVGFilterPrimitiveStandardAttributes::parseAttribute(const QualifiedName& name, const AtomicString& value) +{ + SVGParsingError parseError = NoError; + + if (!isSupportedAttribute(name)) + SVGElement::parseAttribute(name, value); + else if (name == SVGNames::xAttr) + setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError)); + else if (name == SVGNames::yAttr) + setYBaseValue(SVGLength::construct(LengthModeHeight, value, parseError)); + else if (name == SVGNames::widthAttr) + setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError)); + else if (name == SVGNames::heightAttr) + setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError)); + else if (name == SVGNames::resultAttr) + setResultBaseValue(value); + else + ASSERT_NOT_REACHED(); + + reportAttributeParsingError(parseError, name, value); +} + +bool SVGFilterPrimitiveStandardAttributes::setFilterEffectAttribute(FilterEffect*, const QualifiedName&) +{ + // When all filters support this method, it will be changed to a pure virtual method. + ASSERT_NOT_REACHED(); + return false; +} + +void SVGFilterPrimitiveStandardAttributes::svgAttributeChanged(const QualifiedName& attrName) +{ + if (!isSupportedAttribute(attrName)) { + SVGElement::svgAttributeChanged(attrName); + return; + } + + SVGElementInstance::InvalidationGuard invalidationGuard(this); + invalidate(); +} + +void SVGFilterPrimitiveStandardAttributes::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta) +{ + SVGElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta); + + if (!changedByParser) + invalidate(); +} + +void SVGFilterPrimitiveStandardAttributes::setStandardAttributes(FilterEffect* filterEffect) const +{ + ASSERT(filterEffect); + if (!filterEffect) + return; + + if (hasAttribute(SVGNames::xAttr)) + filterEffect->setHasX(true); + if (hasAttribute(SVGNames::yAttr)) + filterEffect->setHasY(true); + if (hasAttribute(SVGNames::widthAttr)) + filterEffect->setHasWidth(true); + if (hasAttribute(SVGNames::heightAttr)) + filterEffect->setHasHeight(true); +} + +RenderObject* SVGFilterPrimitiveStandardAttributes::createRenderer(RenderArena* arena, RenderStyle*) +{ + return new (arena) RenderSVGResourceFilterPrimitive(this); +} + +bool SVGFilterPrimitiveStandardAttributes::rendererIsNeeded(const RenderStyle& style) +{ + if (parentNode() && (parentNode()->hasTagName(SVGNames::filterTag))) + return SVGElement::rendererIsNeeded(style); + + return false; +} + +void invalidateFilterPrimitiveParent(SVGElement* element) +{ + if (!element) + return; + + ContainerNode* parent = element->parentNode(); + + if (!parent) + return; + + RenderObject* renderer = parent->renderer(); + if (!renderer || !renderer->isSVGResourceFilterPrimitive()) + return; + + RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer, false); +} + +} + +#endif // ENABLE(SVG) diff --git a/pool/shard007/C++/0091009_interpl.cc b/pool/shard007/C++/0091009_interpl.cc new file mode 100644 index 0000000000000000000000000000000000000000..d569221f9db92f2766e62553c11d4435a40c2fc9 --- /dev/null +++ b/pool/shard007/C++/0091009_interpl.cc @@ -0,0 +1,234 @@ +/******************************************************************** +* Description: interpl.cc +* Mechanism for queueing NML messages, used by the interpreter and +* canonical interface to report list of NML statements from program +* files to HME. +* +* Derived from a work by Fred Proctor & Will Shackleford +* +* Author: +* License: GPL Version 2 +* System: Linux +* +* Copyright (c) 2004 All rights reserved. +* +* Last change: +********************************************************************/ + + +#include <string.h> /* memcpy() */ + +#include "rcs.hh" // LinkedList +#include "interpl.hh" // these decls +#include "emc.hh" +#include "emcglb.h" +#include "linklist.hh" +#include "nmlmsg.hh" /* class NMLmsg */ +#include "rcs_print.hh" + +NML_INTERP_LIST interp_list; /* NML Union, for interpreter */ + +NML_INTERP_LIST::NML_INTERP_LIST() +{ + linked_list_ptr = new LinkedList; + + next_line_number = 0; + line_number = 0; +} + +NML_INTERP_LIST::~NML_INTERP_LIST() +{ + if (NULL != linked_list_ptr) { + delete linked_list_ptr; + linked_list_ptr = NULL; + } +} + +int NML_INTERP_LIST::append(NMLmsg & nml_msg) +{ + /* check for invalid data */ + if (0 == nml_msg.type) { + rcs_print_error + ("NML_INTERP_LIST::append : attempt to append 0 type\n"); + return -1; + } + + if (NULL == linked_list_ptr) { + return -1; + } + + if (nml_msg.size > MAX_NML_COMMAND_SIZE - 64) { + rcs_print_error + ("NML_INTERP_LIST::append : command size is too large."); + return -1; + } + if (nml_msg.size < 4) { + rcs_print_error + ("NML_INTERP_LIST::append : command size is invalid."); + return -1; + } +#ifdef DEBUG_INTERPL + if (sizeof(temp_node) < MAX_NML_COMMAND_SIZE + 4 || + sizeof(temp_node) > MAX_NML_COMMAND_SIZE + 16) { + rcs_print_error + ("NML_INTERP_LIST::append : assumptions about NML_INTERP_LIST_NODE have been violated.\n"); + return -1; + } +#endif + + // fill in the NML_INTERP_LIST_NODE + temp_node.line_number = next_line_number; + memcpy(temp_node.command.commandbuf, &nml_msg, nml_msg.size); + + // stick it on the list + linked_list_ptr->store_at_tail(&temp_node, + nml_msg.size + + sizeof(temp_node.line_number) + + sizeof(temp_node.dummy) + 32 + (32 - + nml_msg. + size % + 32), 1); + + if (EMC_DEBUG & EMC_DEBUG_INTERP_LIST) { + rcs_print + ("NML_INTERP_LIST::append(nml_msg{size=%d,type=%s}) : list_size=%d, line_number=%d\n", + nml_msg.size, emc_symbol_lookup(nml_msg.type), + linked_list_ptr->list_size, temp_node.line_number); + } + + return 0; +} + +// sets the line number used for subsequent appends +int NML_INTERP_LIST::set_line_number(int line) +{ + next_line_number = line; + + return 0; +} + +int NML_INTERP_LIST::append(NMLmsg * nml_msg_ptr) +{ + /* check for invalid data */ + if (NULL == nml_msg_ptr) { + rcs_print_error + ("NML_INTERP_LIST::append : attempt to append NULL msg\n"); + return -1; + } + + if (0 == nml_msg_ptr->type) { + rcs_print_error + ("NML_INTERP_LIST::append : attempt to append 0 type\n"); + return -1; + } + + if (nml_msg_ptr->size > MAX_NML_COMMAND_SIZE - 64) { + rcs_print_error + ("NML_INTERP_LIST::append : command size is too large."); + return -1; + } + if (nml_msg_ptr->size < 4) { + rcs_print_error + ("NML_INTERP_LIST::append : command size is invalid."); + return -1; + } +#ifdef DEBUG_INTERPL + if (sizeof(temp_node) < MAX_NML_COMMAND_SIZE + 4 || + sizeof(temp_node) > MAX_NML_COMMAND_SIZE + 16 || + ((void *) &temp_node.line_number) > + ((void *) &temp_node.command.commandbuf)) { + rcs_print_error + ("NML_INTERP_LIST::append : assumptions about NML_INTERP_LIST_NODE have been violated."); + return -1; + } +#endif + + if (NULL == linked_list_ptr) { + return -1; + } + // fill in the NML_INTERP_LIST_NODE + temp_node.line_number = next_line_number; + memcpy(temp_node.command.commandbuf, nml_msg_ptr, nml_msg_ptr->size); + + // stick it on the list + linked_list_ptr->store_at_tail(&temp_node, + nml_msg_ptr->size + + sizeof(temp_node.line_number) + + sizeof(temp_node.dummy) + 32 + (32 - + nml_msg_ptr-> + size % + 32), 1); + + if (EMC_DEBUG & EMC_DEBUG_INTERP_LIST) { + rcs_print + ("NML_INTERP_LIST::append(nml_msg_ptr{size=%d,type=%s}) : list_size=%d, line_number=%d\n", + nml_msg_ptr->size, emc_symbol_lookup(nml_msg_ptr->type), + linked_list_ptr->list_size, temp_node.line_number); + } + + return 0; +} + +NMLmsg *NML_INTERP_LIST::get() +{ + NMLmsg *ret; + NML_INTERP_LIST_NODE *node_ptr; + + if (NULL == linked_list_ptr) { + line_number = 0; + return NULL; + } + + node_ptr = (NML_INTERP_LIST_NODE *) linked_list_ptr->retrieve_head(); + + if (NULL == node_ptr) { + line_number = 0; + return NULL; + } + // save line number of this one, for use by get_line_number + line_number = node_ptr->line_number; + + // get it off the front + ret = (NMLmsg *) ((char *) node_ptr->command.commandbuf); + + return ret; +} + +void NML_INTERP_LIST::clear() +{ + if (NULL != linked_list_ptr) { + linked_list_ptr->delete_members(); + } +} + +void NML_INTERP_LIST::print() +{ + NMLmsg *nml_msg; + + if (NULL == linked_list_ptr) { + return; + } + + nml_msg = (NMLmsg *) linked_list_ptr->get_head(); + + while (NULL != nml_msg) { + rcs_print("%d ", nml_msg->type); + nml_msg = (NMLmsg *) linked_list_ptr->get_next(); + } + + rcs_print("\n"); +} + +int NML_INTERP_LIST::len() +{ + if (NULL == linked_list_ptr) { + return 0; + } + + return ((int) linked_list_ptr->list_size); +} + +int NML_INTERP_LIST::get_line_number() +{ + return line_number; +} diff --git a/pool/shard007/C++/0091010_inserter.cpp b/pool/shard007/C++/0091010_inserter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3b7e030ab30d5ee0acc86733f1f2eadece5a8549 --- /dev/null +++ b/pool/shard007/C++/0091010_inserter.cpp @@ -0,0 +1,36 @@ +#include <iostream> +#include <iterator> +#include <algorithm> +#include <vector> +#include <list> + +using namespace std; + +int main(void) { + vector<int> v = { 1, 2, 3, 4, 5, 6 }; + list<int> empl; + vector<int> empv1, empv2; + + cout << "front_inserter" << ' '; + copy(v.begin(), v.end(), front_inserter(empl)); + for (auto el : empl) { + cout << el << ' '; + } + cout << endl; + + cout << "back_inserter" << ' '; + copy(v.begin(), v.end(), back_inserter(empv1)); + for (auto el : empv1) { + cout << el << ' '; + } + cout << endl; + + cout << "inserter" << ' '; + copy(v.begin(), v.end(), inserter(empv2, empv2.begin())); + for (auto el : empv2) { + cout << el << ' '; + } + cout << endl; + + return 0; +} diff --git a/pool/shard007/C++/0091017_MockSerial.cpp b/pool/shard007/C++/0091017_MockSerial.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a24afbb11950fb9cc0a513ead6a5501a8b5a272d --- /dev/null +++ b/pool/shard007/C++/0091017_MockSerial.cpp @@ -0,0 +1,65 @@ +/* + * MockSerial.cpp + * + * Created on: Oct 4, 2011 + * Author: nick + */ + +#include "MockWProgram.hpp" + +// This buffer is much larger than the actual one. + +MockSerial::MockSerial() { + reset(); +} + +void MockSerial::end() { + // Do Nothing +} + +void MockSerial::begin(uint32_t baud) { + _baud = baud; +} + +uint32_t MockSerial::available() { + return _size - _in_ptr; +} + +int MockSerial::read() { + if (_in_ptr < _size) { + return (int) _in_buf[_in_ptr++]; + } else { + return -1; + } +} + +void MockSerial::write(uint8_t value) { + _out_buf[_out_ptr] = value; + _out_ptr++; +} + +void MockSerial::write(uint8_t * array_ptr, uint32_t length) { + for (uint32_t i = 0; i < length; i++) { + _out_buf[_out_ptr + i] = *(array_ptr + i); + } + _out_ptr += length; +} + +void MockSerial::set_input_buffer(uint8_t * new_buf, uint16_t size) { + _in_buf = new_buf; + _in_ptr = 0; + _size = size; +} + +void MockSerial::reset(void) { + uint8_t tmp1[1024] = { 0x00 }; + uint8_t tmp2[1024] = { 0x00 }; + _out_buf = tmp1; + _out_ptr = 0; // Current buffer position + _in_buf = tmp2; + _in_ptr = 0; + _baud = 0; + _size = 0; +} + +MockSerial Serial = MockSerial(); diff --git a/pool/shard007/C++/0091019_dynamic_compressed_row_jacobian_writer.cc b/pool/shard007/C++/0091019_dynamic_compressed_row_jacobian_writer.cc new file mode 100644 index 0000000000000000000000000000000000000000..b46cb797ff2d26759e9e9323c803a72197bc9d45 --- /dev/null +++ b/pool/shard007/C++/0091019_dynamic_compressed_row_jacobian_writer.cc @@ -0,0 +1,114 @@ +// Ceres Solver - A fast non-linear least squares minimizer +// Copyright 2014 Google Inc. All rights reserved. +// http://code.google.com/p/ceres-solver/ +// +// 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. +// +// Author: richie.stebbing@gmail.com (Richard Stebbing) + +#include "ceres/compressed_row_jacobian_writer.h" +#include "ceres/dynamic_compressed_row_jacobian_writer.h" +#include "ceres/casts.h" +#include "ceres/dynamic_compressed_row_sparse_matrix.h" +#include "ceres/parameter_block.h" +#include "ceres/program.h" +#include "ceres/residual_block.h" + +namespace ceres { +namespace internal { + +ScratchEvaluatePreparer* +DynamicCompressedRowJacobianWriter::CreateEvaluatePreparers(int num_threads) { + return ScratchEvaluatePreparer::Create(*program_, num_threads); +} + +SparseMatrix* DynamicCompressedRowJacobianWriter::CreateJacobian() const { + // Initialize `jacobian` with zero number of `max_num_nonzeros`. + const int num_residuals = program_->NumResiduals(); + const int num_effective_parameters = program_->NumEffectiveParameters(); + + DynamicCompressedRowSparseMatrix* jacobian = + new DynamicCompressedRowSparseMatrix(num_residuals, + num_effective_parameters, + 0); + + vector<int>* row_blocks = jacobian->mutable_row_blocks(); + for (int i = 0; i < jacobian->num_rows(); ++i) { + row_blocks->push_back(1); + } + + vector<int>* col_blocks = jacobian->mutable_col_blocks(); + for (int i = 0; i < jacobian->num_cols(); ++i) { + col_blocks->push_back(1); + } + + return jacobian; +} + +void DynamicCompressedRowJacobianWriter::Write(int residual_id, + int residual_offset, + double **jacobians, + SparseMatrix* base_jacobian) { + DynamicCompressedRowSparseMatrix* jacobian = + down_cast<DynamicCompressedRowSparseMatrix*>(base_jacobian); + + // Get the `residual_block` of interest. + const ResidualBlock* residual_block = + program_->residual_blocks()[residual_id]; + const int num_residuals = residual_block->NumResiduals(); + + vector<pair<int, int> > evaluated_jacobian_blocks; + CompressedRowJacobianWriter::GetOrderedParameterBlocks( + program_, residual_id, &evaluated_jacobian_blocks); + + // `residual_offset` is the residual row in the global jacobian. + // Empty the jacobian rows. + jacobian->ClearRows(residual_offset, num_residuals); + + // Iterate over each parameter block. + for (int i = 0; i < evaluated_jacobian_blocks.size(); ++i) { + const ParameterBlock* parameter_block = + program_->parameter_blocks()[evaluated_jacobian_blocks[i].first]; + const int parameter_block_jacobian_index = + evaluated_jacobian_blocks[i].second; + const int parameter_block_size = parameter_block->LocalSize(); + + // For each parameter block only insert its non-zero entries. + for (int r = 0; r < num_residuals; ++r) { + for (int c = 0; c < parameter_block_size; ++c) { + const double& v = jacobians[parameter_block_jacobian_index][ + r * parameter_block_size + c]; + // Only insert non-zero entries. + if (v != 0.0) { + jacobian->InsertEntry( + residual_offset + r, parameter_block->delta_offset() + c, v); + } + } + } + } +} + +} // namespace internal +} // namespace ceres diff --git a/pool/shard007/C++/0091020_IAutomatonContext.cpp b/pool/shard007/C++/0091020_IAutomatonContext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d86e4ea615c84d7dc0ca12ce4c47e6c5a1f77870 --- /dev/null +++ b/pool/shard007/C++/0091020_IAutomatonContext.cpp @@ -0,0 +1,261 @@ +#include "IAutomatonContext.h" + +#include "INode.h" +#include "CIdentifier.h" +#include "defines.h" + +#include <map> +#include <string> + +#include <iostream> + +using namespace Automaton; +using namespace std; + +namespace Automaton +{ + + class CAutomatonContext : public IAutomatonContext + { + std::map<CIdentifier, INode*> m_oNodes; + + std::vector<CIdentifier> m_oReceivedEvents; + + std::vector<CIdentifier> m_oSentEvents; + + std::map<std::string, CIdentifier> m_oXMLNodeToIdentifier; + + Automaton::uint64 m_ui64CurrentTime; + + std::map<CIdentifier, string> m_oParameterName; + std::map<CIdentifier, Automaton::uint64> m_oParameterValue; + + public: + CAutomatonContext(); + + virtual ~CAutomatonContext(); + virtual void release(){ delete this; } + + virtual INode * getNode(const CIdentifier& oIdentifier); + virtual INode * getInitialNode(); + + virtual CIdentifier addNode(INode* pNode); + virtual boolean addSuccessor(CIdentifier oStart, CIdentifier oEnd); + + virtual const CIdentifier * getReceivedEvents() + { + if(m_oReceivedEvents.size() != 0) + { + return &m_oReceivedEvents[0]; + } + return NULL; + } + + virtual Automaton::uint32 getReceivedEventsCount() + { + return m_oReceivedEvents.size(); + } + + virtual void clearReceivedEvents() + { + m_oReceivedEvents.clear(); + } + + virtual void addReceivedEvent(CIdentifier& oIdentifier) + { + m_oReceivedEvents.push_back(oIdentifier); + } + + virtual const CIdentifier * getSentEvents() + { + if(m_oSentEvents.size() != 0) + { + return &m_oSentEvents[0]; + } + return NULL; + } + + virtual Automaton::uint32 getSentEventsCount() + { + return m_oSentEvents.size(); + } + + virtual void clearSentEvents() + { + m_oSentEvents.clear(); + } + + virtual void sendEvent(CIdentifier& oIdentifier); + + virtual CIdentifier getIdentifier(const std::string& oXMLNodeName); + + virtual void setCurrentTime(Automaton::uint64 ui64Time); + virtual Automaton::uint64 getCurrentTime(); + + virtual CIdentifier addParameter(const char * pName, Automaton::uint64 ui64Value); + virtual CIdentifier getVariableIdentifier(const char * pName); + + virtual const char* getParameterName(const CIdentifier& oIdentifier) + { + if(m_oParameterName.count(oIdentifier) == 0) + { + return NULL; + } + else + { + return m_oParameterName[oIdentifier].c_str(); + } + } + + virtual Automaton::uint64 getParameterValue(const CIdentifier& oIdentifier) + { + return m_oParameterValue[oIdentifier]; + } + + }; + + +}; + +//___________________________________________________________________________________________________ +// + +CAutomatonContext::CAutomatonContext() : m_ui64CurrentTime(0) +{ + m_oXMLNodeToIdentifier["Automaton"] = Automaton_Node_Identifier_Automaton; + + m_oXMLNodeToIdentifier["Action"] = Automaton_Node_Identifier_Action; + m_oXMLNodeToIdentifier["ActionSendEvent"] = Automaton_Node_Identifier_ActionSendEvent; + m_oXMLNodeToIdentifier["ActionWaitEvent"] = Automaton_Node_Identifier_ActionWaitEvent; + m_oXMLNodeToIdentifier["ActionWaitTime"] = Automaton_Node_Identifier_ActionWaitTime; + + m_oXMLNodeToIdentifier["Loop"] = Automaton_Node_Identifier_Loop; + m_oXMLNodeToIdentifier["LoopFinite"] = Automaton_Node_Identifier_LoopFinite; + m_oXMLNodeToIdentifier["LoopInfinite"] = Automaton_Node_Identifier_LoopInfinite; + m_oXMLNodeToIdentifier["LoopWaitEvent"] = Automaton_Node_Identifier_LoopWaitEvent; + + + m_oXMLNodeToIdentifier["Switch"] = Automaton_Node_Identifier_Switch; + m_oXMLNodeToIdentifier["SwitchProbabilist"] = Automaton_Node_Identifier_SwitchProbabilist; + m_oXMLNodeToIdentifier["SwitchEvent"] = Automaton_Node_Identifier_SwitchEvent; + + + m_oXMLNodeToIdentifier["RandomOrder"] = Automaton_Node_Identifier_RandomOrder; +} + +CAutomatonContext::~CAutomatonContext() +{ + //deletes all the recorded nodes + map<CIdentifier, INode*>::iterator l_oIterator; + for(l_oIterator=m_oNodes.begin() ; l_oIterator!=m_oNodes.end() ; l_oIterator++) + { + delete l_oIterator->second; + } +} + + +INode * CAutomatonContext::getNode(const CIdentifier& oIdentifier) +{ + if(m_oNodes.count(oIdentifier) == 0) + { + return NULL; + } + + return m_oNodes[oIdentifier]; +} + +INode * CAutomatonContext::getInitialNode() +{ + return m_oNodes[CIdentifier(0)]; +} + +CIdentifier CAutomatonContext::addNode(INode* pNode) +{ + CIdentifier l_oCurrentIdentifier = m_oNodes.size(); + m_oNodes[l_oCurrentIdentifier] = pNode; + + return l_oCurrentIdentifier; +} + +boolean CAutomatonContext::addSuccessor(CIdentifier oStart, CIdentifier oEnd) +{ + if(m_oNodes.count(oStart) == 0 || m_oNodes.count(oEnd) == 0 ) + { + return false; + } + else + { + m_oNodes[oStart]->addSuccessor(oEnd); + return true; + } +} + + +void CAutomatonContext::sendEvent(CIdentifier& oIdentifier) +{ + m_oSentEvents.push_back(oIdentifier); +} + +CIdentifier CAutomatonContext::getIdentifier(const std::string& oXMLNodeName) +{ + if(m_oXMLNodeToIdentifier.count(oXMLNodeName) == 0) + { + return Automaton_Node_Identifier_No_Node; + } + + return m_oXMLNodeToIdentifier[oXMLNodeName]; +} + +void CAutomatonContext::setCurrentTime(Automaton::uint64 ui64Time) +{ + m_ui64CurrentTime = ui64Time; +} + +Automaton::uint64 CAutomatonContext::getCurrentTime() +{ + return m_ui64CurrentTime; +} + +CIdentifier CAutomatonContext::getVariableIdentifier(const char * pName) +{ + map<CIdentifier,string>::iterator iter; + + for(iter=m_oParameterName.begin() ; iter!=m_oParameterName.end() ; iter++) + { + if(iter->second == pName) + { + return iter->first; + } + } + //didn't find it + return CIdentifier(0); +} + +CIdentifier CAutomatonContext::addParameter(const char * pName, Automaton::uint64 ui64Value) +{ + //uses the value map's size plus 1 to create the identifier (plus 1 since 0 is used + //to indicate that an error occured) + CIdentifier l_oCurrentIdentifier(m_oParameterValue.size() + 1); + + if(pName) + { + m_oParameterName[l_oCurrentIdentifier] = pName; + } + m_oParameterValue[l_oCurrentIdentifier] = ui64Value; + + return l_oCurrentIdentifier; +} + +//___________________________________________________________________________________________________ +// + +Automaton_API IAutomatonContext* Automaton::createAutomatonContext() +{ + return new CAutomatonContext; +} + +Automaton_API void Automaton::releaseAutomatonContext(IAutomatonContext* pContext) +{ + pContext->release(); +} + diff --git a/pool/shard007/C++/0091025_il2cppGC.cpp b/pool/shard007/C++/0091025_il2cppGC.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b9501807031701744c233ade80a8d27c6122f25c --- /dev/null +++ b/pool/shard007/C++/0091025_il2cppGC.cpp @@ -0,0 +1,154 @@ +#include "il2cpp.h" +#include <gc.h> + +#if defined(GC_THREADS) && defined(IL2CPP_ENABLE_FINALIZER_THREAD) + +#include <condition_variable> + +static class FinalizerThread +{ +public: + ~FinalizerThread() + { + IsExit_ = true; + Notify(); + + if (Thread_.joinable()) + Thread_.join(); + } + + void Start() + { + Thread_ = std::thread(&FinalizerThread::WorkingThread, this); + } + + void Notify() + { + IsNotify_ = true; + CondVar_.notify_one(); + } + +private: + void WorkingThread() + { + il2cpp_GC_RegisterThread(); + + while (!IsExit_) + { + std::unique_lock<std::mutex> lk(Mutex_); + CondVar_.wait(lk); + + while (IsNotify_) + { + IsNotify_ = false; + GC_invoke_finalizers(); + } + } + + il2cpp_GC_UnregisterThread(); + } + +private: + std::thread Thread_; + std::mutex Mutex_; + std::condition_variable CondVar_; + volatile bool IsNotify_ = false; + bool IsExit_ = false; +} g_FinalizerThread; + +static void GC_CALLBACK FinalizerNotifier() +{ + g_FinalizerThread.Notify(); +} +#endif + +void il2cpp_GC_Init() +{ + GC_set_no_dls(1); + + GC_INIT(); + +#if defined(GC_THREADS) + GC_allow_register_threads(); + +#if defined(IL2CPP_ENABLE_FINALIZER_THREAD) + GC_set_finalize_on_demand(1); + GC_set_finalizer_notifier(&FinalizerNotifier); + g_FinalizerThread.Start(); +#endif +#endif +} + +void* il2cpp_GC_Alloc(uintptr_t sz) +{ + return GC_MALLOC(sz); +} + +void* il2cpp_GC_AllocAtomic(uintptr_t sz) +{ + void* ptr = GC_MALLOC_ATOMIC(sz); + memset(ptr, 0, sz); + return ptr; +} + +void il2cpp_GC_AddRoots(void* low, void* high) +{ + GC_add_roots(low, high); +} + +bool il2cpp_GC_RegisterThread() +{ +#if defined(GC_THREADS) + int temp = 0; + GC_stack_base sb; + int res = GC_get_stack_base(&sb); + if (res != GC_SUCCESS) + sb.mem_base = &temp; + + res = GC_register_my_thread(&sb); + if ((res != GC_SUCCESS) && (res != GC_DUPLICATE)) + return false; + return true; +#else + return false; +#endif +} + +bool il2cpp_GC_UnregisterThread() +{ +#if defined(GC_THREADS) + int res = GC_unregister_my_thread(); + return res == GC_SUCCESS; +#else + return false; +#endif +} + +static void GC_CALLBACK FinalizerCallback(void* obj, void* cdata) +{ + ((IL2CPP_FINALIZER_FUNC)cdata)((cls_Object*)obj); +} + +void il2cpp_GC_RegisterFinalizer(cls_Object* obj, IL2CPP_FINALIZER_FUNC finalizer) +{ + IL2CPP_ASSERT(finalizer != nullptr); + GC_REGISTER_FINALIZER_NO_ORDER(obj, &FinalizerCallback, (void*)finalizer, nullptr, nullptr); +} + +void il2cpp_GC_Collect() +{ + GC_gcollect(); +} + +#if defined(IL2CPP_PATCH_LLVM) +extern "C" void* _il2cpp_GC_PatchCalloc(uintptr_t nelem, uintptr_t sz) +{ + if (nelem != 1 && sz == 1) + return il2cpp_GC_AllocAtomic(nelem); + else if (nelem == 1 && sz != 1) + return il2cpp_GC_Alloc(sz); + else + IL2CPP_TRAP; + return nullptr; +} +#endif diff --git a/pool/shard007/C++/0091026_test_eta3.cpp b/pool/shard007/C++/0091026_test_eta3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..698fced56788e5f1cc106b1910dc7c01c1504391 --- /dev/null +++ b/pool/shard007/C++/0091026_test_eta3.cpp @@ -0,0 +1,107 @@ +/// The test main file for library Eta3Traj +/// Zhiang Chen, 4/2016 + +#include<ros/ros.h> +#include <eta3_spline/eta3_spline.h> +#include <geometry_msgs/PointStamped.h> +#include <nav_msgs/Odometry.h> +#include <std_msgs/Float32.h> +#include <nav_msgs/Path.h> + +double convertPlanarQuat2Psi(geometry_msgs::Quaternion quaternion) { + double quat_z = quaternion.z; + double quat_w = quaternion.w; + double psi = 2.0 * atan2(quat_z, quat_w); // cheap conversion from quaternion to heading for planar motion + return psi; +} + +int main(int argc, char** argv) { + ros::init(argc, argv, "eta3_spline"); //node name + ros::NodeHandle nh; + ros::Publisher desired_state_publisher = nh.advertise<nav_msgs::Odometry>("/desState", 1); + ros::Publisher x_publisher = nh.advertise<std_msgs::Float32>("/x_position", 1); + ros::Publisher y_publisher = nh.advertise<std_msgs::Float32>("/y_position", 1); + ros::Publisher theta_publisher = nh.advertise<std_msgs::Float32>("/des_theta_position", 1); + std::vector<double> eta; + std::vector<double> kappa; + double d_t; + bool got_traj; + std::vector<geometry_msgs::PointStamped> poses; + Eta3Traj Et; + geometry_msgs::PointStamped pose; + std::vector<nav_msgs::Odometry> traj; + std::vector<nav_msgs::Odometry> traj_t; + eta.resize(6); + kappa.resize(4); + int n; + + eta[0]=5; + eta[1]=5; + eta[2]=2; + eta[3]=2; + eta[4]=2; + eta[5]=2; + Et.setEta(eta); + + poses.clear(); + pose.header.frame_id = "des_frame"; + pose.point.x = 0; + pose.point.y = 0; + pose.point.z = 0; + poses.push_back(pose); + + pose.point.x = 10; + pose.point.y = 0; + pose.point.z = 0.78; + poses.push_back(pose); + + pose.point.x = 10; + pose.point.y = 10; + pose.point.z = 2.3; + poses.push_back(pose); + + pose.point.x = 0; + pose.point.y = 10; + pose.point.z = -2.3; + poses.push_back(pose); + + pose.point.x = 0; + pose.point.y = 0; + pose.point.z = 0; + poses.push_back(pose); + + got_traj=false; + Et.setPoses(poses); + got_traj = Et.getTraj(traj,d_t); // It cannot be used to set the d_t but get the d_t + if(!got_traj) + { + ROS_ERROR("Failed to get the trajectory!"); + return 0; + } + n = traj.size(); + for(int j=0; j<n; j++) + { + traj_t.push_back(traj[j]); + } + + + /*nav_msgs::Path g_path; + geometry_msgs::PoseStamped g_pose; + ros::Publisher path_publisher = nh.advertise<nav_msgs::Path>("/path", 1); + n = traj_t.size(); + nav_msgs::Odometry odom; + g_path.header.frame_id = "odom_frame"; + for (int j=0; j<n; j++) + { + odom = traj_t[j]; + g_pose.pose = odom.pose.pose; + g_path.poses.push_back(g_pose); + } + while(ros::ok()) + { + path_publisher.publish(g_path); + ros::Duration(0.02).sleep(); + }*/ + Et.runTraj2(traj); + return 0; +} diff --git a/pool/shard007/C++/0091046_playpenaltyour.cpp b/pool/shard007/C++/0091046_playpenaltyour.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2f9c97ab3394aa6b8f71af02c0b077c5320e5e1b --- /dev/null +++ b/pool/shard007/C++/0091046_playpenaltyour.cpp @@ -0,0 +1,159 @@ +#include "playpenaltyour.h" + +PlayPenaltyOur::PlayPenaltyOur(WorldModel *worldmodel, QObject *parent) : + Play("PlayPenaltyOur", worldmodel, parent) +{ + tGoalie=new TacticGoalie(wm); + tDefenderLeft=new TacticDefender(wm); + tDefenderRight=new TacticDefender(wm); + tAttackerLeft = new TacticAttacker(wm); + tAttackerRight = new TacticAttacker(wm); + penaltyKicker=new TacticPenaltyKicker(wm); +} + +int PlayPenaltyOur::enterCondition() +{ + if(wm->cmgs.ourPenaltyKick()) + { + if( wm->gs != wm->gs_last ) + penaltyKicker->resetEverything(); + + return 100; + } + else + return 0; +} + +void PlayPenaltyOur::setTactics(int index) +{ + switch (wm->ourRobot[index].Role) { + case AgentRole::Golie: + tactics[index] = tGoalie; + break; + case AgentRole::DefenderLeft: + tactics[index] = tDefenderLeft; + break; + case AgentRole::DefenderRight: + tactics[index] = tDefenderRight; + break; + case AgentRole::AttackerMid: + tactics[index] = penaltyKicker; + break; + case AgentRole::AttackerRight: + tactics[index] = tAttackerRight; + break; + case AgentRole::AttackerLeft: + tactics[index] = tAttackerLeft; + break; + default: + break; + } +} + +void PlayPenaltyOur::setPositions() +{ + Position leftDefPos,rightDefPos,goaliePos; + int leftID = -1, rightID = -1 , midID = -1; + bool leftNav, rightNav; + + if( wm->ourRobot[tDefenderLeft->getID()].Role == AgentRole::DefenderLeft ) + leftID = tDefenderLeft->getID(); + + if( wm->ourRobot[tDefenderRight->getID()].Role == AgentRole::DefenderRight ) + rightID = tDefenderRight->getID(); + + if( leftChecker > 100 || leftID == -1 ) + midID = rightID; + + if( rightChecker > 100 || rightID == -1) + midID = leftID; + + zonePositions(leftID,rightID,midID,goaliePos,leftDefPos,leftNav,rightDefPos,rightNav); + + tGoalie->setIdlePosition(goaliePos); + tDefenderLeft->setIdlePosition(leftDefPos); + tDefenderLeft->setUseNav(leftNav); + tDefenderRight->setIdlePosition(rightDefPos); + tDefenderRight->setUseNav(rightNav); + + if( leftID != -1) + { + if( (wm->ourRobot[leftID].pos.loc - leftDefPos.loc).length() > 250 ) + leftChecker++; + else + leftChecker = 0; + } + + if( rightID != -1) + { + if( (wm->ourRobot[rightID].pos.loc - rightDefPos.loc).length() > 250 ) + rightChecker++; + else + rightChecker = 0; + } + + Vector2D pos; + pos = Vector2D(Field::ourPenaltyParallelLineCenter.x,Field::ourPenaltyParallelLineCenter.y + (Field::MaxY*0.75)); + tAttackerRight->setIdlePosition(wm->kn->AdjustKickPoint(pos,Field::oppGoalCenter)); + + pos = Vector2D(Field::ourPenaltyParallelLineCenter.x,Field::ourPenaltyParallelLineCenter.y - (Field::MaxY*0.75)); + tAttackerLeft->setIdlePosition(wm->kn->AdjustKickPoint(pos,Field::oppGoalCenter)); +} + +void PlayPenaltyOur::initRole() +{ + QList<int> activeAgents=wm->kn->ActiveAgents(); + activeAgents.removeOne(wm->ref_goalie_our); + + wm->ourRobot[wm->ref_goalie_our].Role = AgentRole::Golie; + + switch (activeAgents.length()) { + + case 1: + wm->ourRobot[activeAgents.takeFirst()].Role = AgentRole::AttackerMid; + break; + case 2: + wm->ourRobot[activeAgents.takeFirst()].Role = AgentRole::DefenderLeft; + wm->ourRobot[activeAgents.takeFirst()].Role = AgentRole::AttackerMid; + break; + case 3: + wm->ourRobot[activeAgents.takeFirst()].Role = AgentRole::DefenderLeft; + wm->ourRobot[activeAgents.takeFirst()].Role = AgentRole::DefenderRight; + wm->ourRobot[activeAgents.takeFirst()].Role = AgentRole::AttackerMid; + break; + case 4: + wm->ourRobot[activeAgents.takeFirst()].Role = AgentRole::DefenderLeft; + wm->ourRobot[activeAgents.takeFirst()].Role = AgentRole::DefenderRight; + wm->ourRobot[activeAgents.takeFirst()].Role = AgentRole::AttackerMid; + wm->ourRobot[activeAgents.takeFirst()].Role = AgentRole::AttackerLeft; + break; + case 5: + wm->ourRobot[activeAgents.takeFirst()].Role = AgentRole::DefenderRight; + wm->ourRobot[activeAgents.takeFirst()].Role = AgentRole::DefenderLeft; + wm->ourRobot[activeAgents.takeFirst()].Role = AgentRole::AttackerMid; + wm->ourRobot[activeAgents.takeFirst()].Role = AgentRole::AttackerRight; + wm->ourRobot[activeAgents.takeFirst()].Role = AgentRole::AttackerLeft; + break; + } +} + +void PlayPenaltyOur::execute() +{ + QList<int> activeAgents=wm->kn->ActiveAgents(); + + initRole(); + + for(int i=0;i<activeAgents.size();i++) + { + wm->ourRobot[activeAgents.at(i)].Status = AgentStatus::Idle; + } + + for(int i=0;i<activeAgents.size();i++) + { + setTactics(activeAgents.at(i)); + } + + setPositions(); + + wm->ourRobot[penaltyKicker->getID()].Status = AgentStatus::Kicking; +} diff --git a/pool/shard007/C++/0091048_SetUserSettingsRequest.cpp b/pool/shard007/C++/0091048_SetUserSettingsRequest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7abacaa2c3a3a24e3611329d4f8d18e08a47e38b --- /dev/null +++ b/pool/shard007/C++/0091048_SetUserSettingsRequest.cpp @@ -0,0 +1,65 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include <aws/cognito-idp/model/SetUserSettingsRequest.h> +#include <aws/core/utils/json/JsonSerializer.h> + +#include <utility> + +using namespace Aws::CognitoIdentityProvider::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +SetUserSettingsRequest::SetUserSettingsRequest() : + m_accessTokenHasBeenSet(false), + m_mFAOptionsHasBeenSet(false) +{ +} + +Aws::String SetUserSettingsRequest::SerializePayload() const +{ + JsonValue payload; + + if(m_accessTokenHasBeenSet) + { + payload.WithString("AccessToken", m_accessToken); + + } + + if(m_mFAOptionsHasBeenSet) + { + Array<JsonValue> mFAOptionsJsonList(m_mFAOptions.size()); + for(unsigned mFAOptionsIndex = 0; mFAOptionsIndex < mFAOptionsJsonList.GetLength(); ++mFAOptionsIndex) + { + mFAOptionsJsonList[mFAOptionsIndex].AsObject(m_mFAOptions[mFAOptionsIndex].Jsonize()); + } + payload.WithArray("MFAOptions", std::move(mFAOptionsJsonList)); + + } + + return payload.View().WriteReadable(); +} + +Aws::Http::HeaderValueCollection SetUserSettingsRequest::GetRequestSpecificHeaders() const +{ + Aws::Http::HeaderValueCollection headers; + headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSCognitoIdentityProviderService.SetUserSettings")); + return headers; + +} + + + + diff --git a/pool/shard007/C++/0091050_TriangleGenerator.cpp b/pool/shard007/C++/0091050_TriangleGenerator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..15b3680d8d3ba1f539c413cedfa53dd02a5bb615 --- /dev/null +++ b/pool/shard007/C++/0091050_TriangleGenerator.cpp @@ -0,0 +1,32 @@ +#include "aquila/global.h" +#include "aquila/source/generator/TriangleGenerator.h" +#include "UnitTest++/UnitTest++.h" +#include <algorithm> +#include <cstddef> + +SUITE(TriangleGenerator) +{ + // sample frequency is fixed at 1 kHz + Aquila::TriangleGenerator gen(1000); + + TEST(Amplitude) + { + gen.setAmplitude(250).setFrequency(10).generate(100); + auto min = *std::min_element(gen.begin(), gen.end()); + CHECK_EQUAL(-250, min); + } + + TEST(SymmetricTriangle) + { + gen.setWidth(0.5).setAmplitude(250).setFrequency(10).generate(100); + auto min = *std::min_element(gen.begin(), gen.end()); + CHECK_EQUAL(-250, min); + } + + TEST(UnevenPeriod) + { + gen.setWidth(0.5).setAmplitude(250).setFrequency(13).generate(100); + auto min = *std::min_element(gen.begin(), gen.end()); + CHECK_EQUAL(-250, min); + } +} diff --git a/pool/shard007/C++/0091052_coincontroltreewidget.cpp b/pool/shard007/C++/0091052_coincontroltreewidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..15d96bdc583b057a0c852b5f1683caa87bc2a02f --- /dev/null +++ b/pool/shard007/C++/0091052_coincontroltreewidget.cpp @@ -0,0 +1,31 @@ +#include "coincontroltreewidget.h" +#include "coincontroldialog.h" + +CoinControlTreeWidget::CoinControlTreeWidget(QWidget *parent) : + QTreeWidget(parent) +{ + +} + +void CoinControlTreeWidget::keyPressEvent(QKeyEvent *event) +{ + if (event->key() == Qt::Key_Space) // press spacebar -> select checkbox + { + event->ignore(); + int COLUMN_CHECKBOX = 0; + this->currentItem()->setCheckState(COLUMN_CHECKBOX, ((this->currentItem()->checkState(COLUMN_CHECKBOX) == Qt::Checked) ? Qt::Unchecked : Qt::Checked)); + } + else if (event->key() == Qt::Key_Escape) // press esc -> close dialog + { + event->ignore(); + CoinControlDialog *coinControlDialog = (CoinControlDialog*)this->parentWidget(); + coinControlDialog->done(QDialog::Accepted); + } + else + { + this->QTreeWidget::keyPressEvent(event); + } +} +#ifdef _MSC_VER +#include "coincontroltreewidget.moc" +#endif \ No newline at end of file diff --git a/pool/shard007/C++/0091053_tile.cpp b/pool/shard007/C++/0091053_tile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c36b7fc7dff713ec5775c62e56ed5e0638092a44 --- /dev/null +++ b/pool/shard007/C++/0091053_tile.cpp @@ -0,0 +1,74 @@ +#include "tile.hpp" +#include "vector_tile.pb.h" + +#include <google/protobuf/io/zero_copy_stream_impl.h> +#include <google/protobuf/io/gzip_stream.h> + +namespace avecado { + +tile::tile(unsigned int z_, unsigned int x_, unsigned int y_) + : z(z_), x(x_), y(y_), m_mapnik_tile(new mapnik::vector::tile) { +} + +tile::~tile() { +} + +std::string tile::get_data(int compression_level) const { + std::ostringstream buffer; + buffer << tile_gzip(*this, compression_level); + return buffer.str(); +} + +void tile::from_string(const std::string &str) { + tile t(z, x, y); + std::istringstream buffer(str); + buffer >> t; + m_mapnik_tile.swap(t.m_mapnik_tile); +} + +mapnik::vector::tile const &tile::mapnik_tile() const { + return *m_mapnik_tile; +} + +mapnik::vector::tile &tile::mapnik_tile() { + return *m_mapnik_tile; +} + +std::istream &operator>>(std::istream &in, tile &t) { + google::protobuf::io::IstreamInputStream stream(&in); + google::protobuf::io::GzipInputStream gz_stream(&stream); + bool read_ok = t.mapnik_tile().ParseFromZeroCopyStream(&gz_stream); + + if (!read_ok) { + throw std::runtime_error("Unable to read tile from input stream."); + } + + return in; +} + +std::ostream &operator<<(std::ostream &out, const tile_gzip &t) { + google::protobuf::io::OstreamOutputStream stream(&out); + bool write_ok = false; + + if (t.compression_level_ == 0) { + write_ok = t.tile_.mapnik_tile().SerializeToZeroCopyStream(&stream); + + } else { + google::protobuf::io::GzipOutputStream::Options options; + if (t.compression_level_ >= 0) { + options.compression_level = t.compression_level_; + } + options.format = google::protobuf::io::GzipOutputStream::ZLIB; + google::protobuf::io::GzipOutputStream gz_stream(&stream, options); + + write_ok = t.tile_.mapnik_tile().SerializeToZeroCopyStream(&gz_stream); + } + + if (!write_ok) { + throw std::runtime_error("Unable to write tile to output stream."); + } + + return out; +} + +} // namespace avecado diff --git a/pool/shard007/C++/0091055_WatchDog.cpp b/pool/shard007/C++/0091055_WatchDog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a7f5e8f5c2b1ab25466af9165026bb3a76a90caf --- /dev/null +++ b/pool/shard007/C++/0091055_WatchDog.cpp @@ -0,0 +1,199 @@ +/* Copyright (C) 2003 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +#include <ndb_global.h> +#include <my_pthread.h> +#include <sys/times.h> + +#include "WatchDog.hpp" +#include "GlobalData.hpp" +#include <NdbOut.hpp> +#include <NdbSleep.h> +#include <ErrorHandlingMacros.hpp> +#include <EventLogger.hpp> + +#include <NdbTick.h> + +extern EventLogger g_eventLogger; + +extern "C" +void* +runWatchDog(void* w){ + ((WatchDog*)w)->run(); + return NULL; +} + +WatchDog::WatchDog(Uint32 interval) : + theIPValue(globalData.getWatchDogPtr()) +{ + setCheckInterval(interval); + theStop = false; + theThreadPtr = 0; +} + +WatchDog::~WatchDog(){ + doStop(); +} + +Uint32 +WatchDog::setCheckInterval(Uint32 interval){ + // An interval of less than 70ms is not acceptable + return theInterval = (interval < 70 ? 70 : interval); +} + +void +WatchDog::doStart(){ + theStop = false; + theThreadPtr = NdbThread_Create(runWatchDog, + (void**)this, + 32768, + "ndb_watchdog", + NDB_THREAD_PRIO_HIGH); +} + +void +WatchDog::doStop(){ + void *status; + theStop = true; + if(theThreadPtr){ + NdbThread_WaitFor(theThreadPtr, &status); + NdbThread_Destroy(&theThreadPtr); + } +} + +const char *get_action(Uint32 IPValue) +{ + const char *action; + switch (IPValue) { + case 1: + action = "Job Handling"; + break; + case 2: + action = "Scanning Timers"; + break; + case 3: + action = "External I/O"; + break; + case 4: + action = "Print Job Buffers at crash"; + break; + case 5: + action = "Checking connections"; + break; + case 6: + action = "Performing Send"; + break; + case 7: + action = "Polling for Receive"; + break; + case 8: + action = "Performing Receive"; + break; + case 9: + action = "Allocating memory"; + break; + default: + action = "Unknown place"; + break; + }//switch + return action; +} + +void +WatchDog::run() +{ + unsigned int anIPValue, sleep_time; + unsigned int oldIPValue = 0; + unsigned int theIntervalCheck = theInterval; + struct MicroSecondTimer start_time, last_time, now; + NdbTick_getMicroTimer(&start_time); + last_time = start_time; + + // WatchDog for the single threaded NDB + while (!theStop) + { + sleep_time= 100; + + NdbSleep_MilliSleep(sleep_time); + if(theStop) + break; + + NdbTick_getMicroTimer(&now); + if (NdbTick_getMicrosPassed(last_time, now)/1000 > sleep_time*2) + { + struct tms my_tms; + times(&my_tms); + g_eventLogger.info("Watchdog: User time: %llu System time: %llu", + (Uint64)my_tms.tms_utime, + (Uint64)my_tms.tms_stime); + g_eventLogger.warning("Watchdog: Warning overslept %u ms, expected %u ms.", + NdbTick_getMicrosPassed(last_time, now)/1000, + sleep_time); + } + last_time = now; + + // Verify that the IP thread is not stuck in a loop + anIPValue = *theIPValue; + if (anIPValue != 0) + { + oldIPValue = anIPValue; + globalData.incrementWatchDogCounter(0); + NdbTick_getMicroTimer(&start_time); + theIntervalCheck = theInterval; + } + else + { + int warn = 1; + Uint32 elapsed = NdbTick_getMicrosPassed(start_time, now)/1000; + /* + oldIPValue == 9 indicates malloc going on, this can take some time + so only warn if we pass the watchdog interval + */ + if (oldIPValue == 9) + if (elapsed < theIntervalCheck) + warn = 0; + else + theIntervalCheck += theInterval; + + if (warn) + { + const char *last_stuck_action = get_action(oldIPValue); + g_eventLogger.warning("Ndb kernel is stuck in: %s", last_stuck_action); + { + struct tms my_tms; + times(&my_tms); + g_eventLogger.info("Watchdog: User time: %llu System time: %llu", + (Uint64)my_tms.tms_utime, + (Uint64)my_tms.tms_stime); + } + if (elapsed > 3 * theInterval) + { + shutdownSystem(last_stuck_action); + } + } + } + } + return; +} + +void +WatchDog::shutdownSystem(const char *last_stuck_action){ + + ErrorReporter::handleError(NDBD_EXIT_WATCHDOG_TERMINATE, + last_stuck_action, + __FILE__, + NST_Watchdog); +} diff --git a/pool/shard007/C++/0091056_GetOpt.cpp b/pool/shard007/C++/0091056_GetOpt.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ee579f6b6625c1c60c70f2e20a39a591284134ac --- /dev/null +++ b/pool/shard007/C++/0091056_GetOpt.cpp @@ -0,0 +1,165 @@ +/* GetOpt - getopt as a c++ class. + * + * The MIT License (MIT) + * + * Copyright (c) 2015 Klaus Beyer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include <stdio.h> // EOF const +#include <iostream> +#include <fstream> +#include <algorithm> + +#include "GetOpt.h" + +static std::string removeLeftWhiteSpaces( std::string text ) +{ + std::string newtext; + auto pos = text.find_first_not_of( " \t\n" ); + if( pos != std::string::npos ) { + newtext = text.substr( pos, text.length() - pos ); + } else { + newtext = text; + } + return newtext; +} + +GetOpt::GetOpt( int argc, char* argv[], const std::string optstring, const std::string filename ) + : index( 1u ) + , optionString( optstring ) +{ + + // Put cmd line options into front, they win over the file options. + for(int i = 0; i < argc; ++i) { + argStrings.push_back(argv[i]); + } + + + if( !filename.empty() ) { + std::ifstream file; + file.open( filename ); + std::string line; + while( getline( file, line ) ) { + if( line[0] == '-' ) { + // Remove spaces between option and its argument. + if( line[2] == ' ' ) { + auto arg = line.substr( 2 ); + line = line.substr( 0, 2 ) + removeLeftWhiteSpaces( arg ); + } + } + auto found = std::count_if(std::begin(argStrings), std::end(argStrings), [line](auto s) { return line == s; }); + if(found == 0) { + argStrings.push_back(line); + } + } + } + + argCount = argStrings.size(); +} + +char GetOpt::operator()() +{ + optionArgument.clear(); + errorText.clear(); + + // Is first character of option string a ':' + if( optionString[0] == ':' ) { + errorText = argStrings[0] + std::string( ": missing option argument in " ) + optionString + "\n"; + optionString.erase( 0, 1 ); + return ':'; + } + + // Is end of argument list? + if( index >= argCount ) { + return EOF; + } + + // Is a non option argument reached? + if( argStrings[index][0] != '-' ) { + if( argStrings[index][1] == '\0' ) + return EOF; + if( index == argCount - 1 ) { + return EOF; + } + std::rotate(argStrings.begin()+index, argStrings.begin()+index+1, argStrings.end()); + --argCount; + return this->operator()(); + } + + // Is end of argument list reached? + if( argStrings[index][0] == '-' && argStrings[index][1] == '-' ) { + index++; + return EOF; + } + + auto scan = argStrings[index]; + index++; + + // Skip '-' + // Is current character in the option string + char c = scan[1]; + auto place = optionString.find_first_of( c ); + if( place == std::string::npos || c == ':' ) { + errorText = argStrings[0] + std::string( ": unknown option -" ) + c + "\n"; + return '?'; + } + + // Check if an additional argument is needed. + place++; + if( optionString[place] == ':' ) { + place++; + bool argIsOptional = optionString[place] == ':'; + // Check if no space is between option and its argument. + if( scan[2] != '\0' ) { + optionArgument = scan.substr( 2 ); + } else if( index < argCount ) { + if( argStrings[index][0] != '-' ) { + optionArgument = argStrings[index]; + index++; + } else if( !argIsOptional ) { + errorText = argStrings[0] + std::string( ": option requires argument -" ) + c + "\n"; + return ':'; + } + } else if( !argIsOptional ) { + errorText = argStrings[0] + std::string( ": option requires argument -" ) + c + "\n"; + return ':'; + } + } + return c; +} + +std::vector<std::string> GetOpt::getRemainingArguments() +{ + std::vector<std::string> args(argStrings.begin() + index, argStrings.end()); + return args; +} + + +char GetOpt::iterator::operator*() +{ + auto ret = getopt->operator()(); + if( ret == EOF ) { + position = getopt->argCount - 1; // Set iterator to the end + } else { + position = getopt->index - 1; // In case index has advanced more than one position. + } + + return ret; +} diff --git a/pool/shard007/C++/0091061_ElasticGpuSpecificationResponse.cpp b/pool/shard007/C++/0091061_ElasticGpuSpecificationResponse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..015060eb20652a6b817f052939ea346ea8724de2 --- /dev/null +++ b/pool/shard007/C++/0091061_ElasticGpuSpecificationResponse.cpp @@ -0,0 +1,70 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include <aws/ec2/model/ElasticGpuSpecificationResponse.h> +#include <aws/core/utils/xml/XmlSerializer.h> +#include <aws/core/utils/StringUtils.h> +#include <aws/core/utils/memory/stl/AWSStringStream.h> + +#include <utility> + +using namespace Aws::Utils::Xml; +using namespace Aws::Utils; + +namespace Aws +{ +namespace EC2 +{ +namespace Model +{ + +ElasticGpuSpecificationResponse::ElasticGpuSpecificationResponse() : + m_typeHasBeenSet(false) +{ +} + +ElasticGpuSpecificationResponse::ElasticGpuSpecificationResponse(const XmlNode& xmlNode) : + m_typeHasBeenSet(false) +{ + *this = xmlNode; +} + +ElasticGpuSpecificationResponse& ElasticGpuSpecificationResponse::operator =(const XmlNode& xmlNode) +{ + XmlNode resultNode = xmlNode; + + if(!resultNode.IsNull()) + { + XmlNode typeNode = resultNode.FirstChild("type"); + if(!typeNode.IsNull()) + { + m_type = Aws::Utils::Xml::DecodeEscapedXmlText(typeNode.GetText()); + m_typeHasBeenSet = true; + } + } + + return *this; +} + +void ElasticGpuSpecificationResponse::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const +{ + if(m_typeHasBeenSet) + { + oStream << location << index << locationValue << ".Type=" << StringUtils::URLEncode(m_type.c_str()) << "&"; + } + +} + +void ElasticGpuSpecificationResponse::OutputToStream(Aws::OStream& oStream, const char* location) const +{ + if(m_typeHasBeenSet) + { + oStream << location << ".Type=" << StringUtils::URLEncode(m_type.c_str()) << "&"; + } +} + +} // namespace Model +} // namespace EC2 +} // namespace Aws diff --git a/pool/shard007/C++/0091070_diagonalize.cpp b/pool/shard007/C++/0091070_diagonalize.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4162e08c06b06c94ba2fa60416fc264991e7f55d --- /dev/null +++ b/pool/shard007/C++/0091070_diagonalize.cpp @@ -0,0 +1,110 @@ +/*The MIT License(MIT) + + Copyright(c)[2015][Dylan Brown] + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files(the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and / or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions : + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.*/ + +#include "main.h" +#include "diagonalize.h" +#define _USE_MATH_DEFINES +#include<math.h> +#include<stdio.h> +#include<stdlib.h> +#include<string.h> +#include<iostream> +#include "mkl.h" +#include "mkl_dfti.h" +#include "mkl_lapacke.h" +#include<float.h> +#include<fstream> +#include "fitsio.h" +#include<iomanip> + +#if !defined(MKL_ILP64) + #define LI "%li" + #else + #define LI "%lli" +#endif + +#define HBAR 1.054e-34 +#define Nm 3 + + +int diagonalize(double *pMinusA, MKL_Complex16 *kinEnergy, int count, int maxCount, double rampFac, struct simPars pars) +{ + double H1, H2, H3; + MKL_INT info, n = Nm, lda = 3, ldvl = 3, ldvr = 3; + MKL_Complex16 eigenVals[Nm], vl[Nm*Nm], vr[Nm*Nm]; + double *delta; + delta = (double*)mkl_malloc(pars.nY*sizeof(double), 64); + int index; + int j = 0; + double min; + if(count > maxCount) + { + return 0; + } + for(int i = 0; i < pars.nY; ++i) + { + delta[i] = rampFac*pars.detuningGradient*pars.y[i]; + + } + #pragma omp parallel for private(j, index, min, H1, H2, H3, eigenVals) + for(int i = 0; i < pars.nY; ++i) + { + for(int j = 0; j < pars.nX; ++j) + { + index = i*pars.nY + j; + + H1 = (pow(HBAR,2))*pow((pars.kX[j] + 2*pars.kRaman),2)/(2*pars.mass) - HBAR*delta[i]; + H2 = (pow(HBAR,2))*pow(pars.kX[j],2)/(2*pars.mass); + H3 = (pow(HBAR,2))*pow((pars.kX[j] - 2*pars.kRaman),2)/(2*pars.mass) + HBAR*delta[i]; + + MKL_Complex16 Ht[9] = {{H1,0}, {pars.omegaR/2.0,0}, {0,0}, {pars.omegaR/2.0,0}, {H2,0}, {pars.omegaR/2.0,0}, {0,0}, {pars.omegaR/2.0,0}, {H3,0}}; + + info = LAPACKE_zgeev(LAPACK_ROW_MAJOR, 'N', 'N', n, Ht, lda, eigenVals, vl, ldvl, vr, ldvr); + + if(eigenVals[0].real < eigenVals[1].real) + { + min = std::min(eigenVals[0].real, eigenVals[2].real); + } + else + { + min = std::min(eigenVals[1].real, eigenVals[2].real); + } + + pMinusA[index] = min; + + } + } + for (int i = 0; i < pars.N; ++i) + { + kinEnergy[i].real = cos((0.5*pars.dt / HBAR) * pMinusA[i]); + kinEnergy[i].imag = -1*sin((0.5*pars.dt / HBAR) * pMinusA[i]); + } + + goto cleanup; + + cleanup: + mkl_free(delta); + if(info != 0) exit(EXIT_FAILURE); + return 0; + +} + diff --git a/pool/shard007/C++/0091073_VBoxUtils-win.cpp b/pool/shard007/C++/0091073_VBoxUtils-win.cpp new file mode 100644 index 0000000000000000000000000000000000000000..42cff6077b0da0a848a91b75e9de29a158e0c60f --- /dev/null +++ b/pool/shard007/C++/0091073_VBoxUtils-win.cpp @@ -0,0 +1,79 @@ +/* $Id$ */ +/** @file + * + * VBox frontends: Qt GUI ("VirtualBox"): + * Utility classes and functions for handling Win specific tasks + */ + +/* + * Copyright (C) 2010-2011 Oracle Corporation + * + * This file is part of VirtualBox Open Source Edition (OSE), as + * available from http://www.virtualbox.org. This file is free software; + * you can redistribute it and/or modify it under the terms of the GNU + * General Public License (GPL) as published by the Free Software + * Foundation, in version 2 as it comes in the "COPYING" file of the + * VirtualBox OSE distribution. VirtualBox OSE is distributed in the + * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. + */ + +/* Includes: */ +#include "VBoxUtils-win.h" + +/* Namespace for native window sub-system functions: */ +namespace NativeWindowSubsystem +{ + /* Enumerates visible always-on-top (top-most) windows: */ + BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam); + /* Contain visible top-most-window rectangles: */ + QList<QRect> topMostRects; +} + +/* Enumerates visible always-on-top (top-most) windows: */ +BOOL CALLBACK NativeWindowSubsystem::EnumWindowsProc(HWND hWnd, LPARAM /* lParam */) +{ + /* Ignore NULL HWNDs: */ + if (!hWnd) + return TRUE; + + /* Ignore hidden windows: */ + if (!IsWindowVisible(hWnd)) + return TRUE; + + /* Get window style: */ + LONG uStyle = GetWindowLong(hWnd, GWL_STYLE); + /* Ignore minimized windows: */ + if (uStyle & WS_MINIMIZE) + return TRUE; + + /* Get extended window style: */ + LONG uExtendedStyle = GetWindowLong(hWnd, GWL_EXSTYLE); + /* Ignore non-top-most windows: */ + if (!(uExtendedStyle & WS_EX_TOPMOST)) + return TRUE; + + /* Get that window rectangle: */ + RECT rect; + GetWindowRect(hWnd, &rect); + topMostRects << QRect(QPoint(rect.left, rect.top), QPoint(rect.right - 1, rect.bottom - 1)); + + /* Proceed to the next window: */ + return TRUE; +} + +/* Returns area covered by visible always-on-top (top-most) windows: */ +const QRegion NativeWindowSubsystem::areaCoveredByTopMostWindows() +{ + /* Prepare the top-most region: */ + QRegion topMostRegion; + /* Initialize the list of the top-most rectangles: */ + topMostRects.clear(); + /* Populate the list of top-most rectangles: */ + EnumWindows((WNDENUMPROC)EnumWindowsProc, 0); + /* Update the top-most region with top-most rectangles: */ + for (int iRectIndex = 0; iRectIndex < topMostRects.size(); ++iRectIndex) + topMostRegion += topMostRects[iRectIndex]; + /* Return top-most region: */ + return topMostRegion; +} + diff --git a/pool/shard007/C++/0091079_TimeSeriesWithMinMaxTest.cpp b/pool/shard007/C++/0091079_TimeSeriesWithMinMaxTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..13dd39143484ffce5af4a90e5528d113b0fcf6cd --- /dev/null +++ b/pool/shard007/C++/0091079_TimeSeriesWithMinMaxTest.cpp @@ -0,0 +1,71 @@ +// Copyright 2004-present Facebook. All Rights Reserved. +#include "fboss/lib/TimeSeriesWithMinMax.h" + +#include <gtest/gtest.h> +#include <chrono> +#include <thread> + +using namespace facebook::fboss; + +using namespace std::chrono; +using namespace std::this_thread; + +TEST(TimeSeriesWithMinMax, BasicTest) { + TimeSeriesWithMinMax<int> buffer(seconds(3), seconds(1)); + + buffer.addValue(5); + buffer.addValue(7); + buffer.addValue(3); + EXPECT_EQ(buffer.getMax(), 7); + EXPECT_EQ(buffer.getMin(), 3); + + /* sleep override */ + sleep_for(seconds(3)); + buffer.addValue(2); + buffer.addValue(5, std::chrono::system_clock::now() - seconds(5)); + EXPECT_EQ(buffer.getMax(), 2); + EXPECT_EQ(buffer.getMin(), 2); + buffer.addValue(3, std::chrono::system_clock::now() - seconds(2)); + EXPECT_EQ(buffer.getMax(), 3); + EXPECT_EQ(buffer.getMin(), 2); + buffer.addValue(4, std::chrono::system_clock::now()); + EXPECT_EQ(buffer.getMax(), 4); + EXPECT_EQ(buffer.getMin(), 2); + + EXPECT_EQ( + buffer.getMax( + std::chrono::system_clock::now() - seconds(3), + std::chrono::system_clock::now() - seconds(2)), + 3); + EXPECT_EQ( + buffer.getMin( + std::chrono::system_clock::now() - seconds(3), + std::chrono::system_clock::now() - seconds(2)), + 3); + + /* sleep override */ + sleep_for(seconds(3)); + try { + buffer.getMax(); + assert(false); + } catch (std::runtime_error& e) { + } + + buffer.addValue(1); + buffer.addValue(2); + buffer.addValue(3); + EXPECT_EQ(buffer.getMax(), 3); + /* sleep override */ + sleep_for(seconds(1)); + + buffer.addValue(4); + buffer.addValue(5); + EXPECT_EQ(buffer.getMax(), 5); + /* sleep override */ + sleep_for(seconds(3)); + try { + buffer.getMax(); + assert(false); + } catch (std::runtime_error& e) { + } +} diff --git a/pool/shard007/C++/0091089_StackTest.cpp b/pool/shard007/C++/0091089_StackTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c7d4392afb4dd303f6c7633971ec177890b9a510 --- /dev/null +++ b/pool/shard007/C++/0091089_StackTest.cpp @@ -0,0 +1,230 @@ +// Copyright 2016 Adam B. Singer +// Contact: PracticalDesignBook@gmail.com +// +// This file is part of pdCalc. +// +// pdCalc is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 3 of the License, or +// (at your option) any later version. +// +// pdCalc is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with pdCalc; if not, see <http://www.gnu.org/licenses/>. + +#include "StackTest.h" +#include "src/backend/Stack.h" +#include "src/utilities/Observer.h" +#include "src/utilities/Exception.h" +#include <vector> + +using std::vector; +using std::vector; +using std::string; +using std::shared_ptr; +using std::unique_ptr; + +class StackChangedObserver : public pdCalc::Observer +{ +public: + StackChangedObserver(string name); + unsigned int changeCount() const { return changeCount_; } + void notifyImpl(std::shared_ptr<pdCalc::EventData>); + +private: + unsigned int changeCount_; +}; + +StackChangedObserver::StackChangedObserver(string name) +: pdCalc::Observer{name} +, changeCount_{0} +{ +} + +void StackChangedObserver::notifyImpl(std::shared_ptr<pdCalc::EventData>) +{ + ++changeCount_; +} + +class StackErrorObserver : public pdCalc::Observer +{ +public: + StackErrorObserver(string name); + const vector<string>& errorMessages() const { return messages_; } + const vector<pdCalc::StackEventData::ErrorConditions>& errors() const { return errors_; } + void notifyImpl(std::shared_ptr<pdCalc::EventData>); + +private: + vector<string> messages_; + vector<pdCalc::StackEventData::ErrorConditions> errors_; +}; + +StackErrorObserver::StackErrorObserver(string name) +: pdCalc::Observer{name} +{ +} + +void StackErrorObserver::notifyImpl(std::shared_ptr<pdCalc::EventData> data) +{ + std::shared_ptr<pdCalc::StackEventData> p = std::dynamic_pointer_cast<pdCalc::StackEventData>(data); + if(p) + { + messages_.push_back(p->message()); + errors_.push_back(p->error()); + } + + return; +} + +void StackTest::testPushPop() +{ + pdCalc::Stack& stack = pdCalc::Stack::Instance(); + stack.clear(); + StackChangedObserver* raw = new StackChangedObserver{"StackChangedObserver"}; + stack.attach( pdCalc::Stack::StackChanged, unique_ptr<pdCalc::Observer>{raw} ); + + QVERIFY( stack.size() == 0 ); + + vector<double> cur{ stack.getElements(100) }; + + QVERIFY( cur.size() == 0 ); + + stack.push(3.14159); + stack.push(17.3); + + QVERIFY( stack.size() == 2 ); + + stack.push(2.0); + + cur = stack.getElements(2); + + QCOMPARE( cur[0], 2.0 ); + QCOMPARE( cur[1], 17.3 ); + + cur = stack.getElements(3); + + QCOMPARE( cur[0], 2.0 ); + QCOMPARE( cur[1], 17.3 ); + QCOMPARE( cur[2], 3.14159 ); + + double val = stack.pop(); + QCOMPARE(val, 2.0); + QVERIFY( stack.size() == 2 ); + + cur = stack.getElements(2); + QCOMPARE( cur[0], 17.3 ); + QCOMPARE( cur[1], 3.14159 ); + + stack.push(3.0); + + cur = stack.getElements(3); + + QCOMPARE( cur[0], 3.0 ); + QCOMPARE( cur[1], 17.3 ); + QCOMPARE( cur[2], 3.14159 ); + + QCOMPARE(raw->changeCount(), 5u); + + stack.push(5.0, true); + stack.pop(true); + + QCOMPARE(raw->changeCount(), 5u); + + stack.clear(); + stack.detach(pdCalc::Stack::StackChanged, "StackChangedObserver"); + + return; +} + +void StackTest::testSwapTop() +{ + pdCalc::Stack& stack = pdCalc::Stack::Instance(); + stack.clear(); + StackChangedObserver* raw = new StackChangedObserver{"StackChangedObserver"}; + stack.attach( pdCalc::Stack::StackChanged, unique_ptr<pdCalc::Observer>{raw} ); + + QVERIFY( stack.size() == 0 ); + + stack.push(3.14159); + stack.push(17.3); + + vector<double> cur{ stack.getElements(2) }; + QCOMPARE( cur[0], 17.3 ); + QCOMPARE( cur[1], 3.14159 ); + + stack.swapTop(); + + cur = stack.getElements(2); + QCOMPARE( cur[0], 3.14159 ); + QCOMPARE( cur[1], 17.3 ); + + stack.push(2.0); + + cur = stack.getElements(3); + QCOMPARE( cur[0], 2.0 ); + QCOMPARE( cur[1], 3.14159 ); + QCOMPARE( cur[2], 17.3 ); + + stack.swapTop(); + + cur = stack.getElements(3); + QCOMPARE( cur[0], 3.14159 ); + QCOMPARE( cur[1], 2.0 ); + QCOMPARE( cur[2], 17.3 ); + + QCOMPARE(raw->changeCount(), 5u); + + stack.clear(); + stack.detach(pdCalc::Stack::StackChanged, "StackChangedObserver"); + + return; +} + +void StackTest::testErrors() +{ + pdCalc::Stack& stack = pdCalc::Stack::Instance(); + stack.clear(); + StackErrorObserver* raw = new StackErrorObserver{"StackErrorObserver"}; + stack.attach( pdCalc::Stack::StackError, unique_ptr<pdCalc::Observer>{raw} ); + + const string emptyMsg = pdCalc::StackEventData::Message(pdCalc::StackEventData::ErrorConditions::Empty); + const string swapMsg = pdCalc::StackEventData::Message(pdCalc::StackEventData::ErrorConditions::TooFewArguments); + + try + { + stack.pop(); + QVERIFY(false); + } + catch(pdCalc::Exception& e) + { + QCOMPARE(e.what(), emptyMsg); + } + + try + { + stack.swapTop(); + QVERIFY(false); + } + catch(pdCalc::Exception& e) + { + QCOMPARE(e.what(), swapMsg); + } + + const vector<string>& msgs { raw->errorMessages() }; + QVERIFY(msgs.size() == 2); + QCOMPARE(msgs[0], emptyMsg); + QCOMPARE(msgs[1], swapMsg); + + const vector<pdCalc::StackEventData::ErrorConditions> errors { raw->errors() }; + QVERIFY(errors.size() == 2); + QCOMPARE(errors[0], pdCalc::StackEventData::ErrorConditions::Empty); + QCOMPARE(errors[1], pdCalc::StackEventData::ErrorConditions::TooFewArguments); + + stack.clear(); + stack.detach(pdCalc::Stack::StackError, "StackErrorObserver"); +} + diff --git a/pool/shard007/C++/0091093_entityreference.cc b/pool/shard007/C++/0091093_entityreference.cc new file mode 100644 index 0000000000000000000000000000000000000000..3f83c01335616f64da20f804522deb52f9815fe4 --- /dev/null +++ b/pool/shard007/C++/0091093_entityreference.cc @@ -0,0 +1,57 @@ +/* entityreference.cc + * libxml++ and this file are copyright (C) 2000 by Ari Johnson, and + * are covered by the GNU Lesser General Public License, which should be + * included with libxml++ as the file COPYING. + */ + +#include <libxml++/nodes/entityreference.h> + +#include <libxml/tree.h> + +namespace xmlpp +{ + +EntityReference::EntityReference(xmlNode* node) +: Node(node) +{} + +EntityReference::~EntityReference() +{} + +Glib::ustring EntityReference::get_resolved_text() const +{ + Glib::ustring result; + + //Get the child xmlEntity node (there should only be 1). + auto cChild = cobj()->children; + if(cChild && cChild->type == XML_ENTITY_DECL) + { + auto cEntity = (xmlEntity*)cChild; + const xmlChar* pch = cEntity->content; + if(pch) + result = (const char*)pch; + } + + return result; +} + +Glib::ustring EntityReference::get_original_text() const +{ + Glib::ustring result; + + //Get the child xmlEntity node (there should only be 1). + auto cChild = cobj()->children; + if(cChild && cChild->type == XML_ENTITY_DECL) + { + auto cEntity = (xmlEntity*)cChild; + const xmlChar* pch = cEntity->orig; + if(pch) + result = (const char*)pch; + } + + return result; +} + + +} //namespace xmlpp + diff --git a/pool/shard007/C++/0091094_SoftMax.cpp b/pool/shard007/C++/0091094_SoftMax.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cfd88a13b8f96f9a167d3bd6ec666b3beb2edba4 --- /dev/null +++ b/pool/shard007/C++/0091094_SoftMax.cpp @@ -0,0 +1,44 @@ +#include <ATen/ATen.h> +#include <ATen/Config.h> +#include <ATen/NativeFunctions.h> + +#if !AT_MKLDNN_ENABLED() + +namespace at { +namespace native { + +Tensor mkldnn_softmax( + const Tensor& self, + const int64_t dim, + const bool half_to_float) { + AT_ERROR("mkldnn_softmax: ATen not compiled with MKLDNN support"); +} + +} // namespace native +} // namespace at + +#else // AT_MKLDNN_EBABLED + +#include <ATen/native/mkldnn/MKLDNNCommon.h> + +namespace at { +namespace native { + +Tensor mkldnn_softmax( + const Tensor& self, + const int64_t dim, + const bool half_to_float) { + AT_ASSERTM( + !half_to_float, + "softmax with half to float conversion is not supported on Mkldnn"); + const int64_t wrapped_dim = maybe_wrap_dim(dim, self.dim()); + ideep::tensor& x = itensor_from_mkldnn(self); + ideep::tensor y; + ideep::softmax_forward::compute<AllocForMKLDNN>(x, y, wrapped_dim); + return new_with_itensor_mkldnn(std::move(y), self.options()); +} + +} // namespace native +} // namespace at + +#endif // AT_MKLDNN_EBABLED diff --git a/pool/shard007/C++/0091104_graphdef_to_tfl_flatbuffer.cc b/pool/shard007/C++/0091104_graphdef_to_tfl_flatbuffer.cc new file mode 100644 index 0000000000000000000000000000000000000000..96962b470d77cfe48925c63812b883fe95623c3f --- /dev/null +++ b/pool/shard007/C++/0091104_graphdef_to_tfl_flatbuffer.cc @@ -0,0 +1,170 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "tensorflow/compiler/mlir/lite/python/graphdef_to_tfl_flatbuffer.h" + +#include <ostream> + +#include "mlir/IR/MLIRContext.h" // TF:local_config_mlir +#include "mlir/IR/Module.h" // TF:local_config_mlir +#include "tensorflow/compiler/mlir/lite/common/tfl_pass_config.h" +#include "tensorflow/compiler/mlir/lite/tf_tfl_passes.h" +#include "tensorflow/compiler/mlir/lite/tf_to_tfl_flatbuffer.h" +#include "tensorflow/compiler/mlir/tensorflow/translate/import_model.h" +#include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/protobuf/graph_debug_info.pb.h" +#include "tensorflow/lite/toco/model_flags.pb.h" +#include "tensorflow/lite/toco/toco_flags.pb.h" +#include "tensorflow/lite/toco/types.pb.h" + +namespace tensorflow { + +// Converts the toco::IODataType to tensorflow::DataType. Only contains the +// conversion mapping for constants defined in TFLite Python API. +DataType ConvertIODataTypeToDataType(toco::IODataType dtype) { + switch (dtype) { + case toco::IODataType::FLOAT: + return DT_FLOAT; + case toco::IODataType::QUANTIZED_UINT8: + return DT_QUINT8; + case toco::IODataType::INT8: + return DT_QINT8; + case toco::IODataType::INT32: + return DT_INT32; + case toco::IODataType::INT64: + return DT_INT64; + case toco::IODataType::STRING: + return DT_STRING; + case toco::IODataType::BOOL: + return DT_BOOL; + default: + return DT_INVALID; + } +} + +// Give a warning for any unused flags that have been specified. +void WarningUnusedFlags(const toco::ModelFlags& model_flags, + const toco::TocoFlags& toco_flags) { + if (toco_flags.inference_input_type()) { + LOG(WARNING) << "Ignored inference_input_type."; + } + if (toco_flags.output_format()) { + LOG(WARNING) << "Ignored output_format."; + } + if (toco_flags.default_ranges_min() || toco_flags.default_ranges_max()) { + LOG(WARNING) << "Ignored default_ranges_stats."; + } + if (toco_flags.drop_control_dependency()) { + LOG(WARNING) << "Ignored drop_control_dependency."; + } + if (toco_flags.reorder_across_fake_quant()) { + LOG(WARNING) << "Ignored reorder_across_fake_quant."; + } + if (model_flags.change_concat_input_ranges()) { + LOG(WARNING) << "Ignored change_concat_input_ranges."; + } + if (toco_flags.dump_graphviz_dir().empty()) { + LOG(WARNING) << "Ignored dump_graphviz_dir."; + } + if (toco_flags.dump_graphviz_include_video()) { + LOG(WARNING) << "Ignored dump_graphviz_video."; + } + if (model_flags.allow_nonexistent_arrays()) { + LOG(WARNING) << "Allow allow_nonexistent_arrays."; + } +} + +Status ConvertGraphDefToTFLiteFlatBuffer(const toco::ModelFlags& model_flags, + const toco::TocoFlags& toco_flags, + const GraphDebugInfo& debug_info, + const GraphDef& input, + string* result) { + mlir::MLIRContext context; + GraphImportConfig specs; + mlir::TFL::QuantizationSpecs quant_specs; + + // Parse input arrays. + std::vector<string> node_names; + std::vector<string> node_dtypes; + std::vector<std::vector<int>> node_shapes; + std::vector<double> node_mins; + std::vector<double> node_maxs; + tensorflow::DataType inference_type = + ConvertIODataTypeToDataType(toco_flags.inference_type()); + for (auto& flag : model_flags.input_arrays()) { + node_names.push_back(flag.name()); + node_dtypes.push_back( + DataType_Name(ConvertIODataTypeToDataType(flag.data_type()))); + node_shapes.push_back(std::vector<int>(flag.shape().dims().begin(), + flag.shape().dims().end())); + + const double mean_value = flag.mean_value(); + const double std_value = flag.std_value(); + const double qmin = 0.0, qmax = 255.0; + node_mins.push_back((qmin - mean_value) / std_value); + node_maxs.push_back((qmax - mean_value) / std_value); + } + TF_RETURN_IF_ERROR(tensorflow::ParseInputArrayInfo( + node_names, node_dtypes, node_shapes, &specs.inputs)); + if (mlir::TFL::GetInputNodeQuantSpecs(node_names, node_mins, node_maxs, + inference_type, &quant_specs)) { + return errors::InvalidArgument("Failed to get input quant spec."); + } + + // Some extra flag related to post training quantization. + if (toco_flags.post_training_quantize()) { + quant_specs.weight_quantization = true; + if (toco_flags.quantize_to_float16()) { + quant_specs.inference_type = tensorflow::DT_HALF; + } else { + quant_specs.inference_type = tensorflow::DT_QINT8; + } + } + + // Parse output arrays. + std::vector<string> output_arrays(model_flags.output_arrays().begin(), + model_flags.output_arrays().end()); + TF_RETURN_IF_ERROR(tensorflow::ParseOutputArrayInfo( + output_arrays, &specs.output_arrays, &specs.output_arrays_order)); + + // Other flags. + bool emit_builtin_tflite_ops = !toco_flags.force_select_tf_ops(); + bool emit_select_tf_ops = toco_flags.enable_select_tf_ops(); + bool emit_custom_ops = toco_flags.allow_custom_ops(); + specs.prune_unused_nodes = true; + specs.convert_legacy_fed_inputs = true; + specs.graph_as_function = false; + WarningUnusedFlags(model_flags, toco_flags); + + TF_ASSIGN_OR_RETURN( + auto module, ConvertGraphdefToMlir(input, debug_info, specs, &context)); + + mlir::PassManager pm(module->getContext()); + mlir::TFL::PassConfig pass_config(quant_specs); + pass_config.emit_builtin_tflite_ops = emit_builtin_tflite_ops; + pass_config.lower_tensor_list_ops = true; + + tensorflow::AddTFToTFLConversionPasses(pass_config, &pm); + + return ConvertTFExecutorToTFLOrFlatbuffer( + module.get(), /*export_to_mlir=*/false, emit_builtin_tflite_ops, + emit_select_tf_ops, emit_custom_ops, /*emit_quant_adaptor_ops=*/false, + /*lower_tensor_list_ops=*/true, quant_specs, result, &pm); +} + +} // namespace tensorflow diff --git a/pool/shard007/C++/0091106_SivTextureAssetData.cpp b/pool/shard007/C++/0091106_SivTextureAssetData.cpp new file mode 100644 index 0000000000000000000000000000000000000000..49d568c4d66239dcf7661d7ddc51893daf99bad7 --- /dev/null +++ b/pool/shard007/C++/0091106_SivTextureAssetData.cpp @@ -0,0 +1,151 @@ +//----------------------------------------------- +// +// This file is part of the Siv3D Engine. +// +// Copyright (c) 2008-2022 Ryo Suzuki +// Copyright (c) 2016-2022 OpenSiv3D Project +// +// Licensed under the MIT License. +// +//----------------------------------------------- + +# include <Siv3D/TextureAssetData.hpp> + +namespace s3d +{ + TextureAssetData::TextureAssetData() {} + + TextureAssetData::TextureAssetData(const FilePathView _path, const TextureDesc _desc, const Array<AssetTag>& tags) + : IAsset{ tags } + , path{ _path } + , desc{ _desc } {} + + TextureAssetData::TextureAssetData(const FilePathView rgb, const FilePathView alpha, const TextureDesc _desc, const Array<AssetTag>& tags) + : IAsset{ tags } + , path{ rgb } + , secondaryPath{ alpha } + , desc{ _desc } {} + + TextureAssetData::TextureAssetData(const Color& rgb, const FilePathView alpha, TextureDesc _desc, const Array<AssetTag>& tags) + : IAsset{ tags } + , secondaryPath{ alpha } + , rgbColor{ rgb } + , desc{ _desc } {} + + TextureAssetData::TextureAssetData(const Emoji& _emoji, const TextureDesc _desc, const Array<AssetTag>& tags) + : IAsset{ tags } + , desc{ _desc } + , emoji{ _emoji }{} + + TextureAssetData::TextureAssetData(const Icon& _icon, const int32 _size, const TextureDesc _desc, const Array<AssetTag>& tags) + : IAsset{ tags } + , desc{ _desc } + , icon{ _icon } + , iconSize{ _size }{} + + bool TextureAssetData::load(const String& hint) + { + if (isUninitialized()) + { + if (onLoad(*this, hint)) + { + setState(AssetState::Loaded); + return true; + } + else + { + setState(AssetState::Failed); + return false; + } + } + + if (isAsyncLoading()) + { + wait(); + } + + return isLoaded(); + } + + void TextureAssetData::loadAsync(const String& hint) + { + if (isUninitialized()) + { + setState(AssetState::AsyncLoading); + + m_task = Async([this, hint = hint]() + { + setState(onLoad(*this, hint) ? AssetState::Loaded : AssetState::Failed); + }); + } + } + + void TextureAssetData::wait() + { + if (m_task.isValid()) + { + m_task.get(); + } + } + + void TextureAssetData::release() + { + if (isUninitialized()) + { + return; + } + + if (isAsyncLoading()) + { + wait(); + } + + onRelease(*this); + + setState(AssetState::Uninitialized); + } + + bool TextureAssetData::DefaultLoad(TextureAssetData& asset, const String&) + { + if (asset.texture) + { + return true; + } + + if (asset.path) + { + if (asset.secondaryPath) + { + asset.texture = Texture{ asset.path, asset.secondaryPath, asset.desc }; + } + else + { + asset.texture = Texture{ asset.path, asset.desc }; + } + } + else if (asset.secondaryPath) + { + asset.texture = Texture{ asset.rgbColor, asset.secondaryPath }; + } + else if (asset.emoji.codePoints) + { + asset.texture = Texture{ asset.emoji, asset.desc }; + } + else if (asset.icon.code) + { + asset.texture = Texture{ asset.icon, asset.iconSize, asset.desc }; + } + + if (not asset.texture) + { + return false; + } + + return true; + } + + void TextureAssetData::DefaultRelease(TextureAssetData& asset) + { + asset.texture.release(); + } +} diff --git a/pool/shard007/C++/0091107_texture.cpp b/pool/shard007/C++/0091107_texture.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a5336e2e7fccde33afe4a457dbc523b8ce3dbe7 --- /dev/null +++ b/pool/shard007/C++/0091107_texture.cpp @@ -0,0 +1,89 @@ +/*************************************************************************** + Texture test. A cube should be visible in the middle of the screen. + The cube has a texture applied to it. + The arrow keys rotates the cube. + ***************************************************************************/ + +#include <iostream> + +#include "Private.h" +#include "Engine.h" +#include "Camera.h" +#include "Cube.h" +#include "KeyRotBehavior.h" +#include "KeyBehavior.h" +#include "Keyboard.h" +#include "TextureUtil.h" +#include "Light.h" +#include "Polygon.h" + +/** Main */ +int main(int argc, char *argv[]) { + cerr << "Simple emilia test." << endl; + + if (argc < 2) { + cerr << "Usage: texture <image-file>" << endl; + return 0; + } + + // Create the engine. + Engine* engine = new Engine(argc, argv); + engine->setLightning(0.5f, 0.1f); + + // Add a camera. Move a bit. + Camera* camera = new Camera(); + Group* groupCamera = new Group(); + engine->add(groupCamera); + groupCamera->setCamera(camera); + groupCamera->setTranslation(0, 0, 3); + engine->setEngineCamera(groupCamera); + + // Load a texture + EmTexture* texture = TextureUtil::getInstance()->loadTexture(argv[1]); + if (texture == NULL) { + cerr << "Error loading texture" << endl; + return -1; + } + + // Add a cube. + Cube* cube1 = new Cube(1.0, texture); + Cube* cube2 = new Cube(1.0, texture); + Group* groupCube1 = new Group(); + Group* groupCube2 = new Group(); + engine->add(groupCube1); + engine->add(groupCube2); + groupCube1->addShape3D(cube1); + groupCube2->addShape3D(cube2); + cube1->setPolygonProperty(EM_POLY_TRANS); + cube1->setProperty(EM_SHAPE3D_USE_TRANS); + + // Add a light + Light* lightR = new Light(1, 0, 0, 1, 0, 0); + Group* groupLightR = new Group(); + engine->add(groupLightR); + groupLightR->setLight(lightR); + groupLightR->setTranslation(5, 0, 0); + engine->addLight(lightR); + + // Add behaviors to the cubes + KeyRotBehavior* keyRBeh = new KeyRotBehavior(); + groupCube1->setBehavior(keyRBeh); + KeyBehavior* keyBeh = new KeyBehavior(); + groupCube2->setBehavior(keyBeh); + + engine->resetTick(); + while (!Keyboard::isKeyDown(SDLK_ESCAPE)) { + if (engine->nextTickFPS(50)) { + engine->tick(); + } else { + engine->render(); + engine->swap(); + } + } + engine->stopEngine(); + return 0; +} + +#if EM_USE_ALLEGRO +END_OF_MAIN(); +#endif diff --git a/pool/shard007/C++/0091108_storemodel.cpp b/pool/shard007/C++/0091108_storemodel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..213ba8c3c45384b3eb0927601eef55ddedcebeb8 --- /dev/null +++ b/pool/shard007/C++/0091108_storemodel.cpp @@ -0,0 +1,96 @@ +#include "storemodel.h" + +/** + * @brief StoreModel::StoreModel + * SubClass of QSortFilterProxyModel via http://www.qtcentre.org/threads/46471-QTreeView-Filter + */ +StoreModel::StoreModel() +{ +} + +/** + * @brief StoreModel::filterAcceptsRow + * @param sourceRow + * @param sourceParent + * @return + */ +bool StoreModel::filterAcceptsRow(int sourceRow, + const QModelIndex &sourceParent) const +{ + QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); + return ShowThis(index); +} + +/** + * @brief StoreModel::ShowThis + * @param index + * @return + */ +bool StoreModel::ShowThis(const QModelIndex index) const +{ + bool retVal = false; + //Gives you the info for number of childs with a parent + if ( sourceModel()->rowCount(index) > 0 ) + { + for( int nChild = 0; nChild < sourceModel()->rowCount(index); nChild++) + { + QModelIndex childIndex = sourceModel()->index(nChild,0,index); + if ( ! childIndex.isValid() ) + break; + retVal = ShowThis(childIndex); + if (retVal) + { + break; + } + } + } + else + { + QModelIndex useIndex = sourceModel()->index(index.row(), 0, index.parent()); + QString path = fs->filePath(useIndex); + path.replace(QRegExp("\\.gpg$"), ""); + path.replace(QRegExp("^" + store), ""); + if ( ! path.contains(filterRegExp())) + { + retVal = false; + } + else + { + retVal = true; + } + } + return retVal; +} + +/** + * @brief StoreModel::setModelAndStore + * @param sourceModel + * @param passStore + */ +void StoreModel::setModelAndStore(QFileSystemModel *sourceModel, QString passStore) { + fs = sourceModel; + store = passStore; +} + +/** + * @brief StoreModel::data + * @param index + * @param role + * @return + */ +QVariant StoreModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid()) + return QVariant(); + + QVariant initial_value; + initial_value = QSortFilterProxyModel::data(index, role); + + if (role == Qt::DisplayRole) { + QString name = initial_value.toString(); + name.replace(QRegExp("\\.gpg$"), ""); + initial_value.setValue(name); + } + + return initial_value; +} diff --git a/pool/shard007/C++/0091110_ossimPointCloudGeometry.cpp b/pool/shard007/C++/0091110_ossimPointCloudGeometry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d891133e6370c114b7c5fce21f84a4cc287b56b --- /dev/null +++ b/pool/shard007/C++/0091110_ossimPointCloudGeometry.cpp @@ -0,0 +1,78 @@ +//************************************************************************************************** +// +// OSSIM (http://trac.osgeo.org/ossim/) +// +// License: LGPL -- See LICENSE.txt file in the top level directory for more details. +// +//************************************************************************************************** +// $Id$ + +#include <ossim/point_cloud/ossimPointCloudGeometry.h> +#include <ossim/base/ossimEcefPoint.h> +#include <ossim/base/ossimUnitConversionTool.h> +#include <ossim/projection/ossimWktProjectionFactory.h> +#include <ossim/projection/ossimMapProjection.h> + +RTTI_DEF1(ossimPointCloudGeometry, "ossimPointCloudGeometry" , ossimObject); + +ossimPointCloudGeometry::ossimPointCloudGeometry(const ossimString& wkt) + : m_format(GEOGRAPHIC), + m_projection(0), + m_datum(ossimDatumFactory::instance()->wgs84()) +{ + // Establish projection from WKT: + m_projection = dynamic_cast<ossimMapProjection*>( + ossimWktProjectionFactory::instance()->createProjection(wkt)); + + if (m_projection.valid()) + { + m_datum = m_projection->getDatum(); + if (!m_projection->isGeographic()) + m_format = MAP_PROJECTED; + } +} + +bool ossimPointCloudGeometry::operator==(const ossimPointCloudGeometry& other) const +{ + if (m_format != other.m_format) + return false; + + if (m_projection.valid() && other.m_projection.valid() && (*m_projection == *(other.m_projection))) + return true; + + return false; +} + +void ossimPointCloudGeometry::convertPos(const ossimDpt3d& oldPt, ossimGpt& converted_gpos) const +{ + converted_gpos.makeNan(); + + // If the data buffer has existing points, transform them into the new projection and datum: + if (m_format == GEOGRAPHIC) + { + ossimGpt gpt (oldPt.y, oldPt.x, oldPt.z, m_datum); + gpt.changeDatum(converted_gpos.datum()); + converted_gpos = gpt; + } + else if ((m_format == MAP_PROJECTED) && m_projection.valid()) + { + ossimUnitConversionTool uct (1.0, m_projection->getProjectionUnits()); + double coord_scale = uct.getMeters(); + + //Need to convert map E, N to lat, lon + ossimDpt oldMapPt(oldPt.x*coord_scale, oldPt.y*coord_scale); + ossimGpt gpt(getProjection()->inverse(oldMapPt)); + gpt.changeDatum(m_datum); + gpt.hgt = oldPt.z*coord_scale; + gpt.changeDatum(converted_gpos.datum()); + converted_gpos = gpt; + } + else if (m_format == ECF_METERS) + { + ossimEcefPoint oldEcfPt(oldPt); + converted_gpos = ossimGpt (oldEcfPt, converted_gpos.datum()); + } + + return; +} + diff --git a/pool/shard007/C++/0091112_splicecopyhandler.cc b/pool/shard007/C++/0091112_splicecopyhandler.cc new file mode 100644 index 0000000000000000000000000000000000000000..6dcfbd2ab60e1f76c9ab746a09d45f46c802be4b --- /dev/null +++ b/pool/shard007/C++/0091112_splicecopyhandler.cc @@ -0,0 +1,82 @@ +#include "splicecopyhandler.hh" + +SpliceCopyHandler::SpliceCopyHandler() + : d_inputReadable(false), + d_outputWritable(false), + d_taskRunning(false) +{ +} + +SpliceCopyHandler::~SpliceCopyHandler() +{ +} + +void SpliceCopyHandler::onInputClosed() +{ +} + +void SpliceCopyHandler::onInputReadable() +{ + tryCopy(); +} + +void SpliceCopyHandler::connectSource(std::weak_ptr<Source> const &source) +{ + d_source = source; +} + +void SpliceCopyHandler::onOutputClosed() +{ +} + +void SpliceCopyHandler::onOutputWritable() +{ + tryCopy(); +} + +void SpliceCopyHandler::connectSink(std::weak_ptr<Sink> const &sink) +{ + d_sink = sink; +} + +/// TODO: The input and output handlers need to also be notified when +/// a sink or source stops being readable or writable!!!!!!!!!! +/// Maybe add third (unknown) state to d_readable/d_writable, so we can know if anything changed in the mean time? +void SpliceCopyHandler::onTaskCompleted(Task &task, TaskState state) +{ + if (!d_taskRunning) { + return; + } + + d_taskRunning = false; + + if (d_inputReadable && d_outputWritable) { + tryCopy(); + } +} + +void SpliceCopyHandler::tryCopy() +{ + auto source = d_source.lock(); + auto sink = d_sink.lock(); + + if (!source || !sink) { + return; + } + + if (!source->beginRead()) { + return; + } + + if (!sink->beginRead()) { + source->endRead(); + } + +} + +void SpliceCopyHandler::copy() +{ + d_inputReadable = false; + d_outputWritable = false; + +} diff --git a/pool/shard007/C++/0091114_concurrent_monitor.cpp b/pool/shard007/C++/0091114_concurrent_monitor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d9c85669cb3418054bfdde6735a4eb572667446d --- /dev/null +++ b/pool/shard007/C++/0091114_concurrent_monitor.cpp @@ -0,0 +1,132 @@ +/* + Copyright (c) 2005-2019 Intel Corporation + + 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 "concurrent_monitor.h" + +namespace tbb { +namespace internal { + +void concurrent_monitor::thread_context::init() { + new (sema.begin()) binary_semaphore; + ready = true; +} + +concurrent_monitor::~concurrent_monitor() { + abort_all(); + __TBB_ASSERT( waitset_ec.empty(), "waitset not empty?" ); +} + +void concurrent_monitor::prepare_wait( thread_context& thr, uintptr_t ctx ) { + if( !thr.ready ) + thr.init(); + // this is good place to pump previous skipped wakeup + else if( thr.skipped_wakeup ) { + thr.skipped_wakeup = false; + thr.semaphore().P(); + } + thr.context = ctx; + thr.in_waitset = true; + { + tbb::spin_mutex::scoped_lock l( mutex_ec ); + __TBB_store_relaxed( thr.epoch, __TBB_load_relaxed(epoch) ); + waitset_ec.add( (waitset_t::node_t*)&thr ); + } + atomic_fence(); +} + +void concurrent_monitor::cancel_wait( thread_context& thr ) { + // possible skipped wakeup will be pumped in the following prepare_wait() + thr.skipped_wakeup = true; + // try to remove node from waitset + bool th_in_waitset = thr.in_waitset; + if( th_in_waitset ) { + tbb::spin_mutex::scoped_lock l( mutex_ec ); + if (thr.in_waitset) { + waitset_ec.remove( (waitset_t::node_t&)thr ); + // node is removed from waitset, so there will be no wakeup + thr.in_waitset = false; + thr.skipped_wakeup = false; + } + } +} + +void concurrent_monitor::notify_one_relaxed() { + if( waitset_ec.empty() ) + return; + waitset_node_t* n; + const waitset_node_t* end = waitset_ec.end(); + { + tbb::spin_mutex::scoped_lock l( mutex_ec ); + __TBB_store_relaxed( epoch, __TBB_load_relaxed(epoch) + 1 ); + n = waitset_ec.front(); + if( n!=end ) { + waitset_ec.remove( *n ); + to_thread_context(n)->in_waitset = false; + } + } + if( n!=end ) + to_thread_context(n)->semaphore().V(); +} + +void concurrent_monitor::notify_all_relaxed() { + if( waitset_ec.empty() ) + return; + waitset_t temp; + const waitset_node_t* end; + { + tbb::spin_mutex::scoped_lock l( mutex_ec ); + __TBB_store_relaxed( epoch, __TBB_load_relaxed(epoch) + 1 ); + waitset_ec.flush_to( temp ); + end = temp.end(); + for( waitset_node_t* n=temp.front(); n!=end; n=n->next ) + to_thread_context(n)->in_waitset = false; + } + waitset_node_t* nxt; + for( waitset_node_t* n=temp.front(); n!=end; n=nxt ) { + nxt = n->next; + to_thread_context(n)->semaphore().V(); + } +#if TBB_USE_ASSERT + temp.clear(); +#endif +} + +void concurrent_monitor::abort_all_relaxed() { + if( waitset_ec.empty() ) + return; + waitset_t temp; + const waitset_node_t* end; + { + tbb::spin_mutex::scoped_lock l( mutex_ec ); + __TBB_store_relaxed( epoch, __TBB_load_relaxed(epoch) + 1 ); + waitset_ec.flush_to( temp ); + end = temp.end(); + for( waitset_node_t* n=temp.front(); n!=end; n=n->next ) + to_thread_context(n)->in_waitset = false; + } + waitset_node_t* nxt; + for( waitset_node_t* n=temp.front(); n!=end; n=nxt ) { + nxt = n->next; + to_thread_context(n)->aborted = true; + to_thread_context(n)->semaphore().V(); + } +#if TBB_USE_ASSERT + temp.clear(); +#endif +} + +} // namespace internal +} // namespace tbb diff --git a/pool/shard007/C++/0091121_drawing.cpp b/pool/shard007/C++/0091121_drawing.cpp new file mode 100644 index 0000000000000000000000000000000000000000..518e2d7e1c4d536f319d803a527ae32a9826c511 --- /dev/null +++ b/pool/shard007/C++/0091121_drawing.cpp @@ -0,0 +1,100 @@ +/* $Id$ */ +/* + Copyright (C) 2010 - 2013 by Mark de Wever <koraq@xs4all.nl> + Part of the Battle for Wesnoth Project http://www.wesnoth.org/ + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY. + + See the COPYING file for more details. +*/ + +#define GETTEXT_DOMAIN "wesnoth-lib" + +#include "gui/auxiliary/window_builder/drawing.hpp" + +#include "config.hpp" +#include "gui/auxiliary/log.hpp" +#include "gui/widgets/drawing.hpp" + +namespace gui2 { + +namespace implementation { + +tbuilder_drawing::tbuilder_drawing(const config& cfg) + : tbuilder_control(cfg) + , width(cfg["width"]) + , height(cfg["height"]) + , draw(cfg.child("draw")) +{ + assert(!draw.empty()); +} + +twidget* tbuilder_drawing::build() const +{ + tdrawing* widget = new tdrawing(); + + init_control(widget); + + const game_logic::map_formula_callable& size = + get_screen_size_variables(); + + const unsigned w = width(size); + const unsigned h = height(size); + + if(w || h) { + widget->set_best_size(tpoint(w, h)); + } + + widget->canvas().front().set_cfg(draw); + + DBG_GUI_G << "Window builder: placed drawing '" + << id << "' with definition '" + << definition << "'.\n"; + + return widget; +} + +} // namespace implementation + +} // namespace gui2 + +/*WIKI_MACRO + * @begin{macro}{drawing_description} + * + * A drawing is widget with a fixed size and gives access to the + * canvas of the widget in the window instance. This allows special + * display only widgets. + * @end{macro} + */ + + +/*WIKI + * @page = GUIWidgetInstanceWML + * @order = 2_drawing + * + * == Spacer == + * @begin{parent}{name="gui/window/resolution/grid/row/column/"} + * @begin{tag}{name="drawing"}{min=0}{max=-1}{super="generic/widget_instance"} + * @macro = drawing_description + * + * If either the width or the height is not zero the drawing functions as a + * fixed size drawing. + * + * @begin{table}{config} + * width & f_unsigned & 0 & The width of the drawing. $ + * height & f_unsigned & 0 & The height of the drawing. $ + * draw & config & & The config containing the drawing. $ + * @end{table} + * @allow{link}{name="generic/state/draw"} + * @end{tag}{name="drawing"} + * @end{parent}{name="gui/window/resolution/grid/row/column/"} + * The variable available are the same as for the window resolution see + * http://www.wesnoth.org/wiki/GUIToolkitWML#Resolution_2 for the list of + * items. + */ + diff --git a/pool/shard007/C++/0091124_GPUChromaKeyFilter.cpp b/pool/shard007/C++/0091124_GPUChromaKeyFilter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a37d9665d243b06f89bb4348748908cf85de1d5b --- /dev/null +++ b/pool/shard007/C++/0091124_GPUChromaKeyFilter.cpp @@ -0,0 +1,135 @@ +// +// libavg - Media Playback Engine. +// Copyright (C) 2003-2011 Ulrich von Zadow +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// Current versions can be found at www.libavg.de +// + +#include "GPUChromaKeyFilter.h" +#include "Bitmap.h" +#include "ShaderRegistry.h" +#include "OGLShader.h" +#include "ImagingProjection.h" + +#include "../base/ObjectCounter.h" +#include "../base/Exception.h" + +#include <iostream> + +#define SHADERID_CHROMAKEY "chromakey" +#define SHADERID_EROSION "chromakey_erosion" + +using namespace std; + +namespace avg { + +GPUChromaKeyFilter::GPUChromaKeyFilter(const IntPoint& size, bool bStandalone) + : GPUFilter(SHADERID_CHROMAKEY, true, bStandalone, 2), + m_Color(0, 255, 0), + m_HTolerance(0.0), + m_STolerance(0.0), + m_LTolerance(0.0), + m_Softness(0.0), + m_Erosion(0), + m_SpillThreshold(0.0) +{ + ObjectCounter::get()->incRef(&typeid(*this)); + + setDimensions(size); + OGLShaderPtr pShader = getShader(); + m_pTextureParam = pShader->getParam<int>("u_Texture"); + + m_pHKeyParam = pShader->getParam<float>("u_HKey"); + m_pHToleranceParam = pShader->getParam<float>("u_HTolerance"); + m_pHSoftToleranceParam = pShader->getParam<float>("u_HSoftTolerance"); + + m_pSKeyParam = pShader->getParam<float>("u_SKey"); + m_pSToleranceParam = pShader->getParam<float>("u_STolerance"); + m_pSSoftToleranceParam = pShader->getParam<float>("u_SSoftTolerance"); + + m_pLKeyParam = pShader->getParam<float>("u_LKey"); + m_pLToleranceParam = pShader->getParam<float>("u_LTolerance"); + m_pLSoftToleranceParam = pShader->getParam<float>("u_LSoftTolerance"); + + m_pSpillThresholdParam = pShader->getParam<float>("u_SpillThreshold"); + m_pIsLastParam = pShader->getParam<int>("u_bIsLast"); + + createShader(SHADERID_EROSION); + pShader = avg::getShader(SHADERID_EROSION); + m_pErosionTextureParam= pShader->getParam<int>("u_Texture"); + m_pErosionIsLastParam = pShader->getParam<int>("u_bIsLast"); + + m_pProjection2 = ImagingProjectionPtr(new ImagingProjection(size)); +} + +GPUChromaKeyFilter::~GPUChromaKeyFilter() +{ + ObjectCounter::get()->decRef(&typeid(*this)); +} + +void GPUChromaKeyFilter::setParams(const Pixel32& color, float hTolerance, + float sTolerance, float lTolerance, float softness, int erosion, + float spillThreshold) +{ + m_Color = color; + m_HTolerance = hTolerance; + m_STolerance = sTolerance; + m_LTolerance = lTolerance; + m_Softness = softness; + m_Erosion = erosion; + m_SpillThreshold = spillThreshold; + if (m_SpillThreshold <= m_HTolerance) { + m_SpillThreshold = m_HTolerance; + } +} + +void GPUChromaKeyFilter::applyOnGPU(GLTexturePtr pSrcTex) +{ + // Set up double-buffering + int curBufferIndex = m_Erosion%2; + getFBO(curBufferIndex)->activate(); + getShader()->activate(); + m_pTextureParam->set(0); + + float h, s, l; + m_Color.toHSL(h, s, l); + m_pHKeyParam->set(h); + m_pHToleranceParam->set(m_HTolerance*360); + m_pHSoftToleranceParam->set((m_HTolerance+m_Softness)*360.0f); + m_pSKeyParam->set(s); + m_pSToleranceParam->set(m_STolerance); + m_pSSoftToleranceParam->set(m_STolerance+m_Softness); + m_pLKeyParam->set(l); + m_pLToleranceParam->set(m_LTolerance); + m_pLSoftToleranceParam->set(m_LTolerance+m_Softness); + m_pSpillThresholdParam->set(m_SpillThreshold*360); + m_pIsLastParam->set(int(m_Erosion==0)); + draw(pSrcTex); + + for (int i = 0; i < m_Erosion; ++i) { + curBufferIndex = (curBufferIndex+1)%2; + getFBO(curBufferIndex)->activate(); + OGLShaderPtr pShader = avg::getShader(SHADERID_EROSION); + pShader->activate(); + m_pErosionTextureParam->set(0); + m_pErosionIsLastParam->set(int(i==m_Erosion-1)); + getDestTex((curBufferIndex+1)%2)->activate(GL_TEXTURE0); + m_pProjection2->draw(avg::getShader(SHADERID_EROSION)); + } +} + +} diff --git a/pool/shard007/C++/0091145_constant_folding_dequantize.cpp b/pool/shard007/C++/0091145_constant_folding_dequantize.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d4cebe53e11a0d300be25c75ea7c45dfec6dbd1d --- /dev/null +++ b/pool/shard007/C++/0091145_constant_folding_dequantize.cpp @@ -0,0 +1,99 @@ +//***************************************************************************** +// Copyright 2017-2020 Intel Corporation +// +// 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 "constant_folding.hpp" +#include "ngraph/op/dequantize.hpp" +#include "ngraph/runtime/reference/dequantize.hpp" + +using namespace std; +using namespace ngraph; + +template <class QUANT, class REAL> +Output<Node> fold_constant_dequantize(shared_ptr<op::v0::Constant> constant, + shared_ptr<op::v0::Dequantize> dequant, + shared_ptr<op::v0::Constant> scale, + shared_ptr<op::v0::Constant> offset) +{ + const Shape& out_shape = constant->get_output_shape(0); + runtime::AlignedBuffer buffer(shape_size(out_shape) * sizeof(REAL)); + REAL* data_ptr = buffer.get_ptr<REAL>(); + + runtime::reference::dequantize<QUANT, REAL>(constant->get_vector<QUANT>().data(), + scale->get_vector<REAL>().data(), + offset->get_vector<QUANT>().data(), + data_ptr, + constant->get_output_shape(0), + scale->get_output_shape(0), + dequant->get_axes()); + + return make_shared<op::v0::Constant>(dequant->get_output_element_type(0), out_shape, data_ptr) + ->output(0); +} + +void pass::ConstantFolding::construct_constant_dequantize() +{ + auto constant_label = make_shared<pattern::op::Label>( + element::u8, Shape{2}, pattern::has_class<op::v0::Constant>()); + auto dq_scale = op::v0::Constant::create(element::f32, Shape{}, {1}); + auto dq_offset = op::v0::Constant::create(element::u8, Shape{}, {1}); + auto dequant_op = make_shared<op::v0::Dequantize>( + constant_label, dq_scale, dq_offset, element::f32, AxisSet{}); + auto dequant = make_shared<pattern::op::Label>(dequant_op, nullptr, OutputVector{dequant_op}); + + auto constant_dequantize_callback = [constant_label, dequant](pattern::Matcher& m) { + NGRAPH_DEBUG << "In callback for constant_dequantize_callback against node = " + << m.get_match_root()->get_name(); + + auto pattern_map = m.get_pattern_map(); + + auto constant_match = as_type_ptr<op::v0::Constant>(pattern_map[constant_label]); + auto dequant_match = pattern_map[dequant]; + auto dequantize_op = as_type_ptr<op::v0::Dequantize>(dequant_match); + + auto scale = + as_type_ptr<op::v0::Constant>(dequant_match->input_value(1).get_node_shared_ptr()); + auto offset = + as_type_ptr<op::v0::Constant>(dequant_match->input_value(2).get_node_shared_ptr()); + + NGRAPH_CHECK(revalidate_and_ensure_static(dequantize_op)); + auto type = constant_match->get_output_element_type(0); + + if (dequant_match->get_output_element_type(0) != element::f32) + { + return false; + } + + if (type == element::u8) + { + m.get_match_value().replace(fold_constant_dequantize<uint8_t, float>( + constant_match, dequantize_op, scale, offset)); + return true; + } + else if (type == element::i8) + { + m.get_match_value().replace(fold_constant_dequantize<int8_t, float>( + constant_match, dequantize_op, scale, offset)); + return true; + } + + return false; + }; + + auto dequantize_matcher = + make_shared<pattern::Matcher>(dequant, "ConstantFolding.ConstantDequantize"); + this->add_matcher( + dequantize_matcher, constant_dequantize_callback, PassProperty::CHANGE_DYNAMIC_STATE); +} diff --git a/pool/shard007/C++/0091151_renderer_settings_creation.cc b/pool/shard007/C++/0091151_renderer_settings_creation.cc new file mode 100644 index 0000000000000000000000000000000000000000..6a830ec9f29b9764cd425f0681dafbb18d90b457 --- /dev/null +++ b/pool/shard007/C++/0091151_renderer_settings_creation.cc @@ -0,0 +1,113 @@ +// Copyright 2017 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 "components/viz/host/renderer_settings_creation.h" + +#include <string> + +#include "base/command_line.h" +#include "base/feature_list.h" +#include "base/logging.h" +#include "base/strings/string_number_conversions.h" +#include "build/build_config.h" +#include "build/chromeos_buildflags.h" +#include "components/viz/common/display/overlay_strategy.h" +#include "components/viz/common/display/renderer_settings.h" +#include "components/viz/common/features.h" +#include "components/viz/common/switches.h" +#include "ui/base/ui_base_switches.h" + +#if defined(USE_OZONE) +#include "ui/ozone/public/ozone_platform.h" +#endif + +namespace viz { + +namespace { + +bool GetSwitchValueAsInt(const base::CommandLine* command_line, + const std::string& switch_string, + int min_value, + int max_value, + int* result) { + std::string string_value = command_line->GetSwitchValueASCII(switch_string); + int int_value; + if (base::StringToInt(string_value, &int_value) && int_value >= min_value && + int_value <= max_value) { + *result = int_value; + return true; + } else { + LOG(WARNING) << "Failed to parse switch " << switch_string << ": " + << string_value; + return false; + } +} + +} // namespace + +RendererSettings CreateRendererSettings() { + RendererSettings renderer_settings; + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + renderer_settings.partial_swap_enabled = + !command_line->HasSwitch(switches::kUIDisablePartialSwap); + +#if BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_LINUX) + // Simple frame rate throttling only works on macOS and Linux + renderer_settings.apply_simple_frame_rate_throttling = + features::IsSimpleFrameRateThrottlingEnabled(); +#endif + +#if BUILDFLAG(IS_APPLE) + renderer_settings.release_overlay_resources_after_gpu_query = true; + renderer_settings.auto_resize_output_surface = false; +#elif BUILDFLAG(IS_CHROMEOS_ASH) + renderer_settings.auto_resize_output_surface = false; +#endif + renderer_settings.allow_antialiasing = + !command_line->HasSwitch(switches::kDisableCompositedAntialiasing); + renderer_settings.use_skia_renderer = features::IsUsingSkiaRenderer(); + + if (command_line->HasSwitch(switches::kSlowDownCompositingScaleFactor)) { + const int kMinSlowDownScaleFactor = 1; + const int kMaxSlowDownScaleFactor = 1000; + GetSwitchValueAsInt(command_line, switches::kSlowDownCompositingScaleFactor, + kMinSlowDownScaleFactor, kMaxSlowDownScaleFactor, + &renderer_settings.slow_down_compositing_scale_factor); + } + +#if defined(USE_OZONE) + if (command_line->HasSwitch(switches::kEnableHardwareOverlays)) { + renderer_settings.overlay_strategies = ParseOverlayStrategies( + command_line->GetSwitchValueASCII(switches::kEnableHardwareOverlays)); + } else { + auto& host_properties = + ui::OzonePlatform::GetInstance()->GetPlatformRuntimeProperties(); + if (host_properties.supports_overlays) { + renderer_settings.overlay_strategies = {OverlayStrategy::kFullscreen, + OverlayStrategy::kSingleOnTop, + OverlayStrategy::kUnderlay}; + } + } +#endif + + return renderer_settings; +} + +DebugRendererSettings CreateDefaultDebugRendererSettings() { + DebugRendererSettings result; + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + result.tint_composited_content = + command_line->HasSwitch(switches::kTintCompositedContent); + result.tint_composited_content_modulate = + command_line->HasSwitch(switches::kTintCompositedContentModulate); + result.show_overdraw_feedback = + command_line->HasSwitch(switches::kShowOverdrawFeedback); + result.show_dc_layer_debug_borders = + command_line->HasSwitch(switches::kShowDCLayerDebugBorders); + result.show_aggregated_damage = + command_line->HasSwitch(switches::kShowAggregatedDamage); + return result; +} + +} // namespace viz diff --git a/pool/shard007/C++/0091155_swap.cc b/pool/shard007/C++/0091155_swap.cc new file mode 100644 index 0000000000000000000000000000000000000000..4b1fb8cf46d44093c6a6568578d8e23994f2cc60 --- /dev/null +++ b/pool/shard007/C++/0091155_swap.cc @@ -0,0 +1,49 @@ +// { dg-do run { target c++11 } } + +// Copyright (C) 2005-2017 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// <http://www.gnu.org/licenses/>. + +// 20.6.6.2 Template class shared_ptr [util.smartptr.shared] + +#include <memory> +#include <testsuite_hooks.h> + +struct A { }; + +// 20.6.6.2.9 shared_ptr specialized algorithms [util.smartptr.shared.spec] + +// std::swap +int +test01() +{ + A * const a1 = new A; + A * const a2 = new A; + std::shared_ptr<A> p1(a1); + std::shared_ptr<A> p2(a2); + std::swap(p1, p2); + VERIFY( p1.get() == a2 ); + VERIFY( p2.get() == a1 ); + + return 0; +} + +int +main() +{ + test01(); + return 0; +} diff --git a/pool/shard007/C++/0091156_file.cpp b/pool/shard007/C++/0091156_file.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0b15360736819d68e7427b9d837abbaadf9b718e --- /dev/null +++ b/pool/shard007/C++/0091156_file.cpp @@ -0,0 +1,123 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Digia Plc and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QFile> +#include <QTextStream> + +static void process_line(const QByteArray &) +{ +} + +static void process_line(const QString &) +{ +} + +static void noStream_snippet() +{ +//! [0] + QFile file("in.txt"); + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) + return; + + while (!file.atEnd()) { + QByteArray line = file.readLine(); + process_line(line); + } +//! [0] +} + +static void readTextStream_snippet() +{ +//! [1] + QFile file("in.txt"); + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) + return; + + QTextStream in(&file); + while (!in.atEnd()) { + QString line = in.readLine(); + process_line(line); + } +//! [1] +} + +static void writeTextStream_snippet() +{ +//! [2] + QFile file("out.txt"); + if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) + return; + + QTextStream out(&file); + out << "The magic number is: " << 49 << "\n"; +//! [2] +} + +static void writeTextStream_snippet() +{ + QFile file("out.dat"); + if (!file.open(QIODevice::WriteOnly)) + return; + + QDataStream out(&file); + out << "The magic number is: " << 49 << "\n"; +} + +static void readRegularEmptyFile_snippet() +{ +//! [3] + QFile file("/proc/modules"); + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) + return; + + QTextStream in(&file); + QString line = in.readLine(); + while (!line.isNull()) { + process_line(line); + line = in.readLine(); + } +//! [3] +} + +int main() +{ + lineByLine_snippet(); + writeStream_snippet(); +} diff --git a/pool/shard007/C++/0091159_5380320_AC_0MS_132K.cpp b/pool/shard007/C++/0091159_5380320_AC_0MS_132K.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d6f34d3a676a1d9b58b566e0e14a2c44dee03828 --- /dev/null +++ b/pool/shard007/C++/0091159_5380320_AC_0MS_132K.cpp @@ -0,0 +1,31 @@ +#include<cstdio> +#include<algorithm> +using namespace std; + +const int LIMIT=30,INF=-1; + +int memory[LIMIT]; + +int SchemeNum(const int length){ + if(length==0) + return 1; + if(length%2!=0) + return 0; + if(memory[length-1]!=INF) + return memory[length-1]; + memory[length-1]=3*SchemeNum(length-2); + for(int j=length-4;j>=0;j-=2) + memory[length-1]+=SchemeNum(j)*2; + return memory[length-1]; +} + +int main(){ + fill(memory,memory+LIMIT,INF); + while(true){ + int length; + scanf("%d",&length); + if(length==-1) + return 0; + printf("%d\n",SchemeNum(length)); + } +} \ No newline at end of file diff --git a/pool/shard007/C++/0091161_extension_custom_bindings.cc b/pool/shard007/C++/0091161_extension_custom_bindings.cc new file mode 100644 index 0000000000000000000000000000000000000000..047588caeddeaf96605858f78a59b319098a1317 --- /dev/null +++ b/pool/shard007/C++/0091161_extension_custom_bindings.cc @@ -0,0 +1,126 @@ +// Copyright (c) 2012 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 "chrome/renderer/extensions/extension_custom_bindings.h" + +#include <string> + +#include "base/string_util.h" +#include "chrome/common/chrome_view_type.h" +#include "chrome/common/extensions/extension_action.h" +#include "chrome/common/extensions/extension_messages.h" +#include "chrome/common/url_constants.h" +#include "chrome/renderer/extensions/extension_dispatcher.h" +#include "chrome/renderer/extensions/extension_helper.h" +#include "content/public/renderer/render_view.h" +#include "grit/renderer_resources.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "webkit/glue/webkit_glue.h" +#include "v8/include/v8.h" + +namespace extensions { + +namespace { + +} // namespace + +ExtensionCustomBindings::ExtensionCustomBindings( + ExtensionDispatcher* extension_dispatcher) + : ChromeV8Extension(extension_dispatcher) { + RouteStaticFunction("GetExtensionViews", &GetExtensionViews); + RouteStaticFunction("OpenChannelToExtension", &OpenChannelToExtension); +} + +// static +v8::Handle<v8::Value> ExtensionCustomBindings::GetExtensionViews( + const v8::Arguments& args) { + if (args.Length() != 2) + return v8::Undefined(); + + if (!args[0]->IsInt32() || !args[1]->IsString()) + return v8::Undefined(); + + // |browser_window_id| == extension_misc::kUnknownWindowId means getting + // views attached to any browser window. + int browser_window_id = args[0]->Int32Value(); + + std::string view_type_string = *v8::String::Utf8Value(args[1]->ToString()); + StringToUpperASCII(&view_type_string); + // |view_type| == content::VIEW_TYPE_INVALID means getting any type of + // views. + content::ViewType view_type = content::VIEW_TYPE_INVALID; + if (view_type_string == chrome::kViewTypeBackgroundPage) { + view_type = chrome::VIEW_TYPE_EXTENSION_BACKGROUND_PAGE; + } else if (view_type_string == chrome::kViewTypeInfobar) { + view_type = chrome::VIEW_TYPE_EXTENSION_INFOBAR; + } else if (view_type_string == chrome::kViewTypeNotification) { + view_type = chrome::VIEW_TYPE_NOTIFICATION; + } else if (view_type_string == chrome::kViewTypeTabContents) { + view_type = content::VIEW_TYPE_WEB_CONTENTS; + } else if (view_type_string == chrome::kViewTypePopup) { + view_type = chrome::VIEW_TYPE_EXTENSION_POPUP; + } else if (view_type_string == chrome::kViewTypeExtensionDialog) { + view_type = chrome::VIEW_TYPE_EXTENSION_DIALOG; + } else if (view_type_string == chrome::kViewTypeAppShell) { + view_type = chrome::VIEW_TYPE_APP_SHELL; + } else if (view_type_string == chrome::kViewTypePanel) { + view_type = chrome::VIEW_TYPE_PANEL; + } else if (view_type_string != chrome::kViewTypeAll) { + return v8::Undefined(); + } + + ExtensionCustomBindings* v8_extension = + GetFromArguments<ExtensionCustomBindings>(args); + const ::Extension* extension = + v8_extension->GetExtensionForCurrentRenderView(); + if (!extension) + return v8::Undefined(); + + std::vector<content::RenderView*> views = ExtensionHelper::GetExtensionViews( + extension->id(), browser_window_id, view_type); + v8::Local<v8::Array> v8_views = v8::Array::New(); + int v8_index = 0; + for (size_t i = 0; i < views.size(); ++i) { + v8::Local<v8::Context> context = + views[i]->GetWebView()->mainFrame()->mainWorldScriptContext(); + if (!context.IsEmpty()) { + v8::Local<v8::Value> window = context->Global(); + DCHECK(!window.IsEmpty()); + v8_views->Set(v8::Integer::New(v8_index++), window); + } + } + + return v8_views; +} + +// static +v8::Handle<v8::Value> ExtensionCustomBindings::OpenChannelToExtension( + const v8::Arguments& args) { + // Get the current RenderView so that we can send a routed IPC message from + // the correct source. + content::RenderView* renderview = GetCurrentRenderView(); + if (!renderview) + return v8::Undefined(); + + // The Javascript code should validate/fill the arguments. + CHECK(args.Length() >= 3 && + args[0]->IsString() && + args[1]->IsString() && + args[2]->IsString()); + + std::string source_id = *v8::String::Utf8Value(args[0]->ToString()); + std::string target_id = *v8::String::Utf8Value(args[1]->ToString()); + std::string channel_name = *v8::String::Utf8Value(args[2]->ToString()); + int port_id = -1; + renderview->Send(new ExtensionHostMsg_OpenChannelToExtension( + renderview->GetRoutingID(), + source_id, + target_id, + channel_name, + &port_id)); + return v8::Integer::New(port_id); +} + +} // namespace extensions diff --git a/pool/shard007/C++/0091173_GosmoreRoutingRunner.cpp b/pool/shard007/C++/0091173_GosmoreRoutingRunner.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7366eedd4c5b4a638290426993ccab57558a013b --- /dev/null +++ b/pool/shard007/C++/0091173_GosmoreRoutingRunner.cpp @@ -0,0 +1,247 @@ +// +// This file is part of the Marble Virtual Globe. +// +// This program is free software licensed under the GNU LGPL. You can +// find a copy of this license in LICENSE.txt in the top directory of +// the source code. +// +// Copyright 2010 Dennis Nienhüser <nienhueser@kde.org> +// Copyright 2012 Bernhard Beschow <bbeschow@cs.tu-berlin.de> +// + +#include "GosmoreRoutingRunner.h" + +#include "MarbleDebug.h" +#include "MarbleDirs.h" +#include "routing/RouteRequest.h" +#include "routing/instructions/WaypointParser.h" +#include "routing/instructions/InstructionTransformation.h" +#include "GeoDataDocument.h" +#include "GeoDataExtendedData.h" +#include "GeoDataPlacemark.h" + +#include <QProcess> +#include <QMap> + +namespace Marble +{ + +class GosmoreRunnerPrivate +{ +public: + QFileInfo m_gosmoreMapFile; + + WaypointParser m_parser; + + /** Static to share the cache among all instances */ + static QMap<QString, QByteArray> m_partialRoutes; + + QByteArray retrieveWaypoints( const QString &query ) const; + + static GeoDataDocument* createDocument( GeoDataLineString* routeWaypoints, const QVector<GeoDataPlacemark*> instructions ); + + static GeoDataLineString parseGosmoreOutput( const QByteArray &content ); + + static void merge( GeoDataLineString* one, const GeoDataLineString& two ); + + QVector<GeoDataPlacemark*> parseGosmoreInstructions( const QByteArray &content ); + + GosmoreRunnerPrivate(); +}; + +GosmoreRunnerPrivate::GosmoreRunnerPrivate() +{ + m_parser.setLineSeparator("\r"); + m_parser.setFieldSeparator(','); + m_parser.setFieldIndex( WaypointParser::RoadName, 4 ); + m_parser.addJunctionTypeMapping( "Jr", RoutingWaypoint::Roundabout ); +} + +QMap<QString, QByteArray> GosmoreRunnerPrivate::m_partialRoutes; + +void GosmoreRunnerPrivate::merge( GeoDataLineString* one, const GeoDataLineString& two ) +{ + Q_ASSERT( one ); + + QVector<GeoDataCoordinates>::const_iterator iter = two.constBegin(); + for( ; iter != two.constEnd(); ++iter ) { + /** @todo: It might be needed to cut off some points at the start or end */ + one->append( *iter ); + } +} + +QByteArray GosmoreRunnerPrivate::retrieveWaypoints( const QString &query ) const +{ + QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + env.insert("QUERY_STRING", query); + env.insert("LC_ALL", "C"); + QProcess gosmore; + gosmore.setProcessEnvironment(env); + + gosmore.start("gosmore", QStringList() << m_gosmoreMapFile.absoluteFilePath() ); + if (!gosmore.waitForStarted(5000)) { + mDebug() << "Couldn't start gosmore from the current PATH. Install it to retrieve routing results from gosmore."; + return QByteArray(); + } + + if ( gosmore.waitForFinished(15000) ) { + return gosmore.readAllStandardOutput(); + } + else { + mDebug() << "Couldn't stop gosmore"; + } + + return QByteArray(); +} + +GeoDataLineString GosmoreRunnerPrivate::parseGosmoreOutput( const QByteArray &content ) +{ + GeoDataLineString routeWaypoints; + + QStringList lines = QString::fromLocal8Bit( content ).split( '\r' ); + foreach( const QString &line, lines ) { + QStringList fields = line.split(','); + if (fields.size() >= 5) { + qreal lon = fields.at(1).toDouble(); + qreal lat = fields.at(0).toDouble(); + GeoDataCoordinates coordinates( lon, lat, 0.0, GeoDataCoordinates::Degree ); + routeWaypoints.append( coordinates ); + } + } + + return routeWaypoints; +} + +QVector<GeoDataPlacemark*> GosmoreRunnerPrivate::parseGosmoreInstructions( const QByteArray &content ) +{ + // Determine gosmore version + QStringList lines = QString::fromUtf8( content ).split( '\r' ); + if ( lines.size() > 2 ) { + QStringList fields = lines.at( lines.size()-2 ).split(','); + m_parser.setFieldIndex( WaypointParser::RoadName, fields.size()-1 ); + if ( fields.size() < 5 || fields.size() > 6 ) { + // Can happen when gosmore changes the output format, returns garbage + // or the last street name contains a comma. We may still parse it correctly, just try. + mDebug() << "Unexpected number of fields. This gosmore version may be unsupported."; + } + } + + QVector<GeoDataPlacemark*> result; + QTextStream stream( content ); + stream.setCodec("UTF8"); + stream.setAutoDetectUnicode( true ); + + RoutingInstructions directions = InstructionTransformation::process( m_parser.parse( stream ) ); + for( int i=0; i<directions.size(); ++i ) { + GeoDataPlacemark* placemark = new GeoDataPlacemark( directions[i].instructionText() ); + GeoDataExtendedData extendedData; + GeoDataData turnType; + turnType.setName( "turnType" ); + turnType.setValue( qVariantFromValue<int>( int( directions[i].turnType() ) ) ); + extendedData.addValue( turnType ); + GeoDataData roadName; + roadName.setName( "roadName" ); + roadName.setValue( directions[i].roadName() ); + extendedData.addValue( roadName ); + placemark->setExtendedData( extendedData ); + Q_ASSERT( !directions[i].points().isEmpty() ); + GeoDataLineString* geometry = new GeoDataLineString; + QVector<RoutingWaypoint> items = directions[i].points(); + for (int j=0; j<items.size(); ++j ) { + RoutingPoint point = items[j].point(); + GeoDataCoordinates coordinates( point.lon(), point.lat(), 0.0, GeoDataCoordinates::Degree ); + geometry->append( coordinates ); + } + placemark->setGeometry( geometry ); + result.push_back( placemark ); + } + + return result; +} + +GeoDataDocument* GosmoreRunnerPrivate::createDocument( GeoDataLineString* routeWaypoints, const QVector<GeoDataPlacemark*> instructions ) +{ + if ( !routeWaypoints || routeWaypoints->isEmpty() ) { + return 0; + } + + GeoDataDocument* result = new GeoDataDocument(); + GeoDataPlacemark* routePlacemark = new GeoDataPlacemark; + routePlacemark->setName( "Route" ); + routePlacemark->setGeometry( routeWaypoints ); + result->append( routePlacemark ); + + QString name = "%1 %2 (Gosmore)"; + QString unit = QLatin1String( "m" ); + qreal length = routeWaypoints->length( EARTH_RADIUS ); + if (length >= 1000) { + length /= 1000.0; + unit = "km"; + } + result->setName( name.arg( length, 0, 'f', 1 ).arg( unit ) ); + + foreach( GeoDataPlacemark* placemark, instructions ) + { + result->append( placemark ); + } + + return result; +} + +GosmoreRunner::GosmoreRunner( QObject *parent ) : + RoutingRunner( parent ), + d( new GosmoreRunnerPrivate ) +{ + // Check installation + QDir mapDir( MarbleDirs::localPath() + "/maps/earth/gosmore/" ); + d->m_gosmoreMapFile = QFileInfo ( mapDir, "gosmore.pak" ); +} + +GosmoreRunner::~GosmoreRunner() +{ + delete d; +} + +void GosmoreRunner::retrieveRoute( const RouteRequest *route ) +{ + if ( !d->m_gosmoreMapFile.exists() ) + { + emit routeCalculated( 0 ); + return; + } + + GeoDataLineString* wayPoints = new GeoDataLineString; + QByteArray completeOutput; + + for( int i=0; i<route->size()-1; ++i ) + { + QString queryString = "flat=%1&flon=%2&tlat=%3&tlon=%4&fastest=1&v=motorcar"; + GeoDataCoordinates source = route->at(i); + double fLon = source.longitude( GeoDataCoordinates::Degree ); + double fLat = source.latitude( GeoDataCoordinates::Degree ); + queryString = queryString.arg(fLat, 0, 'f', 8).arg(fLon, 0, 'f', 8); + GeoDataCoordinates destination = route->at(i+1); + double tLon = destination.longitude( GeoDataCoordinates::Degree ); + double tLat = destination.latitude( GeoDataCoordinates::Degree ); + queryString = queryString.arg(tLat, 0, 'f', 8).arg(tLon, 0, 'f', 8); + + QByteArray output; + if ( d->m_partialRoutes.contains( queryString ) ) { + output = d->m_partialRoutes[queryString]; + } + else { + output = d->retrieveWaypoints( queryString ); + } + + GeoDataLineString points = d->parseGosmoreOutput( output ); + d->merge( wayPoints, points ); + completeOutput.append( output ); + } + + QVector<GeoDataPlacemark*> instructions = d->parseGosmoreInstructions( completeOutput ); + + GeoDataDocument* result = d->createDocument( wayPoints, instructions ); + emit routeCalculated( result ); +} + +} // namespace Marble diff --git a/pool/shard007/C++/0091176_ATONLq.cpp b/pool/shard007/C++/0091176_ATONLq.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6b05d96eb5c4580d5d4a601b1ce2b2a82c62a6c1 --- /dev/null +++ b/pool/shard007/C++/0091176_ATONLq.cpp @@ -0,0 +1,22 @@ + +#include "ControlInterfaceCommands.h" + +byte controlATONLq() +{ + for (int ix = 0; ix < LOP_MAX_OUT_NEIGHBOURS; ix++) + { + int ttl = (int)constrain(LOP_ONL_ALLOCATION_TTL - (millis() - OuterNeighboursList[ix]->last_seen), 0, LOP_ONL_ALLOCATION_TTL); + if (OuterNeighboursList[ix] != 0 && ttl > 0) + { + Serial.print(OuterNeighboursList[ix]->tx_power); + Serial.print(","); + Serial.print(OuterNeighboursList[ix]->resourceMask.slot); + Serial.print(","); + Serial.print(ttl); + Serial.print(","); + Serial.println(OuterNeighboursList[ix]->address); + } + } + + return ERROR_NONE; +} \ No newline at end of file diff --git a/pool/shard007/C++/0091193_insurgency.cpp b/pool/shard007/C++/0091193_insurgency.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7bc32b32d162c708059cc453bd92b8c5aed60518 --- /dev/null +++ b/pool/shard007/C++/0091193_insurgency.cpp @@ -0,0 +1,202 @@ +/* Copyright (C) 2009-2012, Snares <snares@users.sourceforge.net> + Copyright (C) 2005-2012, Thorvald Natvig <thorvald@natvig.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: + + - 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 Mumble Developers 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 FOUNDATION 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 "../mumble_plugin_win32.h" + +using namespace std; + +BYTE *posptr; +BYTE *rotptr; +BYTE *stateptr; +BYTE *hostptr; + +static bool calcout(float *pos, float *rot, float *opos, float *front, float *top) { + float h = rot[0]; + float v = rot[1]; + + if ((v < -360.0f) || (v > 360.0f) || (h < -360.0f) || (h > 360.0f)) + return false; + + h *= static_cast<float>(M_PI / 180.0f); + v *= static_cast<float>(M_PI / 180.0f); + + // Seems Insurgency is in inches. INCHES?!? + opos[0] = pos[0] / 39.37f; + opos[1] = pos[2] / 39.37f; + opos[2] = pos[1] / 39.37f; + + front[0] = cos(v) * cos(h); + front[1] = -sin(h); + front[2] = sin(v) * cos(h); + + h -= static_cast<float>(M_PI / 2.0f); + + top[0] = cos(v) * cos(h); + top[1] = -sin(h); + top[2] = sin(v) * cos(h); + + return true; +} + +static int fetch(float *avatar_pos, float *avatar_front, float *avatar_top, float *camera_pos, float *camera_front, float *camera_top, string &context, wstring &) { + for (int i=0;i<3;i++) + avatar_pos[i] = avatar_front[i] = avatar_top[i] = camera_pos[i] = camera_front[i] = camera_top[i] = 0.0f; + + float ipos[3], rot[3]; + bool ok; + char state; + char chHostStr[40]; + string sHost; + wostringstream new_identity; + ostringstream new_context; + + ok = peekProc(posptr, ipos, 12) && + peekProc(rotptr, rot, 12) && + peekProc(stateptr, &state, 1) && + peekProc(hostptr, chHostStr, 40); + if (!ok) + return false; + + chHostStr[39] = 0; + + sHost.assign(chHostStr); + if (sHost.find(':')==string::npos) + sHost.append(":27015"); + + new_context << "<context>" + << "<game>insurgency</game>" + << "<hostport>" << sHost << "</hostport>" + << "</context>"; + context = new_context.str(); + + /* TODO + new_identity << "<identity>" + << "<name>" << "SAS" << "</name>" + << "</identity>"; + identity = new_identity.str(); */ + + // Check to see if you are spawned + if (state == 0 || state == 1) + return true; // Deactivate plugin + + ok = calcout(ipos, rot, avatar_pos, avatar_front, avatar_top); + if (ok) { + for (int i=0;i<3;++i) { + camera_pos[i] = avatar_pos[i]; + camera_front[i] = avatar_front[i]; + camera_top[i] = avatar_top[i]; + } + return true; + } + + return false; +} + +static int trylock(const std::multimap<std::wstring, unsigned long long int> &pids) { + posptr = rotptr = NULL; + + if (! initialize(pids, L"hl2.exe", L"client.dll")) + return false; + + BYTE *mod_engine=getModuleAddr(L"engine.dll"); + if (!mod_engine) + return false; + + // Check if we really have Insurgency running + /* + position tuple: client.dll+0x47171c (x,y,z, float) + orientation tuple: client.dll+0x4f1458 (v,h float) + ID string: client.dll+0x31a80a = "CombatWeapon@@" (14 characters, text) + spawn state: client.dll+0x4aee58 (0 when at main menu, 1 when not spawned, 4 to 5 when spawned) + host string: engine.dll+0x3909c4 (ip:port zero-terminated string) + */ + + // Remember addresses for later + posptr = pModule + 0x4F1EE0; + rotptr = pModule + 0x4F247C; + stateptr = pModule + 0x4AFEB8; + hostptr = mod_engine + 0x3909A4; + + //Gamecheck + char sMagic[14]; + if (!peekProc(pModule + 0x46B512, sMagic, 14) || strncmp("CombatWeapon@@", sMagic, 14)!=0) + return false; + + // Check if we can get meaningful data from it + float apos[3], afront[3], atop[3]; + float cpos[3], cfront[3], ctop[3]; + wstring sidentity; + string scontext; + + if (fetch(apos, afront, atop, cpos, cfront, ctop, scontext, sidentity)) { + return true; + } else { + generic_unlock(); + return false; + } +} + +static const std::wstring longdesc() { + return std::wstring(L"Supports Insurgency pModule build 4044. No identity support yet."); +} + +static std::wstring description(L"Insurgency: Modern Infantry Combat (Build 4044)"); +static std::wstring shortname(L"Insurgency: Modern Infantry Combat"); + +static int trylock1() { + return trylock(std::multimap<std::wstring, unsigned long long int>()); +} + +static MumblePlugin insurgencyplug = { + MUMBLE_PLUGIN_MAGIC, + description, + shortname, + NULL, + NULL, + trylock1, + generic_unlock, + longdesc, + fetch +}; + +static MumblePlugin2 insurgencyplug2 = { + MUMBLE_PLUGIN_MAGIC_2, + MUMBLE_PLUGIN_VERSION, + trylock +}; + +extern "C" __declspec(dllexport) MumblePlugin *getMumblePlugin() { + return &insurgencyplug; +} + +extern "C" __declspec(dllexport) MumblePlugin2 *getMumblePlugin2() { + return &insurgencyplug2; +} diff --git a/pool/shard007/C++/0091194_Threads.cpp b/pool/shard007/C++/0091194_Threads.cpp new file mode 100644 index 0000000000000000000000000000000000000000..de6520b216c5f1620902a998ff0b0b1eb57da6fa --- /dev/null +++ b/pool/shard007/C++/0091194_Threads.cpp @@ -0,0 +1,121 @@ +/* +* Copyright 2008 Free Software Foundation, Inc. +* +* +* This software is distributed under the terms of the GNU Affero Public License. +* See the COPYING file in the main directory for details. +* +* This use of this software may be subject to additional restrictions. +* See the LEGAL file in the main directory for details. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +*/ + + + + + +#include "Threads.h" +#include "Timeval.h" + + +using namespace std; + + + + +Mutex gStreamLock; ///< Global lock to control access to cout and cerr. + +void lockCout() +{ + gStreamLock.lock(); + Timeval entryTime; + cout << entryTime << " " << pthread_self() << ": "; +} + + +void unlockCout() +{ + cout << dec << endl << flush; + gStreamLock.unlock(); +} + + +void lockCerr() +{ + gStreamLock.lock(); + Timeval entryTime; + cerr << entryTime << " " << pthread_self() << ": "; +} + +void unlockCerr() +{ + cerr << dec << endl << flush; + gStreamLock.unlock(); +} + + + + + + + +Mutex::Mutex() +{ + bool res; + res = pthread_mutexattr_init(&mAttribs); + assert(!res); + res = pthread_mutexattr_settype(&mAttribs,PTHREAD_MUTEX_RECURSIVE); + assert(!res); + res = pthread_mutex_init(&mMutex,&mAttribs); + assert(!res); +} + + +Mutex::~Mutex() +{ + pthread_mutex_destroy(&mMutex); + bool res = pthread_mutexattr_destroy(&mAttribs); + assert(!res); +} + + + + +/** Block for the signal up to the cancellation timeout. */ +void Signal::wait(Mutex& wMutex, unsigned timeout) const +{ + Timeval then(timeout); + struct timespec waitTime = then.timespec(); + pthread_cond_timedwait(&mSignal,&wMutex.mMutex,&waitTime); +} + + +void Thread::start(void *(*task)(void*), void *arg) +{ + assert(mThread==((pthread_t)0)); + bool res; + // (pat) Moved initialization to constructor to avoid crash in destructor. + //res = pthread_attr_init(&mAttrib); + //assert(!res); + res = pthread_attr_setstacksize(&mAttrib, mStackSize); + assert(!res); + res = pthread_create(&mThread, &mAttrib, task, arg); + assert(!res); +} + + + +// vim: ts=4 sw=4 diff --git a/pool/shard007/C++/0091199_addapplicationreferencedatasourceresponse.cpp b/pool/shard007/C++/0091199_addapplicationreferencedatasourceresponse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c61fc8dd9421e6f0110ad7c1941615a1285e517e --- /dev/null +++ b/pool/shard007/C++/0091199_addapplicationreferencedatasourceresponse.cpp @@ -0,0 +1,103 @@ +/* + Copyright 2013-2021 Paul Colby + + This file is part of QtAws. + + QtAws is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + QtAws is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with the QtAws. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "addapplicationreferencedatasourceresponse.h" +#include "addapplicationreferencedatasourceresponse_p.h" + +#include <QDebug> +#include <QNetworkReply> +#include <QXmlStreamReader> + +namespace QtAws { +namespace KinesisAnalyticsV2 { + +/*! + * \class QtAws::KinesisAnalyticsV2::AddApplicationReferenceDataSourceResponse + * \brief The AddApplicationReferenceDataSourceResponse class provides an interace for KinesisAnalyticsV2 AddApplicationReferenceDataSource responses. + * + * \inmodule QtAwsKinesisAnalyticsV2 + * + * Amazon Kinesis Data Analytics is a fully managed service that you can use to process and analyze streaming data using + * Java, SQL, or Scala. The service enables you to quickly author and run Java, SQL, or Scala code against streaming + * sources to perform time series analytics, feed real-time dashboards, and create real-time + * + * \sa KinesisAnalyticsV2Client::addApplicationReferenceDataSource + */ + +/*! + * Constructs a AddApplicationReferenceDataSourceResponse object for \a reply to \a request, with parent \a parent. + */ +AddApplicationReferenceDataSourceResponse::AddApplicationReferenceDataSourceResponse( + const AddApplicationReferenceDataSourceRequest &request, + QNetworkReply * const reply, + QObject * const parent) + : KinesisAnalyticsV2Response(new AddApplicationReferenceDataSourceResponsePrivate(this), parent) +{ + setRequest(new AddApplicationReferenceDataSourceRequest(request)); + setReply(reply); +} + +/*! + * \reimp + */ +const AddApplicationReferenceDataSourceRequest * AddApplicationReferenceDataSourceResponse::request() const +{ + Q_D(const AddApplicationReferenceDataSourceResponse); + return static_cast<const AddApplicationReferenceDataSourceRequest *>(d->request); +} + +/*! + * \reimp + * Parses a successful KinesisAnalyticsV2 AddApplicationReferenceDataSource \a response. + */ +void AddApplicationReferenceDataSourceResponse::parseSuccess(QIODevice &response) +{ + //Q_D(AddApplicationReferenceDataSourceResponse); + QXmlStreamReader xml(&response); + /// @todo +} + +/*! + * \class QtAws::KinesisAnalyticsV2::AddApplicationReferenceDataSourceResponsePrivate + * \brief The AddApplicationReferenceDataSourceResponsePrivate class provides private implementation for AddApplicationReferenceDataSourceResponse. + * \internal + * + * \inmodule QtAwsKinesisAnalyticsV2 + */ + +/*! + * Constructs a AddApplicationReferenceDataSourceResponsePrivate object with public implementation \a q. + */ +AddApplicationReferenceDataSourceResponsePrivate::AddApplicationReferenceDataSourceResponsePrivate( + AddApplicationReferenceDataSourceResponse * const q) : KinesisAnalyticsV2ResponsePrivate(q) +{ + +} + +/*! + * Parses a KinesisAnalyticsV2 AddApplicationReferenceDataSource response element from \a xml. + */ +void AddApplicationReferenceDataSourceResponsePrivate::parseAddApplicationReferenceDataSourceResponse(QXmlStreamReader &xml) +{ + Q_ASSERT(xml.name() == QLatin1String("AddApplicationReferenceDataSourceResponse")); + Q_UNUSED(xml) ///< @todo +} + +} // namespace KinesisAnalyticsV2 +} // namespace QtAws diff --git a/pool/shard007/C++/0091202_tst_qmltests.cpp b/pool/shard007/C++/0091202_tst_qmltests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..782b041ca50040c83d3b39a893f01ade9b5f5820 --- /dev/null +++ b/pool/shard007/C++/0091202_tst_qmltests.cpp @@ -0,0 +1,52 @@ +/* + Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "../bytearraytestdata.h" +#include "../util.h" + +#include "private/qquickwebview_p.h" +#include <QGuiApplication> +#include <QVarLengthArray> +#include <QtQuickTest/quicktest.h> + +int main(int argc, char** argv) +{ + QVarLengthArray<char*, 8> arguments; + for (int i = 0; i < argc; ++i) + arguments.append(argv[i]); + + arguments.append(const_cast<char*>("-import")); + arguments.append(const_cast<char*>(IMPORT_DIR)); + + argc = arguments.count(); + argv = arguments.data(); + + suppressDebugOutput(); + addQtWebProcessToPath(); + + // Instantiate QApplication to prevent quick_test_main to instantiate a QGuiApplication. + // This can be removed as soon as we do not use QtWidgets any more. + QGuiApplication app(argc, argv); + qmlRegisterType<ByteArrayTestData>("Test", 1, 0, "ByteArrayTestData"); + +#ifdef DISABLE_FLICKABLE_VIEWPORT + QQuickWebViewExperimental::setFlickableViewportEnabled(false); +#endif + return quick_test_main(argc, argv, "qmltests", 0, QUICK_TEST_SOURCE_DIR); +} diff --git a/pool/shard007/C++/0091213_pool_cache_monitor.cpp b/pool/shard007/C++/0091213_pool_cache_monitor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c5c539d65c6e8c08d3f71a7977aaf0d90e26915a --- /dev/null +++ b/pool/shard007/C++/0091213_pool_cache_monitor.cpp @@ -0,0 +1,212 @@ +#include "pool_cache_monitor.hpp" +#include <glibmm/main.h> +#include <glibmm/fileutils.h> +#include <glibmm/miscutils.h> +#include "pool/pool_cached.hpp" +#include "pool/pool_manager.hpp" +#include "util/util.hpp" +#include "pool/part.hpp" + +namespace horizon { +PoolCacheMonitor::PoolCacheMonitor(const std::string &a_pool_base_path, const std::string &a_pool_cache_path) + : pool_base_path(a_pool_base_path), pool_cache_path(a_pool_cache_path) +{ + monitor = Gio::File::create_for_path(pool_cache_path)->monitor_directory(); + monitor->signal_changed().connect(sigc::mem_fun(*this, &PoolCacheMonitor::changed)); + dispatcher.connect([this] { + std::lock_guard<std::mutex> guard(mutex); + status = status_thread; + thread.join(); + s_signal_changed.emit(); + }); +} + +const PoolCacheStatus &PoolCacheMonitor::get_status() const +{ + return status; +} + + +void PoolCacheMonitor::changed(const Glib::RefPtr<Gio::File> &file, const Glib::RefPtr<Gio::File> &file_other, + Gio::FileMonitorEvent event) +{ + update(); +} + +bool PoolCacheMonitor::really_update() +{ + if (!thread.joinable()) { + thread = std::thread(&PoolCacheMonitor::worker, this); + } + return false; +} + +static void find_files(const std::string &base_path, std::function<void(const std::string &)> cb, + const std::string &path = "") +{ + auto this_path = Glib::build_filename(base_path, path); + Glib::Dir dir(this_path); + for (const auto &it : dir) { + auto itempath = Glib::build_filename(this_path, it); + if (Glib::file_test(itempath, Glib::FILE_TEST_IS_DIR)) { + find_files(base_path, cb, Glib::build_filename(path, it)); + } + else if (Glib::file_test(itempath, Glib::FILE_TEST_IS_REGULAR)) { + cb(Glib::build_filename(path, it)); + } + } +} + +void PoolCacheMonitor::worker() +{ + { + std::lock_guard<std::mutex> guard(mutex); + status_thread.items.clear(); + status_thread.n_current = 0; + status_thread.n_total = 0; + status_thread.n_out_of_date = 0; + status_thread.n_missing = 0; + + Pool pool(pool_base_path); + PoolCached pool_cached(pool_base_path, pool_cache_path); + + + Glib::Dir dir(pool_cache_path); + try { + for (const auto &it : dir) { + if (endswith(it, ".json")) { + auto itempath = Glib::build_filename(pool_cache_path, it); + json j_cache; + { + j_cache = load_json_from_file(itempath); + if (j_cache.count("_imp")) + j_cache.erase("_imp"); + } + status_thread.items.emplace_back(); + auto &item = status_thread.items.back(); + status_thread.n_total++; + std::string type_str = j_cache.at("type"); + item.filename_cached = itempath; + if (type_str == "part") { + try { + auto part = Part::new_from_file(itempath, pool_cached); + item.name = part.get_MPN() + " / " + part.get_manufacturer(); + } + catch (...) { + item.name = "Part not found"; + } + } + else { + item.name = j_cache.at("name").get<std::string>(); + } + ObjectType type = object_type_lut.lookup(type_str); + item.type = type; + + UUID uuid(j_cache.at("uuid").get<std::string>()); + item.uuid = uuid; + + std::string pool_filename; + try { + pool_filename = pool.get_filename(type, uuid); + } + catch (const SQLite::Error &e) { + throw; + } + catch (...) { + pool_filename = ""; + } + if (pool_filename.size() && Glib::file_test(pool_filename, Glib::FILE_TEST_IS_REGULAR)) { + json j_pool; + { + j_pool = load_json_from_file(pool_filename); + if (j_pool.count("_imp")) + j_pool.erase("_imp"); + } + auto delta = json::diff(j_cache, j_pool); + item.delta = delta; + if (delta.size()) { + item.state = PoolCacheStatus::Item::State::OUT_OF_DATE; + status_thread.n_out_of_date++; + } + else { + item.state = PoolCacheStatus::Item::State::CURRENT; + status_thread.n_current++; + } + } + else { + item.state = PoolCacheStatus::Item::State::MISSING_IN_POOL; + status_thread.n_missing++; + } + } + } + { + auto models_path = Glib::build_filename(pool_cache_path, "3d_models"); + if (Glib::file_test(models_path, Glib::FILE_TEST_IS_DIR)) { + Glib::Dir dir_3d(models_path); + for (const auto &it : dir_3d) { + if (it.find("pool_") == 0 && it.size() == 41) { + UUID pool_uuid(it.substr(5)); + auto it_pool = PoolManager::get().get_by_uuid(pool_uuid); + if (it_pool) { + auto &this_pool_base_path = it_pool->base_path; + auto this_pool_cache_path = Glib::build_filename(models_path, it); + find_files(this_pool_cache_path, [this, &this_pool_base_path, + &this_pool_cache_path](const std::string &path) { + status_thread.items.emplace_back(); + auto &item = status_thread.items.back(); + status_thread.n_total++; + auto filename_cached = Glib::build_filename(this_pool_cache_path, path); + auto filename_pool = Glib::build_filename(this_pool_base_path, path); + item.filename_cached = path; + item.name = Glib::path_get_basename(path); + item.type = ObjectType::MODEL_3D; + item.uuid = UUID::random(); + if (Glib::file_test(filename_pool, Glib::FILE_TEST_IS_REGULAR)) { + if (compare_files(filename_cached, filename_pool)) { + item.state = PoolCacheStatus::Item::State::CURRENT; + status_thread.n_current++; + } + else { + item.state = PoolCacheStatus::Item::State::OUT_OF_DATE; + status_thread.n_out_of_date++; + } + } + else { + item.state = PoolCacheStatus::Item::State::MISSING_IN_POOL; + status_thread.n_missing++; + } + }); + } + } + } + } + } + } + catch (const SQLite::Error &e) { + status_thread.items.clear(); + status_thread.n_total = -1; + } + } + dispatcher.emit(); +} + +void PoolCacheMonitor::update() +{ + timer_connection.disconnect(); + timer_connection = + Glib::signal_timeout().connect_seconds(sigc::mem_fun(*this, &PoolCacheMonitor::really_update), 1); +} + +void PoolCacheMonitor::update_now() +{ + timer_connection.disconnect(); + really_update(); +} + +PoolCacheMonitor::~PoolCacheMonitor() +{ + if (thread.joinable()) + thread.join(); +} + +} // namespace horizon diff --git a/pool/shard007/C++/0091214_WinServices.cpp b/pool/shard007/C++/0091214_WinServices.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b3b5551a94e996fef6efdca691ccc09ccc7abff9 --- /dev/null +++ b/pool/shard007/C++/0091214_WinServices.cpp @@ -0,0 +1,107 @@ +/* -*- Mode: C; tab-width: 4 -*- + * + * Copyright (c) 1997-2004 Apple Computer, Inc. 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. + + Change History (most recent first): + +$Log: WinServices.cpp,v $ +Revision 1.3 2009/06/22 23:25:04 herscher +<rdar://problem/5265747> ControlPanel doesn't display key and password in dialog box. Refactor Lsa calls into Secret.h and Secret.c, which is used by both the ControlPanel and mDNSResponder system service. + +Revision 1.2 2006/08/14 23:25:20 cheshire +Re-licensed mDNSResponder daemon source code under Apache License, Version 2.0 + +Revision 1.1 2004/06/18 05:23:33 rpantos +First checked in + + +*/ + +#include "WinServices.h" +#include <DebugServices.h> + + +//=========================================================================================================================== +// UTF8StringToStringObject +//=========================================================================================================================== + +OSStatus UTF8StringToStringObject( const char *inUTF8, CString &inObject ) +{ + OSStatus err; + int n; + BSTR unicode; + + unicode = NULL; + + n = MultiByteToWideChar( CP_UTF8, 0, inUTF8, -1, NULL, 0 ); + if( n > 0 ) + { + unicode = (BSTR) malloc( (size_t)( n * sizeof( wchar_t ) ) ); + if( !unicode ) + { + err = ERROR_INSUFFICIENT_BUFFER; + goto exit; + } + + n = MultiByteToWideChar( CP_UTF8, 0, inUTF8, -1, unicode, n ); + try + { + inObject = unicode; + } + catch( ... ) + { + err = ERROR_NO_UNICODE_TRANSLATION; + goto exit; + } + } + else + { + inObject = ""; + } + err = ERROR_SUCCESS; + +exit: + if( unicode ) + { + free( unicode ); + } + return( err ); +} + + +//=========================================================================================================================== +// UTF8StringToStringObject +//=========================================================================================================================== + +OSStatus +StringObjectToUTF8String( CString &inObject, char* outUTF8, size_t outUTF8Len ) +{ + OSStatus err = kNoErr; + + memset( outUTF8, 0, outUTF8Len ); + + if ( inObject.GetLength() > 0 ) + { + size_t size; + + size = (size_t) WideCharToMultiByte( CP_UTF8, 0, inObject.GetBuffer(), inObject.GetLength(), outUTF8, (int) outUTF8Len, NULL, NULL); + err = translate_errno( size != 0, GetLastError(), kUnknownErr ); + require_noerr( err, exit ); + } + +exit: + + return err; +} diff --git a/pool/shard007/C++/0091219_LTE_fdd_enb_msgq.cc b/pool/shard007/C++/0091219_LTE_fdd_enb_msgq.cc new file mode 100644 index 0000000000000000000000000000000000000000..ef87336491479b972ddb54c9fac159eef0fc8ad9 --- /dev/null +++ b/pool/shard007/C++/0091219_LTE_fdd_enb_msgq.cc @@ -0,0 +1,233 @@ +#line 2 "LTE_fdd_enb_msgq.cc" // Make __FILE__ omit the path +/******************************************************************************* + + Copyright 2013-2015 Ben Wojtowicz + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +******************************************************************************* + + File: LTE_fdd_enb_msgq.cc + + Description: Contains all the implementations for the LTE FDD eNodeB + message queues. + + Revision History + ---------- ------------- -------------------------------------------- + 11/10/2013 Ben Wojtowicz Created file + 11/23/2013 Ben Wojtowicz Fixed a bug with receive size. + 01/18/2014 Ben Wojtowicz Added ability to set priorities. + 06/15/2014 Ben Wojtowicz Omitting path from __FILE__. + 02/15/2015 Ben Wojtowicz Moving to new message queue with semaphores + and circular buffers. + 03/15/2015 Ben Wojtowicz Added a mutex to the circular buffer. + 07/25/2015 Ben Wojtowicz Combined the DL and UL schedule messages into + a single PHY schedule message. + 12/06/2015 Ben Wojtowicz Changed boost::mutex and + boost::interprocess::interprocess_semaphore + to sem_t and properly initializing priority. + +*******************************************************************************/ + +/******************************************************************************* + INCLUDES +*******************************************************************************/ + +#include "LTE_fdd_enb_interface.h" +#include "LTE_fdd_enb_msgq.h" + +/******************************************************************************* + DEFINES +*******************************************************************************/ + + +/******************************************************************************* + TYPEDEFS +*******************************************************************************/ + + +/******************************************************************************* + GLOBAL VARIABLES +*******************************************************************************/ + + +/******************************************************************************* + CLASS IMPLEMENTATIONS +*******************************************************************************/ + +/******************/ +/* Callback */ +/******************/ +LTE_fdd_enb_msgq_cb::LTE_fdd_enb_msgq_cb() +{ +} +LTE_fdd_enb_msgq_cb::LTE_fdd_enb_msgq_cb(FuncType f, void* o) +{ + func = f; + obj = o; +} +void LTE_fdd_enb_msgq_cb::operator()(LTE_FDD_ENB_MESSAGE_STRUCT &msg) +{ + return (*func)(obj, msg); +} + +/********************************/ +/* Constructor/Destructor */ +/********************************/ +LTE_fdd_enb_msgq::LTE_fdd_enb_msgq(std::string _msgq_name) +{ + sem_init(&sync_sem, 0, 1); + sem_init(&msg_sem, 0, 1); + circ_buf = new boost::circular_buffer<LTE_FDD_ENB_MESSAGE_STRUCT>(100); + msgq_name = _msgq_name; + rx_setup = false; +} +LTE_fdd_enb_msgq::~LTE_fdd_enb_msgq() +{ + if(rx_setup) + { + send(LTE_FDD_ENB_MESSAGE_TYPE_KILL, + LTE_FDD_ENB_DEST_LAYER_ANY, + NULL, + 0); + + // Cleanup thread + pthread_cancel(rx_thread); + pthread_join(rx_thread, NULL); + rx_setup = false; + } + sem_destroy(&msg_sem); + sem_destroy(&sync_sem); + delete circ_buf; +} + +/***************/ +/* Setup */ +/***************/ +void LTE_fdd_enb_msgq::attach_rx(LTE_fdd_enb_msgq_cb cb) +{ + callback = cb; + prio = 0; + pthread_create(&rx_thread, NULL, &receive_thread, this); + rx_setup = true; +} +void LTE_fdd_enb_msgq::attach_rx(LTE_fdd_enb_msgq_cb cb, + uint32 _prio) +{ + callback = cb; + prio = _prio; + pthread_create(&rx_thread, NULL, &receive_thread, this); + rx_setup = true; +} + +/**********************/ +/* Send/Receive */ +/**********************/ +void LTE_fdd_enb_msgq::send(LTE_FDD_ENB_MESSAGE_TYPE_ENUM type, + LTE_FDD_ENB_DEST_LAYER_ENUM dest_layer, + LTE_FDD_ENB_MESSAGE_UNION *msg_content, + uint32 msg_content_size) +{ + LTE_FDD_ENB_MESSAGE_STRUCT msg; + + msg.type = type; + msg.dest_layer = dest_layer; + if(msg_content != NULL) + { + memcpy(&msg.msg, msg_content, msg_content_size); + } + + sem_wait(&sync_sem); + circ_buf->push_back(msg); + sem_post(&sync_sem); + sem_post(&msg_sem); +} +void LTE_fdd_enb_msgq::send(LTE_FDD_ENB_MESSAGE_TYPE_ENUM type, + LTE_FDD_ENB_DL_SCHEDULE_MSG_STRUCT *dl_sched, + LTE_FDD_ENB_UL_SCHEDULE_MSG_STRUCT *ul_sched) +{ + LTE_FDD_ENB_MESSAGE_STRUCT msg; + + msg.type = type; + msg.dest_layer = LTE_FDD_ENB_DEST_LAYER_PHY; + memcpy(&msg.msg.phy_schedule.dl_sched, dl_sched, sizeof(LTE_FDD_ENB_DL_SCHEDULE_MSG_STRUCT)); + memcpy(&msg.msg.phy_schedule.ul_sched, ul_sched, sizeof(LTE_FDD_ENB_UL_SCHEDULE_MSG_STRUCT)); + + sem_wait(&sync_sem); + circ_buf->push_back(msg); + sem_post(&sync_sem); + sem_post(&msg_sem); +} +void LTE_fdd_enb_msgq::send(LTE_FDD_ENB_MESSAGE_STRUCT &msg) +{ + sem_wait(&sync_sem); + circ_buf->push_back(msg); + sem_post(&sync_sem); + sem_post(&msg_sem); +} +void* LTE_fdd_enb_msgq::receive_thread(void *inputs) +{ + LTE_fdd_enb_interface *interface = LTE_fdd_enb_interface::get_instance(); + LTE_fdd_enb_msgq *msgq = (LTE_fdd_enb_msgq *)inputs; + LTE_FDD_ENB_MESSAGE_STRUCT msg; + struct sched_param priority; + bool not_done = true; + + // Set priority + if(msgq->prio != 0) + { + // FIXME: verify + priority.sched_priority = msgq->prio; + pthread_setschedparam(msgq->rx_thread, SCHED_FIFO, &priority); + } + + while(not_done) + { + // Wait for a message + sem_wait(&msgq->msg_sem); + sem_wait(&msgq->sync_sem); + if(msgq->circ_buf->size() != 0) + { + while(msgq->circ_buf->size() != 0) + { + msg = msgq->circ_buf->front(); + msgq->circ_buf->pop_front(); + sem_post(&msgq->sync_sem); + + // Process message + switch(msg.type) + { + case LTE_FDD_ENB_MESSAGE_TYPE_KILL: + not_done = false; + break; + default: + msgq->callback(msg); + break; + } + + sem_wait(&msgq->sync_sem); + } + }else{ + interface->send_debug_msg(LTE_FDD_ENB_DEBUG_TYPE_ERROR, + LTE_FDD_ENB_DEBUG_LEVEL_MSGQ, + __FILE__, + __LINE__, + "%s circular buffer empty on receive", + msgq->msgq_name.c_str()); + } + sem_post(&msgq->sync_sem); + } + + return(NULL); +} diff --git a/pool/shard007/C++/0091223_581B.cpp b/pool/shard007/C++/0091223_581B.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e858c5ff875ee15d9bccb52883ef46d27d553a09 --- /dev/null +++ b/pool/shard007/C++/0091223_581B.cpp @@ -0,0 +1,48 @@ +#include <bits/stdc++.h> +using namespace std; + +// typedef +typedef long long ll; +typedef pair<int,int> ii; +typedef pair<double,double> dd; +typedef vector<int> vi; +typedef vector<double> vd; +typedef vector<string> vs; +typedef vector<char> vc; +typedef vector<ii> vii; +typedef vector<vi> vvi; +typedef vector<bool> vb; + +#define abs(_x) ((_x)<0?-(_x):(_x)) +#define REP(_a,_b) for(int (_a)=0;(_a)<(_b);++(_a)) +#define mp(_x,_y) make_pair((_x),(_y)) +#define PI 3.1415926535897932385 +#define EPS 1e-9 +#define INF 0x00FFFFFF +#define INFLL 0x00FFFFFFFFFFFFFFLL +#define ceildiv(_a,_b) ((_a)%(_b)==0?(_a)/(_b):((_a)/(_b))+1) +#define fi first +#define se second + +int main(int argc, char **argv){ + ios_base::sync_with_stdio(0); + cin.tie(0); + + int n; + cin>>n; + vi v(n),mx(n+1),h(n); + for(int i=0;i<n;++i)cin>>v[i]; + + + mx[n]=0; + for(int i=n-1;i>=0;--i){ + if(v[i]>mx[i+1])h[i]=0; + else h[i]=mx[i+1]-v[i]+1; + mx[i]=max(v[i],mx[i+1]); + } + + for(int i=0;i<n;++i) + cout<<h[i]<<(i==n-1?'\n':' '); + + return 0; +} diff --git a/pool/shard007/C++/0091224_ImputController.cpp b/pool/shard007/C++/0091224_ImputController.cpp new file mode 100644 index 0000000000000000000000000000000000000000..23debb04bafba36e7a420f8baed916dd6dff767a --- /dev/null +++ b/pool/shard007/C++/0091224_ImputController.cpp @@ -0,0 +1,39 @@ +#include "stdafx.h" +#include "ImputController.h" + + +ImputController::ImputController() +{ + std::fill_n(keyPressed, (int)sf::Keyboard::KeyCount, false); +} + + +ImputController::~ImputController() +{ +} + +void ImputController::checkKeyState() +{ + bool keyPressedTemp[sf::Keyboard::KeyCount]; + std::copy(std::begin(keyPressed), std::end(keyPressed), std::begin(keyPressedTemp)); + for (Controllable* keyCtrl : controllables){ + for (int keylist : keyCtrl->getWatchlist()){ + if (sf::Keyboard::isKeyPressed((sf::Keyboard::Key)keylist) && !keyPressed[keylist]){ + keyCtrl->_OnKeyDown((sf::Keyboard::Key)keylist); + keyPressedTemp[keylist] = true; + }else if (!sf::Keyboard::isKeyPressed((sf::Keyboard::Key)keylist) && keyPressed[keylist]){ + keyCtrl->_OnKeyUp((sf::Keyboard::Key)keylist); + keyPressedTemp[keylist] = false; + } + if (sf::Keyboard::isKeyPressed((sf::Keyboard::Key)keylist)){ + keyCtrl->_OnKeyPressing((sf::Keyboard::Key)keylist); + } + } + } + std::copy(std::begin(keyPressedTemp), std::end(keyPressedTemp), std::begin(keyPressed)); +} + +void ImputController::addControllable(Controllable* ctrla) +{ + controllables.push_back(ctrla); +} diff --git a/pool/shard007/C++/0091226_EncryptionSatisfiesSchema.cpp b/pool/shard007/C++/0091226_EncryptionSatisfiesSchema.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b920cf43e17524c316bcd58c2c5fef9e664d3bc6 --- /dev/null +++ b/pool/shard007/C++/0091226_EncryptionSatisfiesSchema.cpp @@ -0,0 +1,62 @@ +/************************************************************************ +** +** Copyright (C) 2010 Strahinja Markovic +** +** This file is part of FlightCrew. +** +** FlightCrew is free software: you can redistribute it and/or modify +** it under the terms of the GNU Lesser General Public License as published +** by the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** FlightCrew is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public License +** along with FlightCrew. If not, see <http://www.gnu.org/licenses/>. +** +*************************************************************************/ + +#include <stdafx.h> +#include "EncryptionSatisfiesSchema.h" +#include "Result.h" +#include <ToXercesStringConverter.h> + + +namespace FlightCrew +{ + + +EncryptionSatisfiesSchema::EncryptionSatisfiesSchema() + : + m_EncryptionSchema( ENCRYPTION_XSD, + ENCRYPTION_XSD_LEN, + toX( ENCRYPTION_XSD_ID ) ), + m_XencSchema( XENC_SCHEMA_XSD, + XENC_SCHEMA_XSD_LEN, + toX( XENC_SCHEMA_XSD_ID ) ), + m_XmldsigSchema( XMLDSIG_CORE_SCHEMA_XSD, + XMLDSIG_CORE_SCHEMA_XSD_LEN, + toX( XMLDSIG_CORE_SCHEMA_XSD_ID ) ) +{ + +} + + +std::vector< Result > EncryptionSatisfiesSchema::ValidateFile( const fs::path &filepath ) +{ + std::string location = std::string( CONTAINER_XSD_NS ) + .append( " " ) + .append( ENCRYPTION_XSD_ID ); + + std::vector< const xc::MemBufInputSource* > schemas; + schemas.push_back( &m_XmldsigSchema ); + schemas.push_back( &m_XencSchema ); + schemas.push_back( &m_EncryptionSchema ); + + return ValidateAgainstSchema( filepath, location, schemas ); +} + +} //namespace FlightCrew diff --git a/pool/shard007/C++/0091230_SSHTest.cpp b/pool/shard007/C++/0091230_SSHTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bfe2c51c423412a55805adb59a9b4fd20c13ef1c --- /dev/null +++ b/pool/shard007/C++/0091230_SSHTest.cpp @@ -0,0 +1,123 @@ +#include "SSHTest.h" +#include "SubutaiLauncher.h" +#include "Poco/CppUnit/TestCaller.h" +#include "Poco/CppUnit/TestSuite.h" + +SSHTest::SSHTest(const std::string& name) : CppUnit::TestCase(name) +{ + +} + +SSHTest::~SSHTest() +{ + +} + +void SSHTest::setUp() +{ +} + +void SSHTest::tearDown() +{ +} + +void SSHTest::testFindInstallation() +{ + SubutaiLauncher::SSH *pSSH = new SubutaiLauncher::SSH(); + assert(pSSH->findInstallation()); + delete pSSH; +} + +void SSHTest::testConnect() +{ + SubutaiLauncher::SSH *pSSH = new SubutaiLauncher::SSH(); + pSSH->setHost("127.0.0.1", 4567); + pSSH->connect(); + auto connected = pSSH->isConnected(); + delete pSSH; + assert(connected); +} + +void SSHTest::testAuthenticate() +{ + SubutaiLauncher::SSH* pSSH = new SubutaiLauncher::SSH(); + pSSH->setHost("127.0.0.1", 4567); + pSSH->setUsername("subutai", "ubuntai"); + pSSH->connect(); + pSSH->authenticate(); + assert(pSSH->isAuthenticated()); +} + +void SSHTest::testCommand() +{ + SubutaiLauncher::SSH* pSSH = new SubutaiLauncher::SSH(); + pSSH->setHost("127.0.0.1", 4567); + pSSH->setUsername("subutai", "ubuntai"); + pSSH->connect(); + pSSH->authenticate(); + pSSH->execute("touch /tmp/unit-test-command"); + delete pSSH; +} + +void SSHTest::testExecuteInShell() +{ + auto sess = SubutaiLauncher::Session::instance(); + SubutaiLauncher::SSH::initialize(); + sess->setSSHCredentials("subutai", "ubuntai", "127.0.0.1", 4567); + sess->makeSSHSession("ut"); + std::string out; + try + { + auto s = sess->getSSHSession("ut"); + assert(s != nullptr); + s->openShell(); + out = s->executeInShell("touch /tmp/unit-test-in-shell ;\r\r"); + s->closeShell(); + sess->finalizeSSHSession("ut"); + } + catch (SubutaiLauncher::SSHException& exc) + { + std::printf("Exception: %s\n", exc.displayText().c_str()); + } +} + +void SSHTest::testExecuteInThread() +{ + try + { + SubutaiLauncher::SSH::initialize(); + std::printf("-1\n"); + SubutaiLauncher::SSH* pSSH = new SubutaiLauncher::SSH(true); + std::printf("0\n"); + pSSH->openChannel(); + std::printf("1\n"); + pSSH->setHost("127.0.0.1", 4567); + std::printf("2\n"); + pSSH->setUsername("subutai", "ubuntai"); + std::printf("3\n"); + std::thread pThread = pSSH->executeInThread("touch /tmp/unit-test-in-thread"); + std::printf("4\n"); + if (pThread.joinable()) pThread.join(); + std::printf("5\n"); + delete pSSH; + } + catch (SubutaiLauncher::SSHException& exc) + { + std::printf("Exception: %s\n", exc.displayText().c_str()); + } +} + +CppUnit::Test * SSHTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SSHTest"); + + //CppUnit_addTest(pSuite, SSHTest, testFindInstallation); + //CppUnit_addTest(pSuite, SSHTest, testConnect); + //CppUnit_addTest(pSuite, SSHTest, testAuthenticate); + //CppUnit_addTest(pSuite, SSHTest, testCommand); + //CppUnit_addTest(pSuite, SSHTest, testExecuteInThread); + CppUnit_addTest(pSuite, SSHTest, testExecuteInShell); + + return pSuite; +} + diff --git a/pool/shard007/C++/0091239_face.cpp b/pool/shard007/C++/0091239_face.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b37dfb9e9c78861bbd82e054b67d8839be3f0e8f --- /dev/null +++ b/pool/shard007/C++/0091239_face.cpp @@ -0,0 +1,141 @@ +/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ +/** + * Copyright (c) 2014-2015, Regents of the University of California, + * Arizona Board of Regents, + * Colorado State University, + * University Pierre & Marie Curie, Sorbonne University, + * Washington University in St. Louis, + * Beijing Institute of Technology, + * The University of Memphis. + * + * This file is part of NFD (Named Data Networking Forwarding Daemon). + * See AUTHORS.md for complete list of NFD authors and contributors. + * + * NFD is free software: you can redistribute it and/or modify it under the terms + * of the GNU General Public License as published by the Free Software Foundation, + * either version 3 of the License, or (at your option) any later version. + * + * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + * PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "face.hpp" + +#include <ndn-cxx/management/nfd-face-event-notification.hpp> + +namespace nfd { + +Face::Face(const FaceUri& remoteUri, const FaceUri& localUri, bool isLocal, bool isMultiAccess) + : m_id(INVALID_FACEID) + , m_remoteUri(remoteUri) + , m_localUri(localUri) + , m_isLocal(isLocal) + , m_persistency(ndn::nfd::FACE_PERSISTENCY_PERSISTENT) + , m_isMultiAccess(isMultiAccess) + , m_isFailed(false) + , m_metric(0) +{ + onReceiveInterest.connect([this] (const ndn::Interest&) { ++m_counters.getNInInterests(); }); + onReceiveData .connect([this] (const ndn::Data&) { ++m_counters.getNInDatas(); }); + onReceiveBead .connect([this] (const ndn::Bead&) { ++m_counters.getNInBeads(); }); + onSendInterest .connect([this] (const ndn::Interest&) { ++m_counters.getNOutInterests(); }); + onSendData .connect([this] (const ndn::Data&) { ++m_counters.getNOutDatas(); }); + + // Testing it out... + onSendBead .connect([this] (const ndn::Bead&) { + ++m_counters.getNOutBeads(); + }); +} + +Face::~Face() +{ +} + +bool +Face::isUp() const +{ + return true; +} + +bool +Face::decodeAndDispatchInput(const Block& element) +{ + try { + /// \todo Ensure lazy field decoding process + + if (element.type() == tlv::Interest) + { + shared_ptr<Interest> i = make_shared<Interest>(); + i->wireDecode(element); + this->onReceiveInterest(*i); + } + else if (element.type() == tlv::Data) + { + shared_ptr<Data> d = make_shared<Data>(); + d->wireDecode(element); + this->onReceiveData(*d); + } + else if (element.type() == tlv::Bead) + { + std::cout << "BEAD Face::decodeAndDispatchInput" << std::endl; + shared_ptr<Bead> d = make_shared<Bead>(); + d->wireDecode(element); + this->onReceiveBead(*d); + } + else + return false; + + return true; + } + catch (const tlv::Error&) { + return false; + } +} + +void +Face::fail(const std::string& reason) +{ + if (m_isFailed) { + return; + } + + m_isFailed = true; + this->onFail(reason); +} + +template<typename FaceTraits> +void +Face::copyStatusTo(FaceTraits& traits) const +{ + traits.setFaceId(getId()) + .setRemoteUri(getRemoteUri().toString()) + .setLocalUri(getLocalUri().toString()) + .setFaceScope(isLocal() ? ndn::nfd::FACE_SCOPE_LOCAL + : ndn::nfd::FACE_SCOPE_NON_LOCAL) + .setFacePersistency(getPersistency()) + .setLinkType(isMultiAccess() ? ndn::nfd::LINK_TYPE_MULTI_ACCESS + : ndn::nfd::LINK_TYPE_POINT_TO_POINT); +} + +template void +Face::copyStatusTo<ndn::nfd::FaceStatus>(ndn::nfd::FaceStatus&) const; + +template void +Face::copyStatusTo<ndn::nfd::FaceEventNotification>(ndn::nfd::FaceEventNotification&) const; + +ndn::nfd::FaceStatus +Face::getFaceStatus() const +{ + ndn::nfd::FaceStatus status; + + copyStatusTo(status); + this->getCounters().copyTo(status); + + return status; +} + +} // namespace nfd diff --git a/pool/shard007/C++/0091245_dependencies.cpp b/pool/shard007/C++/0091245_dependencies.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0bdae15cadd02686f8ffa47d24e0fbebc07682b6 --- /dev/null +++ b/pool/shard007/C++/0091245_dependencies.cpp @@ -0,0 +1,91 @@ +/* + * %injeqt copyright begin% + * Copyright 2014 Rafał Malinowski (rafal.przemyslaw.malinowski@gmail.com) + * %injeqt copyright end% + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "dependencies.h" + +#include <injeqt/exception/dependency-on-self.h> +#include <injeqt/exception/dependency-on-subtype.h> +#include <injeqt/exception/dependency-on-supertype.h> +#include <injeqt/exception/exception.h> +#include <injeqt/exception/invalid-dependency.h> +#include <injeqt/exception/invalid-setter.h> +#include <injeqt/type.h> + +#include "dependency.h" +#include "interfaces-utils.h" +#include "setter-method.h" +#include "type-relations.h" + +#include <QtCore/QMetaMethod> +#include <algorithm> +#include <cassert> +#include <set> + +namespace injeqt { namespace internal { + +namespace { + +std::vector<setter_method> extract_setters(const types_by_name &known_types, const type &for_type) +{ + assert(!for_type.is_empty()); + + auto result = std::vector<setter_method>{}; + + auto meta_object = for_type.meta_object(); + auto method_count = meta_object->methodCount(); + for (decltype(method_count) i = 0; i < method_count; i++) + { + auto maybe_setter = meta_object->method(i); + if (setter_method::is_setter_tag(maybe_setter.tag())) + result.emplace_back(make_setter_method(known_types, maybe_setter)); + } + + return result; +} + +} + +dependencies extract_dependencies(const types_by_name &known_types, const type &for_type) +{ + assert(!for_type.is_empty()); + + auto interfaces = extract_interfaces(for_type); + auto setters = extract_setters(known_types, for_type); + for (auto &&setter : setters) + { + auto parameter_type = setter.parameter_type(); + if (parameter_type == for_type) + throw exception::dependency_on_self{}; + if (std::find(std::begin(interfaces), std::end(interfaces), parameter_type) != std::end(interfaces)) + throw exception::dependency_on_supertype{}; + auto parameter_interfaces = extract_interfaces(parameter_type); + if (std::find(std::begin(parameter_interfaces), std::end(parameter_interfaces), for_type) != std::end(parameter_interfaces)) + throw exception::dependency_on_subtype{}; + } + + auto result = std::vector<dependency>{}; + std::transform(std::begin(setters), std::end(setters), std::back_inserter(result), + [](const setter_method &setter){ return dependency{setter}; } + ); + + return dependencies{result}; +} + +}} diff --git a/pool/shard007/C++/0091247_nsPrintData.cpp b/pool/shard007/C++/0091247_nsPrintData.cpp new file mode 100644 index 0000000000000000000000000000000000000000..05795f54e7f803b00778dfe170c73b406c926da4 --- /dev/null +++ b/pool/shard007/C++/0091247_nsPrintData.cpp @@ -0,0 +1,130 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "nsPrintData.h" + +#include "nsIStringBundle.h" +#include "nsIServiceManager.h" +#include "nsPrintObject.h" +#include "nsPrintPreviewListener.h" +#include "nsIWebProgressListener.h" +#include "mozilla/Services.h" + +//----------------------------------------------------- +// PR LOGGING +#ifdef MOZ_LOGGING +#define FORCE_PR_LOG /* Allow logging in the release build */ +#endif + +#include "prlog.h" + +#ifdef PR_LOGGING +#define DUMP_LAYOUT_LEVEL 9 // this turns on the dumping of each doucment's layout info +static PRLogModuleInfo * kPrintingLogMod = PR_NewLogModule("printing"); +#define PR_PL(_p1) PR_LOG(kPrintingLogMod, PR_LOG_DEBUG, _p1); +#else +#define PRT_YESNO(_p) +#define PR_PL(_p1) +#endif + +//--------------------------------------------------- +//-- nsPrintData Class Impl +//--------------------------------------------------- +nsPrintData::nsPrintData(ePrintDataType aType) : + mType(aType), mDebugFilePtr(nullptr), mPrintObject(nullptr), mSelectedPO(nullptr), + mPrintDocList(0), mIsIFrameSelected(false), + mIsParentAFrameSet(false), mOnStartSent(false), + mIsAborted(false), mPreparingForPrint(false), mDocWasToBeDestroyed(false), + mShrinkToFit(false), mPrintFrameType(nsIPrintSettings::kFramesAsIs), + mNumPrintablePages(0), mNumPagesPrinted(0), + mShrinkRatio(1.0), mOrigDCScale(1.0), mPPEventListeners(NULL), + mBrandName(nullptr) +{ + MOZ_COUNT_CTOR(nsPrintData); + nsCOMPtr<nsIStringBundle> brandBundle; + nsCOMPtr<nsIStringBundleService> svc = + mozilla::services::GetStringBundleService(); + if (svc) { + svc->CreateBundle( "chrome://branding/locale/brand.properties", getter_AddRefs( brandBundle ) ); + if (brandBundle) { + brandBundle->GetStringFromName(NS_LITERAL_STRING("brandShortName").get(), &mBrandName ); + } + } + + if (!mBrandName) { + mBrandName = ToNewUnicode(NS_LITERAL_STRING("Mozilla Document")); + } + +} + +nsPrintData::~nsPrintData() +{ + MOZ_COUNT_DTOR(nsPrintData); + // remove the event listeners + if (mPPEventListeners) { + mPPEventListeners->RemoveListeners(); + NS_RELEASE(mPPEventListeners); + } + + // Only Send an OnEndPrinting if we have started printing + if (mOnStartSent && mType != eIsPrintPreview) { + OnEndPrinting(); + } + + if (mPrintDC && !mDebugFilePtr) { + PR_PL(("****************** End Document ************************\n")); + PR_PL(("\n")); + bool isCancelled = false; + mPrintSettings->GetIsCancelled(&isCancelled); + + nsresult rv = NS_OK; + if (mType == eIsPrinting) { + if (!isCancelled && !mIsAborted) { + rv = mPrintDC->EndDocument(); + } else { + rv = mPrintDC->AbortDocument(); + } + if (NS_FAILED(rv)) { + // XXX nsPrintData::ShowPrintErrorDialog(rv); + } + } + } + + delete mPrintObject; + + if (mBrandName) { + NS_Free(mBrandName); + } +} + +void nsPrintData::OnStartPrinting() +{ + if (!mOnStartSent) { + DoOnProgressChange(0, 0, true, nsIWebProgressListener::STATE_START|nsIWebProgressListener::STATE_IS_DOCUMENT|nsIWebProgressListener::STATE_IS_NETWORK); + mOnStartSent = true; + } +} + +void nsPrintData::OnEndPrinting() +{ + DoOnProgressChange(100, 100, true, nsIWebProgressListener::STATE_STOP|nsIWebProgressListener::STATE_IS_DOCUMENT); + DoOnProgressChange(100, 100, true, nsIWebProgressListener::STATE_STOP|nsIWebProgressListener::STATE_IS_NETWORK); +} + +void +nsPrintData::DoOnProgressChange(int32_t aProgress, + int32_t aMaxProgress, + bool aDoStartStop, + int32_t aFlag) +{ + for (int32_t i=0;i<mPrintProgressListeners.Count();i++) { + nsIWebProgressListener* wpl = mPrintProgressListeners.ObjectAt(i); + wpl->OnProgressChange(nullptr, nullptr, aProgress, aMaxProgress, aProgress, aMaxProgress); + if (aDoStartStop) { + wpl->OnStateChange(nullptr, nullptr, aFlag, NS_OK); + } + } +} + diff --git a/pool/shard007/C++/0091252_resizeindicator.cpp b/pool/shard007/C++/0091252_resizeindicator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a2a9cd13d01160c500573ab86d8b6dbf96b9a286 --- /dev/null +++ b/pool/shard007/C++/0091252_resizeindicator.cpp @@ -0,0 +1,102 @@ +/************************************************************************** +** +** This file is part of Qt Creator +** +** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). +** +** Contact: Nokia Corporation (info@qt.nokia.com) +** +** +** GNU Lesser General Public License Usage +** +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this file. +** Please review the following information to ensure the GNU Lesser General +** Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** Other Usage +** +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** If you have questions regarding the use of this file, please contact +** Nokia at info@qt.nokia.com. +** +**************************************************************************/ + +#include "resizeindicator.h" + +#include "formeditoritem.h" + +namespace QmlDesigner { + +ResizeIndicator::ResizeIndicator(LayerItem *layerItem) + : m_layerItem(layerItem) +{ + Q_ASSERT(layerItem); +} + +ResizeIndicator::~ResizeIndicator() +{ + m_itemControllerHash.clear(); +} + +void ResizeIndicator::show() +{ + QHashIterator<FormEditorItem*, ResizeController> itemControllerIterator(m_itemControllerHash); + while (itemControllerIterator.hasNext()) { + ResizeController controller = itemControllerIterator.next().value(); + controller.show(); + } +} +void ResizeIndicator::hide() +{ + QHashIterator<FormEditorItem*, ResizeController> itemControllerIterator(m_itemControllerHash); + while (itemControllerIterator.hasNext()) { + ResizeController controller = itemControllerIterator.next().value(); + controller.hide(); + } +} + +void ResizeIndicator::clear() +{ + m_itemControllerHash.clear(); +} + +void ResizeIndicator::setItems(const QList<FormEditorItem*> &itemList) +{ + clear(); + + foreach (FormEditorItem* item, itemList) { + if (item + && item->qmlItemNode().isValid() + && item->qmlItemNode().instanceIsResizable() + && !item->qmlItemNode().instanceHasRotationTransform() + && !item->qmlItemNode().instanceIsInPositioner()) { + ResizeController controller(m_layerItem, item); + m_itemControllerHash.insert(item, controller); + } + } +} + +void ResizeIndicator::updateItems(const QList<FormEditorItem*> &itemList) +{ + foreach (FormEditorItem* item, itemList) { + if (m_itemControllerHash.contains(item)) { + if (item->qmlItemNode().instanceHasRotationTransform()) { + m_itemControllerHash.take(item); + } else { + ResizeController controller(m_itemControllerHash.value(item)); + controller.updatePosition(); + } + } + } +} + +} diff --git a/pool/shard007/C++/0091260_Instance.cpp b/pool/shard007/C++/0091260_Instance.cpp new file mode 100644 index 0000000000000000000000000000000000000000..043594d72c4e012b1377b5009b8be5c9b928ce7f --- /dev/null +++ b/pool/shard007/C++/0091260_Instance.cpp @@ -0,0 +1,99 @@ +// Copyright 2016 Zheng Xian Qiu + +#include "Instance.h" + +namespace Seeker { + + const int Instance::FPS = 60; + const int Instance::FIXED_DELTA_TIME = 1000/60; + + Instance::Instance() : Instance(new GameState()) { + } + + Instance::Instance(GameState* state) : state(state), stop(false) { + window = new class Window; + if(window->Create(Config::Window.Name, Config::Window.Width, Config::Window.Height) == false) { + // TODO: Use custom exception instead it. + delete window; + throw false; + } + renderer = window->Renderer(); + + EventManager::On(this); + + nextTime = CurrentTime(); + } + + Instance::~Instance() { + delete window; + } + + void Instance::Run() { + while(!stop) { + EventManager::Refresh(); + Update(); + } + } + + void Instance::Update() { + long realTime = CurrentTime(); + + while(nextTime < realTime) { + int deltaTime = realTime - lastTime; + nextTime += FIXED_DELTA_TIME; + // TODO: Modify to use "GameState" + if(state) { + state->Update(deltaTime); + IScript::UpdateAll(deltaTime); + + renderer->Clear(); + state->Render(); + IScript::RenderAll(); + renderer->Render(); + } + + realFPS = 1 / ((float) deltaTime / 1000); + lastTime = realTime; + } + } + + void Instance::Stop() { + stop = true; + } + + long Instance::CurrentTime() { + auto now = high_resolution_clock::now(); + auto nowInMillisecond = time_point_cast<milliseconds>(now); + auto epoch = nowInMillisecond.time_since_epoch(); + auto value = duration_cast<milliseconds>(epoch); + return value.count(); + } + + // ISubscriber implement + void Instance::OnEvent(const EventType type, Event& event) { + switch(type) { + case EventType::Quit: + stop = true; + break; + case EventType::Mouse: + if(static_cast<MouseEvent&>(event).button == MouseEvent::Button::Right) { + stop = true; + } + default: + break; + } + } + + GameState* Instance::State() { + return state; + } + + GameState* Instance::SetState(GameState* _state) { + state = _state; + return state; + } + + Scene* Instance::CurrentScene() { + return state->CurrentScene(); + } +} diff --git a/pool/shard007/C++/0091262_parameters.cpp b/pool/shard007/C++/0091262_parameters.cpp new file mode 100644 index 0000000000000000000000000000000000000000..628aac31f6bf6f9b946047f83a6c5799228393fd --- /dev/null +++ b/pool/shard007/C++/0091262_parameters.cpp @@ -0,0 +1,166 @@ +/* This file is part of SMART+. + + SMART+ is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + SMART+ is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with SMART+. If not, see <http://www.gnu.org/licenses/>. + + */ + +///@file parameters.cpp +///@brief Handle of input parameters +///@version 0.9 + +#include <iostream> +#include <fstream> +#include <assert.h> +#include <math.h> +#include <armadillo> + +#include <smartplus/Libraries/Identification/parameters.hpp> + +using namespace std; +using namespace arma; + +namespace smart{ + +//=====Private methods for parameters=================================== + +//=====Public methods for parameters============================================ + +//@brief default constructor +//------------------------------------------------------------- +parameters::parameters() +//------------------------------------------------------------- +{ + + number = 0; + value = 0.; //Initial Value of the parameter + min_value = 0.; //Minimum value of the parameter + max_value = 0.; //Maximum value of the parameter + ninput_files = 0; +} + +/*! + \brief Constructor + \param mnumber : number of the parameter + \param mmin_value : Minimal value of the parameter + \param mmax_value : Maximal value of the parameter + */ + +//------------------------------------------------------------- +parameters::parameters(const int &mnumber, const double &mmin_value, const double &mmax_value) +//------------------------------------------------------------- +{ + number = mnumber; + min_value = mmin_value; + max_value = mmax_value; + value = (min_value+max_value)/2.; + ninput_files = 0; +} + +/*! + \brief Constructor with parameters + \param mnumber : number of the parameter + \param mmin_value : Minimal value of the parameter + \param mmax_value : Maximal value of the parameter + */ + +//------------------------------------------------------------- +parameters::parameters(const int &mnumber, const double &mmin_value, const double &mmax_value, const string &mkey, const int &mninput_files, const std::vector<std::string> &minput_files) +//------------------------------------------------------------- +{ + number = mnumber; + min_value = mmin_value; + max_value = mmax_value; + value = (min_value+max_value)/2.; + + key = mkey; + ninput_files = mninput_files; + input_files = minput_files; +} + +/*! + \brief Copy constructor + \param ed opti_data object to duplicate + */ + +//------------------------------------------------------ +parameters::parameters(const parameters& pa) +//------------------------------------------------------ +{ + number=pa.number; + min_value = pa.min_value; + max_value = pa.max_value; + value = pa.value; + + key = pa.key; + ninput_files = pa.ninput_files; + input_files = pa.input_files; +} + +/*! + \brief destructor + */ + +parameters::~parameters() {} + +//------------------------------------------------------------- +void parameters::update(const double &p) +//------------------------------------------------------------- +{ + value = p; +} + + +//------------------------------------------------------------- +void parameters::resize(const int &n) +//------------------------------------------------------------- +{ + + ninput_files = n; + input_files.resize(n); +} + +//---------------------------------------------------------------------- +parameters& parameters::operator = (const parameters& pa) +//---------------------------------------------------------------------- +{ + number=pa.number; + min_value = pa.min_value; + max_value = pa.max_value; + value = pa.value; + + key = pa.key; + ninput_files = pa.ninput_files; + input_files = pa.input_files; + + return *this; +} + +//-------------------------------------------------------------------------- +ostream& operator << (ostream& s, const parameters& pa) +//-------------------------------------------------------------------------- +{ + + s << "Display info on the parameter data\n"; + s << "Number of the parameter: " << pa.number << "\n"; + s << "Bounds (Min and Max) values: " << pa.min_value << "\t" << pa.max_value << "\n"; + s << "Number of files impacted and list of files: " << pa.input_files.size() << "\n"; + + for (vector<string>::const_iterator iter = pa.input_files.begin(); iter != pa.input_files.end(); iter++) { + cout << *iter << "\n"; + } + + return s; +} + +} //namespace smart \ No newline at end of file diff --git a/pool/shard007/C++/0091266_EndpointUser.cpp b/pool/shard007/C++/0091266_EndpointUser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a33e49d41e53fc6ef3f3054a0b082f58aca30d5f --- /dev/null +++ b/pool/shard007/C++/0091266_EndpointUser.cpp @@ -0,0 +1,104 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include <aws/pinpoint/model/EndpointUser.h> +#include <aws/core/utils/json/JsonSerializer.h> + +#include <utility> + +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +namespace Aws +{ +namespace Pinpoint +{ +namespace Model +{ + +EndpointUser::EndpointUser() : + m_userAttributesHasBeenSet(false), + m_userIdHasBeenSet(false) +{ +} + +EndpointUser::EndpointUser(JsonView jsonValue) : + m_userAttributesHasBeenSet(false), + m_userIdHasBeenSet(false) +{ + *this = jsonValue; +} + +EndpointUser& EndpointUser::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("UserAttributes")) + { + Aws::Map<Aws::String, JsonView> userAttributesJsonMap = jsonValue.GetObject("UserAttributes").GetAllObjects(); + for(auto& userAttributesItem : userAttributesJsonMap) + { + Array<JsonView> listOf__stringJsonList = userAttributesItem.second.AsArray(); + Aws::Vector<Aws::String> listOf__stringList; + listOf__stringList.reserve((size_t)listOf__stringJsonList.GetLength()); + for(unsigned listOf__stringIndex = 0; listOf__stringIndex < listOf__stringJsonList.GetLength(); ++listOf__stringIndex) + { + listOf__stringList.push_back(listOf__stringJsonList[listOf__stringIndex].AsString()); + } + m_userAttributes[userAttributesItem.first] = std::move(listOf__stringList); + } + m_userAttributesHasBeenSet = true; + } + + if(jsonValue.ValueExists("UserId")) + { + m_userId = jsonValue.GetString("UserId"); + + m_userIdHasBeenSet = true; + } + + return *this; +} + +JsonValue EndpointUser::Jsonize() const +{ + JsonValue payload; + + if(m_userAttributesHasBeenSet) + { + JsonValue userAttributesJsonMap; + for(auto& userAttributesItem : m_userAttributes) + { + Array<JsonValue> listOf__stringJsonList(userAttributesItem.second.size()); + for(unsigned listOf__stringIndex = 0; listOf__stringIndex < listOf__stringJsonList.GetLength(); ++listOf__stringIndex) + { + listOf__stringJsonList[listOf__stringIndex].AsString(userAttributesItem.second[listOf__stringIndex]); + } + userAttributesJsonMap.WithArray(userAttributesItem.first, std::move(listOf__stringJsonList)); + } + payload.WithObject("UserAttributes", std::move(userAttributesJsonMap)); + + } + + if(m_userIdHasBeenSet) + { + payload.WithString("UserId", m_userId); + + } + + return payload; +} + +} // namespace Model +} // namespace Pinpoint +} // namespace Aws diff --git a/pool/shard007/C++/0091268_psb_cc_object.cpp b/pool/shard007/C++/0091268_psb_cc_object.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a8518df15eefa410437cca055035282b0d6e40b3 --- /dev/null +++ b/pool/shard007/C++/0091268_psb_cc_object.cpp @@ -0,0 +1,84 @@ +/* +KRKR PSBFILE Compiler/Decompiler + +Author:201724 +QQ:495159 +EMail:number201724@me.com +*/ +#include "psb_cc_object.h" +#include "psb_cc_array.h" +#include <algorithm> + +psb_cc_object::psb_cc_object(psb_cc* cc, Json::Value& sourceCode) : + psb_cc_base(cc, sourceCode, psb_value_t::TYPE_OBJECTS) +{ + vector<string> members = sourceCode.getMemberNames(); + + for (uint32_t i = 0; i < members.size(); i++) + { + string key_name = members[i]; + _objects[key_name] = cc->pack(sourceCode[key_name]); + } +} + + +psb_cc_object::~psb_cc_object() +{ +} + +bool psb_cc_object::compile() +{ + cc_stream s; + reset_data(); + + s.write_integer(psb_value_t::TYPE_OBJECTS, 0x1); + + psb_cc_array *names = new psb_cc_array(); + psb_cc_array *offsets = new psb_cc_array(); + + names->resize(_objects.size()); + offsets->resize(_objects.size()); + + vector <string> src_names = _src.getMemberNames(); + + cc_stream entries; + vector<uint32_t> names_vec; + for (uint32_t i = 0; i < src_names.size(); i++) + { + string key_name = src_names[i]; + names_vec.push_back(_cc->add_names(key_name)); + } + + sort(names_vec.begin(), names_vec.end()); + + for (uint32_t i = 0; i < names_vec.size(); i++) + { + string key_name = _cc->get_names(names_vec[i]); + names->operator[](i) = names_vec[i]; + psb_cc_base *base = _objects[key_name]; + base->compile(); + + offsets->operator[](i) = entries.get_length(); + entries.append(base->get_data(), base->get_length()); + } + + names->compile(); + offsets->compile(); + + s.append(names->get_data(), names->get_length()); + s.append(offsets->get_data(), offsets->get_length()); + s.append(entries.get_data(), entries.get_length()); + + _data = s.copy_buffer(); + _length = s.get_length(); + + dump(); + + return true; +} + +const char* psb_cc_object::get_class_name() +{ + return "psb_cc_object"; +} + diff --git a/pool/shard007/C++/0091274_candidate.cc b/pool/shard007/C++/0091274_candidate.cc new file mode 100644 index 0000000000000000000000000000000000000000..dc97743b8f0f7143705c504c12800c57e9f9a771 --- /dev/null +++ b/pool/shard007/C++/0091274_candidate.cc @@ -0,0 +1,151 @@ +// +// The MIT License (MIT) +// +// Copyright 2013-2014 The MilkCat Project Developers +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +// candidate.cc --- Created at 2014-02-02 +// + +#include "neko/candidate.h" +#include <stdio.h> +#include <string.h> +#include <math.h> +#include <vector> +#include <string> +#include <unordered_map> +#include "milkcat/libmilkcat.h" +#include "utils/readable_file.h" +#include "neko/maxent_classifier.h" +#include "neko/crf_vocab.h" +#include "neko/utf8.h" + +namespace milkcat { + +// Extracts features from name_str for the maxent classifier +std::vector<std::string> ExtractNameFeature(const char *name_str) { + std::vector<std::string> feature_list; + std::vector<std::string> utf8_chars; + + // Split the name_str into a vector of utf8 characters + const char *it = name_str; + char utf8_char[16], *end; + while (*it) { + uint32_t cp = utf8::next(it); + end = utf8::append(cp, utf8_char); + *end = '\0'; + utf8_chars.push_back(utf8_char); + } + + if (utf8_chars.size() >= 2) { + feature_list.push_back(std::string("B:") + utf8_chars[0]); + feature_list.push_back(std::string("E:") + + utf8_chars[utf8_chars.size() - 1]); + for (auto it = utf8_chars.begin() + 1; it < utf8_chars.end() - 1; ++it) { + feature_list.push_back(std::string("M:") + *it); + } + } + + return feature_list; +} + +// Get the candidate from crf segmentation vocabulary specified by crf_vocab. +// Returns a map the key is the word, and the value is its cost in unigram. +std::unordered_map<std::string, float> GetCandidate( + const char *model_path, + const char *vocabulary_path, + const std::unordered_map<std::string, int> &crf_vocab, + int total_count, + int (* log_func)(const char *message), + Status *status, + int thres_freq) { + std::unordered_map<std::string, float> candidates; + char msg_text[1024]; + + ModelFactory *model_factory = new ModelFactory(MODEL_PATH); + + // If vocabulary_path != nullptr use vocabulary_path as OOV-filter otherwise + // use system dictionary as the OOV-word filter + const TrieTree *index = nullptr; + if (vocabulary_path) { + model_factory->SetUserDictionary(vocabulary_path); + index = model_factory->UserIndex(status); + } else { + index = model_factory->Index(status); + } + + MaxentModel *name_model = nullptr; + if (status->ok()) name_model = MaxentModel::New(model_path, status); + + MaxentClassifier *classifier = nullptr; + if (status->ok()) classifier = new MaxentClassifier(name_model); + + // Calculate the thres_freq via total_count if thres_freq = kDefaultThresFreq + if (thres_freq == kDefaultThresFreq) + thres_freq = static_cast<int>(atan(1e-7 * total_count) * 50) + 2; + + if (status->ok() && log != nullptr) { + snprintf(msg_text, + sizeof(msg_text), + "Threshold frequency of candidates is %d", + thres_freq); + log_func(msg_text); + } + + int person_name = 0; + std::vector<std::string> feature; + if (status->ok()) { + for (auto &x : crf_vocab) { + // If the word frequency is greater than the threshold value and it not + // exists in the original vocabulary + if (x.second > thres_freq && index->Search(x.first.c_str()) < 0) { + feature = ExtractNameFeature(x.first.c_str()); + + // Filter one character word + if (feature.size() == 0) continue; + const char *y = classifier->Classify(feature); + + // And if it is not a name + if (strcmp(y, "F") == 0) { + candidates[x.first] = -log( + static_cast<float>(x.second) / total_count); + } else { + person_name++; + } + } + } + } + + if (status->ok() && log != nullptr) { + snprintf(msg_text, + sizeof(msg_text), + "Filtered %d person names.", + person_name); + log_func(msg_text); + } + + delete name_model; + delete classifier; + delete model_factory; + + return candidates; +} + +} // namespace milkcat diff --git a/pool/shard007/C++/0091281_max_xor_w_vector.cpp b/pool/shard007/C++/0091281_max_xor_w_vector.cpp new file mode 100644 index 0000000000000000000000000000000000000000..84a5df8767c8710c5371c2e85dcacf5459f81300 --- /dev/null +++ b/pool/shard007/C++/0091281_max_xor_w_vector.cpp @@ -0,0 +1,106 @@ +// +// max_xor.cpp +// Interview +// +// Created by Mohammad Rahman on 10/16/16. +// Copyright © 2016 Mohammad Rahman. All rights reserved. +// + +#include <iostream> +#include <vector> +#include <cstdlib> +using namespace std; + + +class trieNode { +public: + const int num_width = sizeof(int)*8; + vector<vector<int>> trie; + + trieNode() { + trie.push_back(vector<int>(2, -1)); + } + + bool is_leaf(int node_n) { + if (trie[node_n][0] != -1 && trie[node_n][1] != -1) return true; + else return false; + } + + bool has_child(int node_n, int child) { + if (trie[node_n][child] != -1) return true; + else return false; + } + + int get_child(int node_n, int child) { + return trie[node_n][child]; + } + + void set_new_child(int node_n, int child) { + trie[node_n][child] = (int)trie.size(); + trie.push_back(vector<int>(2, -1)); + } + + bool get_bit(int x, int i) { + return (x & (1 << i)) != 0; + } + + void set_bit(int& x, int i) { + x = x | (1 << i); + } + + void insert(int x) { + int p = 0; + for (int i = 0; i < num_width; i++) { + if (get_bit(x, num_width - 1 - i)) { + if (!has_child(p, 1)){ + set_new_child(p, 1); + } + p = get_child(p, 1); + } + else { + if (!has_child(p, 0)){ + set_new_child(p, 0); + } + p = get_child(p, 0); + } + } + } + + int findMaxXor(int x) { + int p = 0; + int max_xor = 0; + for (int i = 0; i < num_width; i++) { + if (get_bit(x, num_width - 1 - i)) { + if (has_child(p, 0)) { + p = get_child(p, 0); + set_bit(max_xor, num_width - 1 - i); + } else { + p = get_child(p, 1); + } + } else { + if (has_child(p, 1)) { + p = get_child(p, 1); + set_bit(max_xor, num_width - 1 - i); + } else { + p = get_child(p, 0); + } + } + } + return max_xor; + } +}; + +class Solution { +public: + int findMaximumXOR(vector<int>& nums) { + if (nums.empty()) return 0; + int result = INT_MIN; + trieNode tn; + tn.insert(nums[0]); + for(int i = 0; i < nums.size(); i++) { + result = max(result, tn.findMaxXor(nums[i])); + tn.insert(nums[i]); + } + return result; + } +}; diff --git a/pool/shard007/C++/0091283_vrpn_Qt_AutoGUI.cpp b/pool/shard007/C++/0091283_vrpn_Qt_AutoGUI.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ddf4cea948faf40f807cc73dc66ed76e0f0b6e4d --- /dev/null +++ b/pool/shard007/C++/0091283_vrpn_Qt_AutoGUI.cpp @@ -0,0 +1,69 @@ +/*========================================================================= + + Name: vrpn_Qt_GUI.cpp + + Author: David Borland, EventLab + + Description: Contains the main function for vrpn_Qt_GUI. + + This is an example of generating a GUI from a simple XML + file using QAutoGUI. + +=========================================================================*/ + + +#include <QApplication> + +#include "vrpn_Qt.h" +#include "QAutoGUI.h" + +#include <QDebug> +#include <QString> + + +int main(int argc, char** argv) { + // Initialize Qt + QApplication app(argc, argv); + + + // Set default xml file, server name, and port + QString xmlFile("vrpn_Qt_AutoGUI.xml"); + char* name = "qt"; + int port = vrpn_DEFAULT_LISTEN_PORT_NO; + + // Parse the command line to override defaults + for (int i = 1; i < argc; i++) { + if (QString(argv[i]) == "-xmlFile") { + xmlFile = argv[++i]; + } + else if (QString(argv[i]) == "-serverName") { + name = argv[++i]; + } + else if (QString(argv[i]) == "-vrpnPort") { + port = QString(argv[++i]).toInt(); + } + else { + qDebug() << "Error parsing command line.\n" + << "Usage: vrpn_Qt_GUI.exe [-xmlFile fileName] [-vrpnPort portNumber]"; + } + } + + + // Set up VRPN + vrpn_Connection* connection = vrpn_create_server_connection(port); + vrpn_Qt vq(name, connection); + + // Create the GUI + QAutoGUI gui; + gui.ParseXML(xmlFile); + + // Add widgets to the vrpn_Qt + vq.AddChildren(&gui); + vq.PrintWidgets(); + + // Show the widget + gui.show(); + + return app.exec(); +} + diff --git a/pool/shard007/C++/0091290_utils.cc b/pool/shard007/C++/0091290_utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..9465c91f1e0236fc51aee07628453166f53b9748 --- /dev/null +++ b/pool/shard007/C++/0091290_utils.cc @@ -0,0 +1,60 @@ +// Copyright 2010-2012 RethinkDB, all rights reserved. +#include <unistd.h> +#include <time.h> +#include <stdlib.h> +#include <stdio.h> +#include "utils.hpp" + +/* Timing related functions */ +typedef unsigned long long ticks_t; +ticks_t secs_to_ticks(float secs) { + return (unsigned long long)secs * 1000000000L; +} + +ticks_t get_ticks() { + timespec tv; + clock_gettime(CLOCK_MONOTONIC, &tv); + return secs_to_ticks(tv.tv_sec) + tv.tv_nsec; +} + +long get_ticks_res() { + timespec tv; + clock_getres(CLOCK_MONOTONIC, &tv); + return secs_to_ticks(tv.tv_sec) + tv.tv_nsec; +} + +float ticks_to_secs(ticks_t ticks) { + return ticks / 1000000000.0f; +} + +float ticks_to_ms(ticks_t ticks) { + return ticks / 1000000.0f; +} + +float ticks_to_us(ticks_t ticks) { + return ticks / 1000.0f; +} + +void sleep_ticks(ticks_t ticks) { + int secs = ticks / secs_to_ticks(1); + if (secs) { + sleep(secs); + ticks -= secs_to_ticks(secs); + } + if (ticks) { + usleep(ticks_to_us(ticks)); + } +} + +int count_decimal_digits(int n) { + if (n < 0) { + fprintf(stderr, "Didn't expect a negative number in count_decimal_digits().\n"); + exit(-1); + } + int digits = 1; + while (n >= 10) { + n /= 10; + digits++; + } + return digits; +} diff --git a/pool/shard007/C++/0091303_value_binding.cpp b/pool/shard007/C++/0091303_value_binding.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4f5bdc9c62cd991e5e3867255542268b946fb735 --- /dev/null +++ b/pool/shard007/C++/0091303_value_binding.cpp @@ -0,0 +1,72 @@ +/* This file is part of the KDE libraries + Copyright (C) 2005, 2006 Ian Reinhart Geiser <geiseri@kde.org> + Copyright (C) 2005, 2006 Matt Broadstone <mbroadst@gmail.com> + Copyright (C) 2005, 2006 Richard J. Moore <rich@kde.org> + Copyright (C) 2005, 2006 Erik L. Bunce <kde@bunce.us> + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ +#include "value_binding.h" +#include "static_binding.h" + +using namespace KJSEmbed; + +const KJS::ClassInfo ValueBinding::info = { "ValueBinding", 0, 0, 0 }; + +KJS::JSValue *callValueType( KJS::ExecState *exec, KJS::JSObject *self, const KJS::List &args ) +{ + Q_UNUSED(args); + KJSEmbed::ValueBinding *imp = KJSEmbed::extractBindingImp<KJSEmbed::ValueBinding>(exec, self ); + if( imp ) + { + return KJS::jsString( imp->className().ascii() ); + } + return KJS::jsNull(); +} + +const Method ValueFactory::ValueMethods[] = +{ + {"type", 0, KJS::DontDelete|KJS::ReadOnly, &callValueType }, + //{"cast", 1, KJS::DontDelete|KJS::ReadOnly, &callPointerCast }, + //{"toString", 0, KJS::DontDelete|KJS::ReadOnly, &callPointerToString }, + {0, 0, 0, 0 } +}; + +const Method *ValueFactory::methods() +{ + return ValueMethods; +} + +ValueBinding::ValueBinding( KJS::ExecState *exec, const char *typeName) + : ProxyBinding( exec ), + m_value(0), + m_name(typeName) +{ + StaticBinding::publish( exec, this, ValueFactory::methods() ); +} + +ValueBinding::~ValueBinding() +{ + delete m_value; +} + +KJS::UString ValueBinding::toString(KJS::ExecState *exec) const +{ + Q_UNUSED(exec); + return m_value->type().name(); +} + +//kate: indent-spaces on; indent-width 4; replace-tabs on; indent-mode cstyle; diff --git a/pool/shard007/C++/0091312_factorial.cpp b/pool/shard007/C++/0091312_factorial.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fc02193669c9520e896240121b88a10b10074c6a --- /dev/null +++ b/pool/shard007/C++/0091312_factorial.cpp @@ -0,0 +1,46 @@ +#include <iostream> + +using namespace std; + +// Making these return doubles allows for calculating much higher factorials +// If these return ints, then you can only do up to 12! +double factorialRecursive(int num); +double factorialReverse(int num); +double factorialIterative(int num); + +int main() { + cout << "factorialRecursive(3): " << factorialRecursive(3) << endl; + cout << "factorialRecursive(-2): " << factorialRecursive(-2) << endl; + cout << "factorialRecursive(70): " << factorialRecursive(70) << endl; + cout << "factorialReverse(3): " << factorialReverse(3) << endl; + cout << "factorialReverse(-2): " << factorialReverse(-2) << endl; + cout << "factorialReverse(70): " << factorialReverse(70) << endl; + cout << "factorialIterative(3): " << factorialIterative(3) << endl; + cout << "factorialIterative(-2): " << factorialIterative(-2) << endl; + cout << "factorialIterative(70): " << factorialIterative(70) << endl; + return 0; +} + +// Recursive example +double factorialRecursive(int num) { + if (num < 2) + return 1; + else + return num * factorialRecursive(num - 1); +} + +// Reverse reverse loop example +double factorialReverse(int num) { + double fact = 1; + while (num > 1) + fact *= num--; + return fact; +} + +// Iterative example +double factorialIterative(int num) { + double fact = 1; + for (int i = 2; i <= num; i++) + fact *= i; + return fact; +} diff --git a/pool/shard007/C++/0091315_motion_emu.cpp b/pool/shard007/C++/0091315_motion_emu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..31e11875de0e5c2da22d1257253e120e76f3e70a --- /dev/null +++ b/pool/shard007/C++/0091315_motion_emu.cpp @@ -0,0 +1,173 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include <algorithm> +#include <chrono> +#include <mutex> +#include <thread> +#include <tuple> +#include "common/math_util.h" +#include "common/quaternion.h" +#include "common/thread.h" +#include "common/vector_math.h" +#include "input_common/motion_emu.h" + +namespace InputCommon { + +// Implementation class of the motion emulation device +class MotionEmuDevice { +public: + MotionEmuDevice(int update_millisecond, float sensitivity, float tilt_clamp) + : update_millisecond(update_millisecond), + update_duration(std::chrono::duration_cast<std::chrono::steady_clock::duration>( + std::chrono::milliseconds(update_millisecond))), + sensitivity(sensitivity), tilt_clamp(tilt_clamp), + motion_emu_thread(&MotionEmuDevice::MotionEmuThread, this) {} + + ~MotionEmuDevice() { + if (motion_emu_thread.joinable()) { + shutdown_event.Set(); + motion_emu_thread.join(); + } + } + + void BeginTilt(int x, int y) { + mouse_origin = Math::MakeVec(x, y); + is_tilting = true; + } + + void Tilt(int x, int y) { + auto mouse_move = Math::MakeVec(x, y) - mouse_origin; + if (is_tilting) { + std::lock_guard<std::mutex> guard(tilt_mutex); + if (mouse_move.x == 0 && mouse_move.y == 0) { + tilt_angle = 0; + } else { + tilt_direction = mouse_move.Cast<float>(); + tilt_angle = std::clamp(tilt_direction.Normalize() * sensitivity, 0.0f, + MathUtil::PI * this->tilt_clamp / 180.0f); + } + } + } + + void EndTilt() { + std::lock_guard<std::mutex> guard(tilt_mutex); + tilt_angle = 0; + is_tilting = false; + } + + std::tuple<Math::Vec3<float>, Math::Vec3<float>> GetStatus() { + std::lock_guard<std::mutex> guard(status_mutex); + return status; + } + +private: + const int update_millisecond; + const std::chrono::steady_clock::duration update_duration; + const float sensitivity; + + Math::Vec2<int> mouse_origin; + + std::mutex tilt_mutex; + Math::Vec2<float> tilt_direction; + float tilt_angle = 0; + float tilt_clamp = 90; + + bool is_tilting = false; + + Common::Event shutdown_event; + + std::tuple<Math::Vec3<float>, Math::Vec3<float>> status; + std::mutex status_mutex; + + // Note: always keep the thread declaration at the end so that other objects are initialized + // before this! + std::thread motion_emu_thread; + + void MotionEmuThread() { + auto update_time = std::chrono::steady_clock::now(); + Math::Quaternion<float> q = MakeQuaternion(Math::Vec3<float>(), 0); + Math::Quaternion<float> old_q; + + while (!shutdown_event.WaitUntil(update_time)) { + update_time += update_duration; + old_q = q; + + { + std::lock_guard<std::mutex> guard(tilt_mutex); + + // Find the quaternion describing current 3DS tilting + q = MakeQuaternion(Math::MakeVec(-tilt_direction.y, 0.0f, tilt_direction.x), + tilt_angle); + } + + auto inv_q = q.Inverse(); + + // Set the gravity vector in world space + auto gravity = Math::MakeVec(0.0f, -1.0f, 0.0f); + + // Find the angular rate vector in world space + auto angular_rate = ((q - old_q) * inv_q).xyz * 2; + angular_rate *= 1000 / update_millisecond / MathUtil::PI * 180; + + // Transform the two vectors from world space to 3DS space + gravity = QuaternionRotate(inv_q, gravity); + angular_rate = QuaternionRotate(inv_q, angular_rate); + + // Update the sensor state + { + std::lock_guard<std::mutex> guard(status_mutex); + status = std::make_tuple(gravity, angular_rate); + } + } + } +}; + +// Interface wrapper held by input receiver as a unique_ptr. It holds the implementation class as +// a shared_ptr, which is also observed by the factory class as a weak_ptr. In this way the factory +// can forward all the inputs to the implementation only when it is valid. +class MotionEmuDeviceWrapper : public Input::MotionDevice { +public: + MotionEmuDeviceWrapper(int update_millisecond, float sensitivity, float tilt_clamp) { + device = std::make_shared<MotionEmuDevice>(update_millisecond, sensitivity, tilt_clamp); + } + + std::tuple<Math::Vec3<float>, Math::Vec3<float>> GetStatus() const override { + return device->GetStatus(); + } + + std::shared_ptr<MotionEmuDevice> device; +}; + +std::unique_ptr<Input::MotionDevice> MotionEmu::Create(const Common::ParamPackage& params) { + int update_period = params.Get("update_period", 100); + float sensitivity = params.Get("sensitivity", 0.01f); + float tilt_clamp = params.Get("tilt_clamp", 90.0f); + auto device_wrapper = + std::make_unique<MotionEmuDeviceWrapper>(update_period, sensitivity, tilt_clamp); + // Previously created device is disconnected here. Having two motion devices for 3DS is not + // expected. + current_device = device_wrapper->device; + return std::move(device_wrapper); +} + +void MotionEmu::BeginTilt(int x, int y) { + if (auto ptr = current_device.lock()) { + ptr->BeginTilt(x, y); + } +} + +void MotionEmu::Tilt(int x, int y) { + if (auto ptr = current_device.lock()) { + ptr->Tilt(x, y); + } +} + +void MotionEmu::EndTilt() { + if (auto ptr = current_device.lock()) { + ptr->EndTilt(); + } +} + +} // namespace InputCommon diff --git a/pool/shard007/C++/0091316_testApp.cpp b/pool/shard007/C++/0091316_testApp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ef2de38bcafac971369c697275452c66c16701e1 --- /dev/null +++ b/pool/shard007/C++/0091316_testApp.cpp @@ -0,0 +1,92 @@ +#include "testApp.h" + +//-------------------------------------------------------------- +void testApp::setup() +{ + //ofSetLogLevel(OF_LOG_VERBOSE); + +// string videoPath = ofToDataPath("../../../video/Timecoded_Big_bunny_1.mov", true); + string videoPath = ofToDataPath("../../../video/PEEK.mov", true); + + //Somewhat like ofFboSettings we may have a lot of options so this is the current model + ofxOMXPlayerSettings settings; + settings.videoPath = videoPath; + settings.useHDMIForAudio = false; //default true + settings.enableTexture = true; //default true + settings.enableLooping = true; //default true + settings.enableAudio = true; //default true, save resources by disabling + settings.doFlipTexture = true; //default false + + + //so either pass in the settings + omxPlayer.setup(settings); + + // listen on the given port + cout << "listening for osc messages on port " << PORT << "\n"; + receiver.setup(PORT); + + ofHideCursor(); + //ofSetVerticalSync(true); //just trying framerate + //ofSetFrameRate(60); +} + +//-------------------------------------------------------------- +void testApp::update() +{ + // check for waiting messages + while(receiver.hasWaitingMessages()){ + // get the next message + ofxOscMessage m; + receiver.getNextMessage(&m); + omxPlayer.restartMovie(); + } +} + + +//-------------------------------------------------------------- +void testApp::draw(){ + if(!omxPlayer.isTextureEnabled) + { + return; + } + + omxPlayer.draw(0, 0, ofGetWidth(), ofGetHeight()); +} + +//-------------------------------------------------------------- +void testApp::keyPressed(int key){ +} + +//-------------------------------------------------------------- +void testApp::keyReleased(int key){ + +} + +//-------------------------------------------------------------- +void testApp::mouseMoved(int x, int y){ +} + +//-------------------------------------------------------------- +void testApp::mouseDragged(int x, int y, int button){ + +} + +//-------------------------------------------------------------- +void testApp::mousePressed(int x, int y, int button){ +} + +//-------------------------------------------------------------- +void testApp::mouseReleased(int x, int y, int button){ +} + +//-------------------------------------------------------------- +void testApp::windowResized(int w, int h){ +} + +//-------------------------------------------------------------- +void testApp::gotMessage(ofMessage msg){ +} + +//-------------------------------------------------------------- +void testApp::dragEvent(ofDragInfo dragInfo){ +} diff --git a/pool/shard007/C++/0091317_ibex_SystemFactory.cpp b/pool/shard007/C++/0091317_ibex_SystemFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..66bc3e2e96d6f479b4d6b0fd221eddc9b9b2df17 --- /dev/null +++ b/pool/shard007/C++/0091317_ibex_SystemFactory.cpp @@ -0,0 +1,207 @@ +//============================================================================ +// I B E X +// File : ibex_SystemFactory.cpp +// Author : Gilles Chabert +// Copyright : Ecole des Mines de Nantes (France) +// License : See the LICENSE file +// Created : Aug 27, 2012 +// Last Update : May 26, 2013 +//============================================================================ + +#include "ibex_SystemFactory.h" +#include "ibex_Exception.h" +#include "ibex_ExprCtr.h" +#include "ibex_ExprCopy.h" +#include "ibex_EmptySystemException.h" + +using std::vector; + +namespace ibex { + +SystemFactory::SystemFactory() : nb_arg(0), nb_var(0), goal(NULL), args(NULL) { } + + +SystemFactory::~SystemFactory() { + if (args) delete args; +} + +void SystemFactory::add_var(const ExprSymbol& v) { + if (goal || !ctrs.empty()) ibex_error("cannot add a variable to a system after a constraint (or the goal function)"); + + tmp_args.push_back(&v); + nb_arg++; + nb_var+= v.dim.size(); +} + +void SystemFactory::add_var(const Array<const ExprSymbol>& a) { + if (goal || !ctrs.empty()) ibex_error("cannot add a variable to a system after a constraint (or the goal function)"); + + for (int i=0; i<a.size(); i++) { + tmp_args.push_back(&a[i]); + nb_arg++; + nb_var+= a[i].dim.size(); + } +} + +void SystemFactory::add_goal(const ExprNode& goal) { + if (!args) args = new Array<const ExprSymbol>(tmp_args); + + Array<const ExprSymbol> goal_vars(args->size()); + varcopy(*args,goal_vars); + const ExprNode& goal_expr=ExprCopy().copy(*args, goal_vars, goal); //, true); + this->goal = new Function(goal_vars, goal_expr); +} + +void SystemFactory::add_goal(const Function& goal) { + if (!args) args = new Array<const ExprSymbol>(tmp_args); + + // check that the arguments of the goal + // matches the arguments entered + assert(varequals(goal.args(), *args)); + + this->goal = new Function(goal); +} + +void SystemFactory::add_ctr(const ExprCtr& ctr) { + if (!args) args = new Array<const ExprSymbol>(tmp_args); + + Array<const ExprSymbol> ctr_vars(args->size()); + varcopy(*args,ctr_vars); + const ExprNode& ctr_expr=ExprCopy().copy(*args, ctr_vars, ctr.e); //, true); + + ctrs.push_back(new NumConstraint(*new Function(ctr_vars, ctr_expr), ctr.op, true)); +} + +void SystemFactory::add_ctr2(const ExprCtr& ctr) { + if (!args) args = new Array<const ExprSymbol>(tmp_args); + + Array<const ExprSymbol> ctr_vars(args->size()); + varcopy(*args,ctr_vars); + const ExprNode& ctr_expr=ExprCopy().copy(*args, ctr_vars, ctr.e); //, true); + + ctrs.push_back(new NumConstraint(*new Function(ctr_vars, ctr_expr), ctr.op, true)); +} + +void SystemFactory::add_ctr(const NumConstraint& ctr) { + if (!args) args = new Array<const ExprSymbol>(tmp_args); + + // check that the arguments of the constraint + // matches the arguments entered + assert(varequals(ctr.f.args(),*args)); + + ctrs.push_back(new NumConstraint(*new Function(ctr.f), ctr.op, true)); +} + +// precondition: nb_ctr > 0 +void System::init_f_from_ctrs() { + + if (ctrs.is_empty()) return; // <=> m>0 + + int total_output_size=0; + for (int j=0; j<ctrs.size(); j++) + total_output_size += ctrs[j].f.image_dim(); + + Array<const ExprNode> image(total_output_size); + int i=0; + + // concatenate all the components of all the constraints function + for (int j=0; j<ctrs.size(); j++) { + Function& fj=ctrs[j].f; + + /*========= 1st variant =============== + * will have the disadvantage that the DAG structure + * of a vector constraint may be lost, e.g., a 2D constraint x+y=0 + * will result in two components (x+y)[0] and (x+y)[1] where (x+y) + * is for each a separate subnode. + */ +// for (int k=0; k<fj.image_dim(); k++) { +// const ExprNode& e=ExprCopy().copy(fj[k].args(), args, fj[k].expr()); +// image.set_ref(i++,e); +// } + /*======================================================================*/ + + + /*========= 2nd variant ===============*/ + /* copy the DAG directly of the jth constraint and create + * indexed expression after. + * + * TODO: Disadvantage : a vector constraint like + * (x[0],x[1])=(0,1) + * will be transformed into + * (x[0],x[1])[0]=(0,1)[0] and (x[0],x[1])[1]=(0,1)[1] + * instead of + * x[0]=0 and x[1]=1. + */ + const ExprNode& e=ExprCopy().copy(fj.args(), args, fj.expr()); + + const Dim& fjd=fj.expr().dim; + switch (fjd.type()) { + case Dim::SCALAR : + image.set_ref(i++,e); + break; + case Dim::ROW_VECTOR: + case Dim::COL_VECTOR: + for (int k=0; k<fjd.vec_size(); k++) + image.set_ref(i++,e[k]); + break; + case Dim::MATRIX: + for (int k=0; k<fjd.nb_rows(); k++) + for (int l=0; l<fjd.nb_cols(); l++) + image.set_ref(i++,e[k][l]); + break; + default: + assert(false); + break; + } + /*======================================================================*/ + + } + assert(i==total_output_size); + + // TODO: we should probably homgenize; in the case of a scalar function + // a 1-sized vector should be created. + f.init(args, total_output_size>1? ExprVector::new_(image,false) : image[0]); +} + + +System::System(const SystemFactory& fac) : nb_var(0), nb_ctr(0), box(1) { + init(fac); +} + +void System::init(const SystemFactory& fac) { + + // the field fac.args is initialized upon addition of an objective + // function or a constraint. + if (!fac.args) throw EmptySystemException(); + + (int&) nb_var = fac.nb_var; + (int&) nb_ctr = fac.ctrs.size(); + + // =========== init goal ============== + goal = fac.goal; + + // f is not initialized here --> see init_f_from_ctrs() below + + // =========== init args ============== + args.resize(fac.nb_arg); + varcopy(*fac.args, args); + + box.resize(nb_var); + + // =========== init ctrs ============== + ctrs.resize(nb_ctr); + for (int i=0; i<nb_ctr; i++) + ctrs.set_ref(i,*(fac.ctrs[i])); + + // =========== init main function + // we cannot generate first the global function f and + // then each constraint with (f[i] op 0) because + // a constraint can be vector or matrix valued. + // so we do the contrary: we generate first the constraints, + // and build f with the components of all constraints' functions. + + init_f_from_ctrs(); +} + +} // end namespace + diff --git a/pool/shard007/C++/0091319_proxy_resolver_winhttp.cc b/pool/shard007/C++/0091319_proxy_resolver_winhttp.cc new file mode 100644 index 0000000000000000000000000000000000000000..1e14fbb51bf1252c33c385c2a0e10d9e0104e75b --- /dev/null +++ b/pool/shard007/C++/0091319_proxy_resolver_winhttp.cc @@ -0,0 +1,178 @@ +// Copyright (c) 2011 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 "net/proxy/proxy_resolver_winhttp.h" + +#include <windows.h> +#include <winhttp.h> + +#include "base/metrics/histogram.h" +#include "base/string_util.h" +#include "base/utf_string_conversions.h" +#include "googleurl/src/gurl.h" +#include "net/base/net_errors.h" +#include "net/proxy/proxy_info.h" + +#pragma comment(lib, "winhttp.lib") + +using base::TimeDelta; +using base::TimeTicks; + +namespace net { + +static void FreeInfo(WINHTTP_PROXY_INFO* info) { + if (info->lpszProxy) + GlobalFree(info->lpszProxy); + if (info->lpszProxyBypass) + GlobalFree(info->lpszProxyBypass); +} + +ProxyResolverWinHttp::ProxyResolverWinHttp() + : ProxyResolver(false /*expects_pac_bytes*/), session_handle_(NULL) { +} + +ProxyResolverWinHttp::~ProxyResolverWinHttp() { + CloseWinHttpSession(); +} + +int ProxyResolverWinHttp::GetProxyForURL(const GURL& query_url, + ProxyInfo* results, + const CompletionCallback& /*callback*/, + RequestHandle* /*request*/, + const BoundNetLog& /*net_log*/) { + // If we don't have a WinHTTP session, then create a new one. + if (!session_handle_ && !OpenWinHttpSession()) + return ERR_FAILED; + + // If we have been given an empty PAC url, then use auto-detection. + // + // NOTE: We just use DNS-based auto-detection here like Firefox. We do this + // to avoid WinHTTP's auto-detection code, which while more featureful (it + // supports DHCP based auto-detection) also appears to have issues. + // + WINHTTP_AUTOPROXY_OPTIONS options = {0}; + options.fAutoLogonIfChallenged = FALSE; + options.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL; + std::wstring pac_url_wide = ASCIIToWide(pac_url_.spec()); + options.lpszAutoConfigUrl = pac_url_wide.c_str(); + + WINHTTP_PROXY_INFO info = {0}; + DCHECK(session_handle_); + + // Per http://msdn.microsoft.com/en-us/library/aa383153(VS.85).aspx, it is + // necessary to first try resolving with fAutoLogonIfChallenged set to false. + // Otherwise, we fail over to trying it with a value of true. This way we + // get good performance in the case where WinHTTP uses an out-of-process + // resolver. This is important for Vista and Win2k3. + BOOL ok = WinHttpGetProxyForUrl( + session_handle_, ASCIIToWide(query_url.spec()).c_str(), &options, &info); + if (!ok) { + if (ERROR_WINHTTP_LOGIN_FAILURE == GetLastError()) { + options.fAutoLogonIfChallenged = TRUE; + ok = WinHttpGetProxyForUrl( + session_handle_, ASCIIToWide(query_url.spec()).c_str(), + &options, &info); + } + if (!ok) { + DWORD error = GetLastError(); + // If we got here because of RPC timeout during out of process PAC + // resolution, no further requests on this session are going to work. + if (ERROR_WINHTTP_TIMEOUT == error || + ERROR_WINHTTP_AUTO_PROXY_SERVICE_ERROR == error) { + CloseWinHttpSession(); + } + return ERR_FAILED; // TODO(darin): Bug 1189288: translate error code. + } + } + + int rv = OK; + + switch (info.dwAccessType) { + case WINHTTP_ACCESS_TYPE_NO_PROXY: + results->UseDirect(); + break; + case WINHTTP_ACCESS_TYPE_NAMED_PROXY: + // According to MSDN: + // + // The proxy server list contains one or more of the following strings + // separated by semicolons or whitespace. + // + // ([<scheme>=][<scheme>"://"]<server>[":"<port>]) + // + // Based on this description, ProxyInfo::UseNamedProxy() isn't + // going to handle all the variations (in particular <scheme>=). + // + // However in practice, it seems that WinHTTP is simply returning + // things like "foopy1:80;foopy2:80". It strips out the non-HTTP + // proxy types, and stops the list when PAC encounters a "DIRECT". + // So UseNamedProxy() should work OK. + results->UseNamedProxy(WideToASCII(info.lpszProxy)); + break; + default: + NOTREACHED(); + rv = ERR_FAILED; + } + + FreeInfo(&info); + return rv; +} + +void ProxyResolverWinHttp::CancelRequest(RequestHandle request) { + // This is a synchronous ProxyResolver; no possibility for async requests. + NOTREACHED(); +} + +LoadState ProxyResolverWinHttp::GetLoadState(RequestHandle request) const { + NOTREACHED(); + return LOAD_STATE_IDLE; +} + +LoadState ProxyResolverWinHttp::GetLoadStateThreadSafe( + RequestHandle request) const { + return LOAD_STATE_IDLE; +} + +void ProxyResolverWinHttp::CancelSetPacScript() { + NOTREACHED(); +} + +int ProxyResolverWinHttp::SetPacScript( + const scoped_refptr<ProxyResolverScriptData>& script_data, + const CompletionCallback& /*callback*/) { + if (script_data->type() == ProxyResolverScriptData::TYPE_AUTO_DETECT) { + pac_url_ = GURL("http://wpad/wpad.dat"); + } else { + pac_url_ = script_data->url(); + } + return OK; +} + +bool ProxyResolverWinHttp::OpenWinHttpSession() { + DCHECK(!session_handle_); + session_handle_ = WinHttpOpen(NULL, + WINHTTP_ACCESS_TYPE_NO_PROXY, + WINHTTP_NO_PROXY_NAME, + WINHTTP_NO_PROXY_BYPASS, + 0); + if (!session_handle_) + return false; + + // Since this session handle will never be used for WinHTTP connections, + // these timeouts don't really mean much individually. However, WinHTTP's + // out of process PAC resolution will use a combined (sum of all timeouts) + // value to wait for an RPC reply. + BOOL rv = WinHttpSetTimeouts(session_handle_, 10000, 10000, 5000, 5000); + DCHECK(rv); + + return true; +} + +void ProxyResolverWinHttp::CloseWinHttpSession() { + if (session_handle_) { + WinHttpCloseHandle(session_handle_); + session_handle_ = NULL; + } +} + +} // namespace net diff --git a/pool/shard007/C++/0091322_UserControl.cpp b/pool/shard007/C++/0091322_UserControl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4f74819d868b09c78e1fedef8b012df28d455c1b --- /dev/null +++ b/pool/shard007/C++/0091322_UserControl.cpp @@ -0,0 +1,220 @@ +#include "stdafx.h" +#include "UserControl.h" + +namespace PrettyFramework { + + UserControl::UserControl(LayoutControl* parent) + : BaseControl(parent) + , m_state(State::Normal) + { + } + + UserControl::~UserControl() + { + } + + void UserControl::Paint0(Gdiplus::Graphics& graph) + { + OnPaint(graph); /* »æÖÆ×ÔÉíͼ²ã */ + + if (m_layout != nullptr) { + + Gdiplus::Region rgnOldClip; + graph.GetClip(&rgnOldClip); + + Rect rcClip = GetViewRect(); + rcClip.DeflateRect(m_margin); + + auto& F = toGdiplusRect(rcClip); + Gdiplus::Region rgnClip(F); + + { /* »æÖÆ×ӿؼþ */ + + Rect rect = m_layout->GetViewRect(); + auto& F2 = toGdiplusRect(rect); + + Gdiplus::Region rgnControl(F2); + + rgnControl.Intersect(&rgnClip); + graph.SetClip(&rgnControl); + + m_layout->Paint(graph); + } + + graph.SetClip(&rgnOldClip); + } + } + + void UserControl::SetDisable(BOOL disable) + { + if (disable) { + m_state = State::Disable; + } else { + m_state &= ~State::Disable; + } + } + + void UserControl::SetPressed(BOOL pressed) + { + if (pressed) { + m_state |= State::Pressed; + } else { + m_state &= ~State::Pressed; + } + } + + void UserControl::SetFocused(BOOL focused) + { + if (focused) { + m_state |= State::Focused; + } else { + m_state &= ~State::Focused; + } + } + + void UserControl::SetHovered(BOOL hovered) + { + if (hovered) { + m_state |= State::Hovered; + } else { + m_state &= ~State::Hovered; + } + } + + void UserControl::OnMouseUp(Point point) + { + if (IsDisable()) { + return; + } + + BOOL bHitted = HitTest(point); + SetPressed(FALSE); + SetFocused(bHitted); + + EventParam param; + param.point = point; + param.control = this; + param.will_eat_it = FALSE; + + if (bHitted) { + OnPreviewMouseUp(param); + if (param.will_eat_it) { + return; /* ³ÔµôËü */ + } + } + + if (m_layout != nullptr) { + m_layout->OnMouseUp(point); + } else { + Redraw(); + } + + if (bHitted) { + OnMouseUp(param); + } + } + + void UserControl::OnMouseMove(Point point) + { + if (IsDisable()) { + return; + } + + BOOL hover_changed = FALSE; + + BOOL is_hovered = HitTest(point); + if (is_hovered != IsHovered()) { + hover_changed = TRUE; + } + + SetHovered(is_hovered); + + EventParam param; + param.point = point; + param.control = this; + param.will_eat_it = FALSE; + + if (is_hovered) { + OnPreviewMouseMove(param); + if (param.will_eat_it) { + return; /* ³ÔµôËü */ + } + } + + if (m_layout != nullptr) { + m_layout->OnMouseMove(point); + } else { + if (hover_changed) { + Redraw(); + } + } + + if (is_hovered) { + OnMouseMove(param); + } + } + + void UserControl::OnMouseDown(Point point) + { + if (IsDisable()) { + return; + } + + BOOL ptHitted = HitTest(point); + SetFocused(ptHitted); + SetPressed(ptHitted); + + EventParam param; + param.point = point; + param.control = this; + param.will_eat_it = FALSE; + + if (ptHitted) { + OnPreviewMouseDown(param); + if (param.will_eat_it) { + return; /* ³ÔµôËü */ + } + } + + if (m_layout != nullptr) { + m_layout->OnMouseDown(point); + } else { + Redraw(); + } + + if (ptHitted) { + OnMouseDown(param); + } + } + + void UserControl::RecalcLayout() + { + if (m_layout != nullptr) { + Rect rcClient(GetRect()); + rcClient.MoveTo(0.0f, 0.0f); + m_layout->SetRect(rcClient); + } + } + + BaseControl* UserControl::FindControlById(CString id) + { + if (m_id == id) { return this; } + + if (m_layout != nullptr) { + return m_layout->FindControlById(id); + } + + return nullptr; + } + + void UserControl::Dump() + { + TRACE(_T("UserControl:%s Rect:%d,%d,%d,%d \n"), GetId(), GetRect().GetLeft() + , GetRect().GetTop(), GetRect().GetRight(), GetRect().GetBottom()); + + if (m_layout != nullptr) { + return m_layout->Dump(); + } + } + +} \ No newline at end of file diff --git a/pool/shard007/C++/0091324_hid.cpp b/pool/shard007/C++/0091324_hid.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f6eb6ca87f9ec6e54e3b284e007614c4bdb9456f --- /dev/null +++ b/pool/shard007/C++/0091324_hid.cpp @@ -0,0 +1,126 @@ +#include "citrus/hid.hpp" +#include "internal.hpp" + +#include <unordered_map> + +#include <3ds.h> + +namespace ctr { + namespace hid { + static std::unordered_map<u32, const std::string> buttonNames = { + {BUTTON_NONE, "None"}, + {BUTTON_A, "A"}, + {BUTTON_B, "B"}, + {BUTTON_SELECT, "Select"}, + {BUTTON_START, "Start"}, + {BUTTON_DRIGHT, "D-Pad Right"}, + {BUTTON_DLEFT, "D-Pad Left"}, + {BUTTON_DUP, "D-Pad Up"}, + {BUTTON_DDOWN, "D-Pad Down"}, + {BUTTON_R, "R"}, + {BUTTON_L, "L"}, + {BUTTON_X, "X"}, + {BUTTON_Y, "Y"}, + {BUTTON_ZL, "ZL"}, + {BUTTON_ZR, "ZR"}, + {BUTTON_TOUCH, "Touch"}, + {BUTTON_CSTICK_RIGHT, "C-Stick Right"}, + {BUTTON_CSTICK_LEFT, "C-Stick Left"}, + {BUTTON_CSTICK_UP, "C-Stick Up"}, + {BUTTON_CSTICK_DOWN, "C-Stick Down"}, + {BUTTON_CPAD_RIGHT, "Circle-Pad Right"}, + {BUTTON_CPAD_LEFT, "Circle-Pad Left"}, + {BUTTON_CPAD_UP, "Circle-Pad Up"}, + {BUTTON_CPAD_DOWN, "Circle-Pad Down"}, + {BUTTON_UP, "Up"}, + {BUTTON_DOWN, "Down"}, + {BUTTON_LEFT, "Left"}, + {BUTTON_RIGHT, "Right"} + }; + } +} + +bool ctr::hid::init() { + return true; +} + +void ctr::hid::exit() { +} + +void ctr::hid::poll() { + hidScanInput(); +} + +ctr::hid::Button ctr::hid::anyPressed() { + for(u32 i = 0; i < 32; i++) { + Button button = (ctr::hid::Button) (1 << i); + if(pressed(button)) { + return button; + } + } + + return BUTTON_NONE; +} + +bool ctr::hid::released(ctr::hid::Button button) { + return (hidKeysUp() & button) != 0; +} + +bool ctr::hid::pressed(ctr::hid::Button button) { + return (hidKeysDown() & button) != 0; +} + +bool ctr::hid::held(ctr::hid::Button button) { + return (hidKeysHeld() & button) != 0; +} + +ctr::hid::Touch ctr::hid::touch() { + touchPosition pos; + hidTouchRead(&pos); + return {pos.px, pos.py}; +} + +ctr::hid::Analog ctr::hid::circlePad() { + circlePosition pos; + hidCircleRead(&pos); + return {pos.dx, pos.dy}; +} + +ctr::hid::Analog ctr::hid::cStick() { + circlePosition pos; + irrstCstickRead(&pos); + return {pos.dx, pos.dy}; +} + +void enableAccelerometer() { + ctr::err::parse(ctr::err::SOURCE_HID_ENABLE_ACCELEROMETER, (u32) HIDUSER_EnableAccelerometer()); +} + +void disableAccelerometer() { + ctr::err::parse(ctr::err::SOURCE_HID_DISABLE_ACCELEROMETER, (u32) HIDUSER_DisableAccelerometer()); +} + +ctr::hid::Axis ctr::hid::accelerometer() { + accelVector vec; + hidAccelRead(&vec); + return {vec.x, vec.y, vec.z}; +} + +void enableGyroscope() { + ctr::err::parse(ctr::err::SOURCE_HID_ENABLE_GYROSCOPE, (u32) HIDUSER_EnableGyroscope()); +} + +void disableGyroscope() { + ctr::err::parse(ctr::err::SOURCE_HID_DISABLE_GYROSCOPE, (u32) HIDUSER_DisableGyroscope()); +} + +ctr::hid::Axis ctr::hid::gyroscope() { + angularRate rate; + hidGyroRead(&rate); + return {rate.x, rate.y, rate.z}; +} + +const std::string ctr::hid::buttonName(ctr::hid::Button button) { + std::unordered_map<u32, const std::string>::iterator result = buttonNames.find(button); + return result != buttonNames.end() ? result->second : "<unknown>"; +} \ No newline at end of file diff --git a/pool/shard007/C++/0091329_TaskTest.cpp b/pool/shard007/C++/0091329_TaskTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..df6448e55f5d8c0612a6f1a576e003f22ddbb761 --- /dev/null +++ b/pool/shard007/C++/0091329_TaskTest.cpp @@ -0,0 +1,86 @@ +/* +----------------------------------------------------------------------------- +This source file is part of fastbird engine +For the latest info, see http://www.jungwan.net/ + +Copyright (c) 2013-2015 Jungwan Byun + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +----------------------------------------------------------------------------- +*/ + +#include "stdafx.h" +#include "TaskTest.h" +#include "FBThread/TaskScheduler.h" +#include "FBThread/Task.h" +using namespace fb; + +std::atomic<size_t> gNumExecuted = 0; +class MyTask : public Task { +public: + MyTask(ThreadSafeCounter* _ExecCounter = nullptr) + : Task(false, _ExecCounter) + { + if (mExecCounter) { + _ExecCounter->operator++(); + } + } + void Execute(TaskScheduler* Scheduler) OVERRIDE { + if (!mExecCounter) { + // 5 children tasks + for (int i = 0; i < 5; ++i) { + auto t = std::make_shared<MyTask>(&mSyncCounter); + Scheduler->AddTask(t); + } + } + double v = 1; + for (int i = 1; i < 10000; ++i) { + v += Random(-1.f, 1.f); + } + Logger::Log(FB_DEFAULT_LOG_ARG, FormatString("[%u]V= %f; num executed = %u", std::this_thread::get_id(), v, ++gNumExecuted).c_str()); + } +}; +class TaskTest::Impl { +public: + + + Impl() { + for (int i = 0; i < 5000; ++i) { + auto t = std::make_shared<MyTask>(); + TaskScheduler::GetInstance().AddTask(t); + } + } + + ~Impl() { + + } + +}; + +//--------------------------------------------------------------------------- +FB_IMPLEMENT_STATIC_CREATE(TaskTest); +TaskTest::TaskTest() + : mImpl(new Impl) +{ + +} + +TaskTest::~TaskTest() { + +} \ No newline at end of file diff --git a/pool/shard007/C++/0091331_qgscheckboxfieldformatter.cpp b/pool/shard007/C++/0091331_qgscheckboxfieldformatter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9179212c50a3b913b0dff07edf2dc0934eec46d0 --- /dev/null +++ b/pool/shard007/C++/0091331_qgscheckboxfieldformatter.cpp @@ -0,0 +1,89 @@ +/*************************************************************************** + qgscheckboxfieldformatter.cpp - QgsCheckBoxFieldFormatter + + --------------------- + begin : 23.09.2019 + copyright : (C) 2019 by Denis Rouzaud + email : denis@opengis.ch + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include <QObject> + +#include "qgscheckboxfieldformatter.h" +#include "qgsvectorlayer.h" +#include "qgsapplication.h" + + +QString QgsCheckBoxFieldFormatter::id() const +{ + return QStringLiteral( "CheckBox" ); +} + +QString QgsCheckBoxFieldFormatter::representValue( QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config, const QVariant &cache, const QVariant &value ) const +{ + Q_UNUSED( cache ) + + /* + This follows this logic: + + if field type is bool: + NULL => nullRepresentation + true => tr("true") + false => tr("false") + else + if cannot convert to string (like json integer list) => (invalid) + if == checkedstate => tr("true") + if == uncheckedstate => tr("false") + else (value.toString) + */ + + bool isNull = value.isNull(); + bool boolValue = false; + QString textValue = QgsApplication::nullRepresentation(); + + const QVariant::Type fieldType = layer->fields().at( fieldIndex ).type(); + if ( fieldType == QVariant::Bool ) + { + boolValue = value.toBool(); + } + else + { + if ( !value.canConvert<QString>() ) + { + isNull = true; + textValue = QObject::tr( "(invalid)" ); + } + else + { + if ( config.contains( QStringLiteral( "CheckedState" ) ) && value.toString() == config[ QStringLiteral( "CheckedState" ) ].toString() ) + { + boolValue = true; + } + else if ( config.contains( QStringLiteral( "UncheckedState" ) ) && value.toString() == config[ QStringLiteral( "UncheckedState" ) ].toString() ) + { + boolValue = false; + } + else + { + isNull = true; + textValue = QStringLiteral( "(%1)" ).arg( value.toString() ); + } + } + } + + if ( isNull ) + { + return textValue; + } + if ( boolValue ) + return QObject::tr( "true" ); + else + return QObject::tr( "false" ); +} diff --git a/pool/shard007/C++/0091340_SVGComponentTransferFunctionElement.cpp b/pool/shard007/C++/0091340_SVGComponentTransferFunctionElement.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f61b2ea0d23a6347c17c8d31e665727626680cd0 --- /dev/null +++ b/pool/shard007/C++/0091340_SVGComponentTransferFunctionElement.cpp @@ -0,0 +1,129 @@ +/* + Copyright (C) 2004, 2005, 2007 Nikolas Zimmermann <zimmermann@kde.org> + 2004, 2005, 2006 Rob Buis <buis@kde.org> + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "config.h" + +#if ENABLE(SVG) && ENABLE(FILTERS) +#include "SVGComponentTransferFunctionElement.h" + +#include "MappedAttribute.h" +#include "SVGFEComponentTransferElement.h" +#include "SVGNames.h" +#include "SVGNumberList.h" + +namespace WebCore { + +SVGComponentTransferFunctionElement::SVGComponentTransferFunctionElement(const QualifiedName& tagName, Document* doc) + : SVGElement(tagName, doc) + , m_type(FECOMPONENTTRANSFER_TYPE_UNKNOWN) + , m_tableValues(SVGNumberList::create(SVGNames::tableValuesAttr)) + , m_slope(1.0f) + , m_amplitude(1.0f) + , m_exponent(1.0f) +{ +} + +SVGComponentTransferFunctionElement::~SVGComponentTransferFunctionElement() +{ +} + +void SVGComponentTransferFunctionElement::parseMappedAttribute(MappedAttribute* attr) +{ + const String& value = attr->value(); + if (attr->name() == SVGNames::typeAttr) { + if (value == "identity") + setTypeBaseValue(FECOMPONENTTRANSFER_TYPE_IDENTITY); + else if (value == "table") + setTypeBaseValue(FECOMPONENTTRANSFER_TYPE_TABLE); + else if (value == "discrete") + setTypeBaseValue(FECOMPONENTTRANSFER_TYPE_DISCRETE); + else if (value == "linear") + setTypeBaseValue(FECOMPONENTTRANSFER_TYPE_LINEAR); + else if (value == "gamma") + setTypeBaseValue(FECOMPONENTTRANSFER_TYPE_GAMMA); + } + else if (attr->name() == SVGNames::tableValuesAttr) + tableValuesBaseValue()->parse(value); + else if (attr->name() == SVGNames::slopeAttr) + setSlopeBaseValue(value.toFloat()); + else if (attr->name() == SVGNames::interceptAttr) + setInterceptBaseValue(value.toFloat()); + else if (attr->name() == SVGNames::amplitudeAttr) + setAmplitudeBaseValue(value.toFloat()); + else if (attr->name() == SVGNames::exponentAttr) + setExponentBaseValue(value.toFloat()); + else if (attr->name() == SVGNames::offsetAttr) + setOffsetBaseValue(value.toFloat()); + else + SVGElement::parseMappedAttribute(attr); +} + +void SVGComponentTransferFunctionElement::synchronizeProperty(const QualifiedName& attrName) +{ + SVGElement::synchronizeProperty(attrName); + + if (attrName == anyQName()) { + synchronizeType(); + synchronizeTableValues(); + synchronizeSlope(); + synchronizeIntercept(); + synchronizeAmplitude(); + synchronizeExponent(); + synchronizeOffset(); + return; + } + + if (attrName == SVGNames::typeAttr) + synchronizeType(); + else if (attrName == SVGNames::tableValuesAttr) + synchronizeTableValues(); + else if (attrName == SVGNames::slopeAttr) + synchronizeSlope(); + else if (attrName == SVGNames::interceptAttr) + synchronizeIntercept(); + else if (attrName == SVGNames::amplitudeAttr) + synchronizeAmplitude(); + else if (attrName == SVGNames::exponentAttr) + synchronizeExponent(); + else if (attrName == SVGNames::offsetAttr) + synchronizeOffset(); +} + +ComponentTransferFunction SVGComponentTransferFunctionElement::transferFunction() const +{ + ComponentTransferFunction func; + func.type = (ComponentTransferType) type(); + func.slope = slope(); + func.intercept = intercept(); + func.amplitude = amplitude(); + func.exponent = exponent(); + func.offset = offset(); + SVGNumberList* numbers = tableValues(); + + ExceptionCode ec = 0; + unsigned int nr = numbers->numberOfItems(); + for (unsigned int i = 0; i < nr; i++) + func.tableValues.append(numbers->getItem(i, ec)); + return func; +} + +} + +#endif // ENABLE(SVG) diff --git a/pool/shard007/C++/0091344_cachetable-prefetch-close-test.cc b/pool/shard007/C++/0091344_cachetable-prefetch-close-test.cc new file mode 100644 index 0000000000000000000000000000000000000000..e8d08c86aa1171f2102971eaafa1f3d0a967247e --- /dev/null +++ b/pool/shard007/C++/0091344_cachetable-prefetch-close-test.cc @@ -0,0 +1,195 @@ +/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ +// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: + +// verify that closing the cachetable with prefetches in progress works +#ident "$Id$" +/* +COPYING CONDITIONS NOTICE: + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation, and provided that the + following conditions are met: + + * Redistributions of source code must retain this COPYING + CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the + DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the + PATENT MARKING NOTICE (below), and the PATENT RIGHTS + GRANT (below). + + * Redistributions in binary form must reproduce this COPYING + CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the + DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the + PATENT MARKING NOTICE (below), and the PATENT RIGHTS + GRANT (below) in the documentation and/or other materials + provided with the distribution. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301, USA. + +COPYRIGHT NOTICE: + + TokuFT, Tokutek Fractal Tree Indexing Library. + Copyright (C) 2007-2013 Tokutek, Inc. + +DISCLAIMER: + + This program is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + +UNIVERSITY PATENT NOTICE: + + The technology is licensed by the Massachusetts Institute of + Technology, Rutgers State University of New Jersey, and the Research + Foundation of State University of New York at Stony Brook under + United States of America Serial No. 11/760379 and to the patents + and/or patent applications resulting from it. + +PATENT MARKING NOTICE: + + This software is covered by US Patent No. 8,185,551. + This software is covered by US Patent No. 8,489,638. + +PATENT RIGHTS GRANT: + + "THIS IMPLEMENTATION" means the copyrightable works distributed by + Tokutek as part of the Fractal Tree project. + + "PATENT CLAIMS" means the claims of patents that are owned or + licensable by Tokutek, both currently or in the future; and that in + the absence of this license would be infringed by THIS + IMPLEMENTATION or by using or running THIS IMPLEMENTATION. + + "PATENT CHALLENGE" shall mean a challenge to the validity, + patentability, enforceability and/or non-infringement of any of the + PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS. + + Tokutek hereby grants to you, for the term and geographical scope of + the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free, + irrevocable (except as stated in this section) patent license to + make, have made, use, offer to sell, sell, import, transfer, and + otherwise run, modify, and propagate the contents of THIS + IMPLEMENTATION, where such license applies only to the PATENT + CLAIMS. This grant does not include claims that would be infringed + only as a consequence of further modifications of THIS + IMPLEMENTATION. If you or your agent or licensee institute or order + or agree to the institution of patent litigation against any entity + (including a cross-claim or counterclaim in a lawsuit) alleging that + THIS IMPLEMENTATION constitutes direct or contributory patent + infringement, or inducement of patent infringement, then any rights + granted to you under this License shall terminate as of the date + such litigation is filed. If you or your agent or exclusive + licensee institute or order or agree to the institution of a PATENT + CHALLENGE, then Tokutek may terminate any rights granted to you + under this License. +*/ + +#ident "Copyright (c) 2007-2013 Tokutek Inc. All rights reserved." + +#include "test.h" + +bool expect_pf; + +static void +flush (CACHEFILE f __attribute__((__unused__)), + int UU(fd), + CACHEKEY k __attribute__((__unused__)), + void *v __attribute__((__unused__)), + void** UU(dd), + void *e __attribute__((__unused__)), + PAIR_ATTR s __attribute__((__unused__)), + PAIR_ATTR* new_size __attribute__((__unused__)), + bool w __attribute__((__unused__)), + bool keep __attribute__((__unused__)), + bool c __attribute__((__unused__)), + bool UU(is_clone) + ) { + assert(w == false); +} + +static int fetch_calls = 0; + +static int +fetch (CACHEFILE f __attribute__((__unused__)), + PAIR UU(p), + int UU(fd), + CACHEKEY k __attribute__((__unused__)), + uint32_t fullhash __attribute__((__unused__)), + void **value __attribute__((__unused__)), + void** UU(dd), + PAIR_ATTR *sizep __attribute__((__unused__)), + int *dirtyp __attribute__((__unused__)), + void *extraargs __attribute__((__unused__)) + ) { + + fetch_calls++; + sleep(2); + + *value = 0; + *sizep = make_pair_attr(1); + *dirtyp = 0; + + return 0; +} + +static void cachetable_prefetch_full_test (bool partial_fetch) { + const int test_limit = 2; + expect_pf = false; + int r; + CACHETABLE ct; + toku_cachetable_create(&ct, test_limit, ZERO_LSN, nullptr); + const char *fname1 = TOKU_TEST_FILENAME; + unlink(fname1); + CACHEFILE f1; + r = toku_cachetable_openf(&f1, ct, fname1, O_RDWR|O_CREAT, S_IRWXU|S_IRWXG|S_IRWXO); assert(r == 0); + + // prefetch block 0. this will take 2 seconds. + CACHEKEY key = make_blocknum(0); + uint32_t fullhash = toku_cachetable_hash(f1, make_blocknum(0)); + + // if we want to do a test of partial fetch, + // we first put the key into the cachefile so that + // the subsequent prefetch does a partial fetch + CACHETABLE_WRITE_CALLBACK wc = def_write_callback(NULL); + wc.flush_callback = flush; + if (partial_fetch) { + expect_pf = true; + void* value; + long size; + r = toku_cachetable_get_and_pin( + f1, + key, + fullhash, + &value, + &size, + wc, + fetch, + def_pf_req_callback, + def_pf_callback, + true, + 0 + ); + assert(r==0); + r = toku_test_cachetable_unpin(f1, key, fullhash, CACHETABLE_CLEAN, make_pair_attr(1)); + } + + r = toku_cachefile_prefetch(f1, key, fullhash, wc, fetch, def_pf_req_callback, def_pf_callback, 0, NULL); + toku_cachetable_verify(ct); + + // close with the prefetch in progress. the close should block until + // all of the reads and writes are complete. + toku_cachefile_close(&f1, false, ZERO_LSN); + toku_cachetable_close(&ct); +} + +int +test_main(int argc, const char *argv[]) { + default_parse_args(argc, argv); + cachetable_prefetch_full_test(true); + cachetable_prefetch_full_test(false); + return 0; +} diff --git a/pool/shard007/C++/0091347_WebSpeechRecognitionResult.cpp b/pool/shard007/C++/0091347_WebSpeechRecognitionResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b546f88d16ce6a6b68c383c2da8bdfcc9ad806c9 --- /dev/null +++ b/pool/shard007/C++/0091347_WebSpeechRecognitionResult.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2012 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. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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 "config.h" +#include "WebSpeechRecognitionResult.h" + +#include "SpeechRecognitionAlternative.h" +#include "SpeechRecognitionResult.h" +#include <wtf/PassRefPtr.h> +#include <wtf/Vector.h> + +namespace WebKit { + +void WebSpeechRecognitionResult::assign(const WebSpeechRecognitionResult& other) +{ + m_private = other.m_private; +} + +void WebSpeechRecognitionResult::assign(const WebVector<WebString>& transcripts, const WebVector<float>& confidences, bool final) +{ + ASSERT(transcripts.size() == confidences.size()); + + Vector<RefPtr<WebCore::SpeechRecognitionAlternative> > alternatives(transcripts.size()); + for (size_t i = 0; i < transcripts.size(); ++i) + alternatives[i] = WebCore::SpeechRecognitionAlternative::create(transcripts[i], confidences[i]); + + m_private = WebCore::SpeechRecognitionResult::create(alternatives, final); +} + +void WebSpeechRecognitionResult::reset() +{ + m_private.reset(); +} + +WebSpeechRecognitionResult::operator PassRefPtr<WebCore::SpeechRecognitionResult>() const +{ + return m_private.get(); +} + +} // namespace WebKit diff --git a/pool/shard007/C++/0091348_PVOutput_Input.cpp b/pool/shard007/C++/0091348_PVOutput_Input.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f32f19d110f33aa5b7d315a0c09697e5d76b20aa --- /dev/null +++ b/pool/shard007/C++/0091348_PVOutput_Input.cpp @@ -0,0 +1,216 @@ +#include "stdafx.h" +#include "PVOutput_Input.h" +#include "../main/Helper.h" +#include "../main/Logger.h" +#include "hardwaretypes.h" +#include "../main/localtime_r.h" +#include "../json/json.h" +#include "../main/RFXtrx.h" +#include "../main/SQLHelper.h" +#include "../httpclient/HTTPClient.h" +#include "../main/mainworker.h" + +#define round(a) ( int ) ( a + .5 ) + +//#define DEBUG_PVOutputInput + +CPVOutputInput::CPVOutputInput(const int ID, const std::string &SID, const std::string &Key) +{ + m_HwdID=ID; + m_SID=SID; + m_KEY=Key; + m_stoprequested=false; + Init(); +} + +CPVOutputInput::~CPVOutputInput(void) +{ +} + +void CPVOutputInput::Init() +{ +} + +bool CPVOutputInput::StartHardware() +{ + Init(); + //Start worker thread + m_thread = boost::shared_ptr<boost::thread>(new boost::thread(boost::bind(&CPVOutputInput::Do_Work, this))); + m_bIsStarted=true; + sOnConnected(this); + return (m_thread!=NULL); +} + +bool CPVOutputInput::StopHardware() +{ + if (m_thread!=NULL) + { + assert(m_thread); + m_stoprequested = true; + m_thread->join(); + } + m_bIsStarted=false; + return true; +} + +#define PVOUTPUT_POLL_INTERVAL 5 + +void CPVOutputInput::Do_Work() +{ + int LastMinute=-1; + int sec_counter = 0; + _log.Log(LOG_STATUS,"PVOutput (Input): Worker started..."); + while (!m_stoprequested) + { + sleep_seconds(1); + sec_counter++; + + time_t atime=mytime(NULL); + m_LastHeartbeat = atime; + struct tm ltime; + localtime_r(&atime,<ime); + if (((ltime.tm_min/PVOUTPUT_POLL_INTERVAL!=LastMinute))&&(ltime.tm_sec>20)) + { + LastMinute=ltime.tm_min/PVOUTPUT_POLL_INTERVAL; + GetMeterDetails(); + } + } + _log.Log(LOG_STATUS,"PVOutput (Input): Worker stopped..."); +} + +bool CPVOutputInput::WriteToHardware(const char *pdata, const unsigned char length) +{ + return false; +} + +void CPVOutputInput::SendTempSensor(const unsigned char Idx, const float Temp, const std::string &defaultname) +{ + RBUF tsen; + memset(&tsen,0,sizeof(RBUF)); + + tsen.TEMP.packetlength=sizeof(tsen.TEMP)-1; + tsen.TEMP.packettype=pTypeTEMP; + tsen.TEMP.subtype=sTypeTEMP10; + tsen.TEMP.battery_level=9; + tsen.TEMP.rssi=12; + tsen.TEMP.id1=0; + tsen.TEMP.id2=Idx; + + tsen.TEMP.tempsign=(Temp>=0)?0:1; + int at10=round(abs(Temp*10.0f)); + tsen.TEMP.temperatureh=(BYTE)(at10/256); + at10-=(tsen.TEMP.temperatureh*256); + tsen.TEMP.temperaturel=(BYTE)(at10); + + sDecodeRXMessage(this, (const unsigned char *)&tsen.TEMP, defaultname.c_str(), 255); +} + +void CPVOutputInput::SendVoltage(const unsigned long Idx, const float Volt, const std::string &defaultname) +{ + _tGeneralDevice gDevice; + gDevice.subtype=sTypeVoltage; + gDevice.id=1; + gDevice.floatval1=Volt; + gDevice.intval1 = static_cast<int>(Idx); + sDecodeRXMessage(this, (const unsigned char *)&gDevice, defaultname.c_str(), 255); +} + +void CPVOutputInput::SendPercentage(const unsigned long Idx, const float Percentage, const std::string &defaultname) +{ + _tGeneralDevice gDevice; + gDevice.subtype=sTypePercentage; + gDevice.id=1; + gDevice.floatval1=Percentage; + gDevice.intval1 = static_cast<int>(Idx); + sDecodeRXMessage(this, (const unsigned char *)&gDevice, defaultname.c_str(), 255); +} + +void CPVOutputInput::GetMeterDetails() +{ + if (m_SID.size()==0) + return; + if (m_KEY.size()==0) + return; + + std::string sResult; + + std::stringstream sstr; + sstr << "http://pvoutput.org/service/r2/getstatus.jsp?sid=" << m_SID << "&key=" << m_KEY; + if (!HTTPClient::GET(sstr.str(),sResult)) + { + _log.Log(LOG_ERROR,"PVOutput (Input): Error login!"); + return; + } + std::vector<std::string> splitresult; + StringSplit(sResult,",",splitresult); + if (splitresult.size()<9) + { + _log.Log(LOG_ERROR,"PVOutput (Input): Invalid Data received!"); + return; + } + + double Usage=atof(splitresult[3].c_str()); + if (Usage < 0) + Usage = 0; + + bool bHaveConsumption=false; + double Consumption=0; + if (splitresult[5]!="NaN") + { + Consumption=atof(splitresult[5].c_str()); + if (Consumption < 0) + Consumption = 0; + bHaveConsumption=true; + } + + if (splitresult[6]!="NaN") + { + double Efficiency=atof(splitresult[6].c_str())*100.0; + if (Efficiency>100.0) + Efficiency=100.0; + SendPercentage(1,float(Efficiency),"Efficiency"); + } + if (splitresult[7]!="NaN") + { + double Temperature=atof(splitresult[7].c_str()); + SendTempSensor(1,float(Temperature),"Temperature"); + } + if (splitresult[8]!="NaN") + { + double Voltage=atof(splitresult[8].c_str()); + if (Voltage>=0) + SendVoltage(1,float(Voltage),"Voltage"); + } + + sstr.clear(); + sstr.str(""); + + sstr << "http://pvoutput.org/service/r2/getstatistic.jsp?sid=" << m_SID << "&key=" << m_KEY << "&c=1"; + if (!HTTPClient::GET(sstr.str(),sResult)) + { + _log.Log(LOG_ERROR,"PVOutput (Input): Error login!"); + return; + } + StringSplit(sResult,",",splitresult); + if (splitresult.size()<11) + { + _log.Log(LOG_ERROR,"PVOutput (Input): Invalid Data received!"); + return; + } + + double kWhCounterUsage=atof(splitresult[0].c_str()); + SendKwhMeter(0, 1, 255, Usage, kWhCounterUsage / 1000.0, "SolarMain"); + + if (bHaveConsumption) + { + if (splitresult.size() > 11) + { + double kWhCounterConsumed = atof(splitresult[11].c_str()); + if (kWhCounterConsumed != 0) + { + SendKwhMeter(0, 2, 255, Consumption, kWhCounterConsumed / 1000.0, "SolarConsumed"); + } + } + } +} + diff --git a/pool/shard007/C++/0091350_Ragnarok.cpp b/pool/shard007/C++/0091350_Ragnarok.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb1cbf54015687cd9c985b47601d10d2647a2bb3 --- /dev/null +++ b/pool/shard007/C++/0091350_Ragnarok.cpp @@ -0,0 +1,93 @@ +#include "main.h" + +LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM); + +Main *main; + +BOOL bActive = TRUE; + +int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) +{ + static TCHAR szAppName[] = "Ragnarok"; + HWND hwnd; + MSG msg; + WNDCLASS wndclass; + + wndclass.style = CS_HREDRAW | CS_VREDRAW; + wndclass.lpfnWndProc = WndProc; + wndclass.cbClsExtra = 0; + wndclass.cbWndExtra = 0; + wndclass.hInstance = hInstance; + wndclass.hIcon = LoadIcon (hInstance, "icon"); + wndclass.hCursor = LoadCursor (NULL, IDC_ARROW); + wndclass.hbrBackground = NULL; + wndclass.lpszMenuName = NULL; + wndclass.lpszClassName = szAppName; + + if (!RegisterClass (&wndclass)) + { + MessageBox (NULL, "Nepodaøilo se zaregistrovat tøídu okna", szAppName, MB_ICONERROR); + return 0; + } + + hwnd = CreateWindowEx (WS_EX_TOPMOST, + szAppName, + szAppName, + WS_POPUP, + CW_USEDEFAULT, + CW_USEDEFAULT, + CW_USEDEFAULT, + CW_USEDEFAULT, + NULL, + NULL, + hInstance, + NULL); + + main = new Main (hwnd); + + ShowWindow (hwnd, iCmdShow); + UpdateWindow (hwnd); + + if (!main->DXInit ()) + { + delete main; + main = NULL; + return 0; + } + + while (1) + { + if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)) + { + if (!GetMessage (&msg, NULL, 0, 0)) + return msg.wParam; + + TranslateMessage (&msg); + DispatchMessage (&msg); + } + else if (bActive) + main->Test (); + else + WaitMessage (); + } +} + +LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) +{ + switch (message) + { + case WM_ACTIVATEAPP: + bActive = wParam; + return 0; + + case WM_CHAR: + main->PutChar ((char)wParam); + return 0; + + case WM_DESTROY: + delete main; + PostQuitMessage (0); + return 0; + } + return DefWindowProc (hwnd, message, wParam, lParam); +} \ No newline at end of file diff --git a/pool/shard007/C++/0091359_md5_test.cc b/pool/shard007/C++/0091359_md5_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..f0c165aa4ff274df14a85c247d90afc26ecbd1f4 --- /dev/null +++ b/pool/shard007/C++/0091359_md5_test.cc @@ -0,0 +1,43 @@ +/* Copyright 2016 Google Inc. 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 "md5.h" +#include "gtest/gtest.h" + +namespace google { +namespace service_control_client { +namespace { + +// Unit tests to use CheckRequest protobuf message + +TEST(MD5Test, TestPriableGigest) { + static const char data[] = "Test Data"; + ASSERT_EQ("0a22b2ac9d829ff3605d81d5ae5e9d16", + MD5::DebugString(MD5()(data, sizeof(data)))); +} + +TEST(MD5Test, TestGigestEqual) { + static const char data1[] = "Test Data1"; + static const char data2[] = "Test Data2"; + auto d1 = MD5()(data1, sizeof(data1)); + auto d11 = MD5()(data1, sizeof(data1)); + auto d2 = MD5()(data2, sizeof(data2)); + ASSERT_EQ(d11, d1); + ASSERT_NE(d1, d2); +} + +} // namespace +} // namespace service_control_client +} // namespace google diff --git a/pool/shard007/C++/0091369_mewzikdata.cpp b/pool/shard007/C++/0091369_mewzikdata.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7aa826bba81cfc3a35e3c4a7209c99570a617484 --- /dev/null +++ b/pool/shard007/C++/0091369_mewzikdata.cpp @@ -0,0 +1,107 @@ +#include "mewzikdata.h" +#include <QDir> +#include <QDebug> + +MewZikDataValue::MewZikDataValue(const QString &artist, const QString &album, + const QString &genre, const QString &title) + : m_artist(artist), m_album(album), m_genre(genre), m_title(title) +{ + +} +QString MewZikDataValue::artist() const +{ + return m_artist; +} +QString MewZikDataValue::album() const +{ + return m_album; +} +QString MewZikDataValue::genre() const +{ + return m_genre; +} +QString MewZikDataValue::title() const +{ + return m_title; +} +/** + * @brief MewZikDataModel::MewZikDataModel + * When initializing the data structure we'll have a database in theory that + * will index the library on startup (based on a setting). Currently using + * an absolute path to where music exists on a local machine for testing. + * Database will be in place in due time. The database will do all the filtering + * of files that we wish to include in the library whether it be *.wav, *.mp3, + * *.mp4 etc. + * This abstract list model will be bound to UI for listing the content the user + * has chosen to include within their library. + * @param parent + */ +MewZikDataModel::MewZikDataModel(QObject *parent) : QAbstractListModel(parent) +{ + QStringList nameFilter("*.mp3"); + QDir directory("/Users/kevin/Music/iTunes/iTunes Media/Music/Unknown Artist/Unknown Album"); + QStringList txtFilesAndDirectories = directory.entryList(nameFilter); + QFileInfoList fileList = directory.entryInfoList(nameFilter); + + qDebug() << directory.entryInfoList(); + qDebug() << "length" << fileList.length(); + for (int i = 0; i < fileList.length(); i++){ + qDebug() << "File: " << fileList.at(i).absoluteFilePath(); + // MewZikDataValue *t = new MewZikDataValue(txtFilesAndDirectories.at(i), "b", "c", "d"); + // addRow(*t); + } + +} + +void MewZikDataModel::addRow(const MewZikDataValue &dataValue) +{ + beginInsertRows(QModelIndex(), rowCount(), rowCount()); + m_mewZikDataValues << dataValue; + endInsertRows(); +} + +int MewZikDataModel::rowCount(const QModelIndex &parent) const +{ + Q_UNUSED(parent) + return m_mewZikDataValues.count(); +} +void MewZikDataModel::removeAllRows() +{ + beginResetModel(); + m_mewZikDataValues.clear(); + endResetModel(); +} +/** + * @brief MewZikDataModel::data + * This overridden method is a list model that a ListView will use to display + * the content library. + * @param index The index in the database to present content info + * @param role The role of which data to present. Artist, Genre etc. + * @return + */ +QVariant MewZikDataModel::data(const QModelIndex &index, int role) const +{ + if(!index.isValid()) + return QVariant(); + const MewZikDataValue &mewZikDataValue = m_mewZikDataValues[index.row()]; + if(role == ArtistRole){ + return mewZikDataValue.artist(); + }else if(role == AlbumRole){ + return mewZikDataValue.album(); + }else if(role == GenreRole){ + return mewZikDataValue.genre(); + }else if(role == TitleRole){ + return mewZikDataValue.title(); + } + return QVariant(); +} + +QHash<int, QByteArray> MewZikDataModel::roleNames() const +{ + QHash<int, QByteArray> roles; + roles[ArtistRole] = "artist"; + roles[AlbumRole] = "album"; + roles[GenreRole] = "genre"; + roles[TitleRole] = "title"; + return roles; +} diff --git a/pool/shard007/C++/0091378_main.cc b/pool/shard007/C++/0091378_main.cc new file mode 100644 index 0000000000000000000000000000000000000000..d57bca724b14d216500127dce1de6706fc543d33 --- /dev/null +++ b/pool/shard007/C++/0091378_main.cc @@ -0,0 +1,61 @@ +#include <iostream> +#include <boost/program_options.hpp> +#include <dbus-c++/dbus.h> +#include <dbus-c++/glib-integration.h> +#include <gtkmm/application.h> +#include "countwindow.hh" + +using namespace std; +namespace po = boost::program_options; + +namespace { + DBus::Glib::BusDispatcher dbus_dispatcher; +} + +int main(int argc, char *argv[]) { + po::options_description desc("Allowed options"); + desc.add_options() + ("help", "Display this help and exit.") + ("period", po::value<int>()->value_name("MINUTES")->default_value(60), "Maximum session period in minutes") + ("idle-timeout", po::value<int>()->value_name("MINUTES")->default_value(5), "Maximum idle timeout in minutes") + ; + po::variables_map config; + try { + po::store(po::parse_command_line(argc, argv, desc), config); + } catch (const po::error& e) { + cerr << "Invalid commandline option: " << e.what() << endl + << endl + << desc << endl; + return 1; + } + po::notify(config); + + if (config.count("help")) { + cout << desc << endl; + return 0; + } + + auto app = Gtk::Application::create("nl.attingo.countdown"); + + if (!Glib::thread_supported()) + Glib::thread_init(); + + DBus::_init_threading(); + DBus::default_dispatcher=&dbus_dispatcher; + + CountWindow window(chrono::minutes(config["period"].as<int>()), chrono::minutes(config["idle-timeout"].as<int>())); + + auto css = Gtk::CssProvider::create(); + try { + css->load_from_path(DATADIR "countdown.css"); + } catch (const Glib::Error &e) { + cerr << "Error loading CSS: " << e.what() << endl; + return 1; + } + auto screen = Gdk::Screen::get_default(); + auto ctx = Gtk::StyleContext::create(); + ctx->add_provider_for_screen(screen, css, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); + + return app->run(window, 1, argv); +} + diff --git a/pool/shard007/C++/0091381_RmlFile.cpp b/pool/shard007/C++/0091381_RmlFile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fef772cf8b48861d1abf6a933cde561dcc2b77b3 --- /dev/null +++ b/pool/shard007/C++/0091381_RmlFile.cpp @@ -0,0 +1,97 @@ +// +// Copyright (c) 2017-2020 the rbfx project. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +#include "../Core/Context.h" +#include "../IO/File.h" +#include "../IO/FileSystem.h" +#include "../Resource/ResourceCache.h" +#include "../RmlUI/RmlFile.h" + +#include "../DebugNew.h" + +namespace Urho3D +{ + +namespace Detail +{ + +RmlFile::RmlFile(Urho3D::Context* context) + : context_(context) +{ + +} + +Rml::FileHandle RmlFile::Open(const Rml::String& path) +{ + ResourceCache* cache = context_->GetSubsystem<ResourceCache>(); + SharedPtr<File> file(cache->GetFile(path)); + if (file.NotNull()) + { + loadedFiles_.insert(GetAbsolutePath(cache->GetResourceFileName(path))); + return reinterpret_cast<Rml::FileHandle>(file.Detach()); + } + return 0; +} + +void RmlFile::Close(Rml::FileHandle file) +{ + delete reinterpret_cast<File*>(file); +} + +size_t RmlFile::Read(void* buffer, size_t size, Rml::FileHandle file) +{ + return reinterpret_cast<File*>(file)->Read(buffer, size); +} + +bool RmlFile::Seek(Rml::FileHandle file, long offset, int origin) +{ + File* fp = reinterpret_cast<File*>(file); + if (origin == SEEK_CUR) + offset = fp->Tell() + offset; + else if (origin == SEEK_END) + offset = fp->GetSize() - offset; + return fp->Seek(offset) == offset; +} + +size_t RmlFile::Tell(Rml::FileHandle file) +{ + return reinterpret_cast<File*>(file)->Tell(); +} + +size_t RmlFile::Length(Rml::FileHandle file) +{ + return reinterpret_cast<File*>(file)->GetSize(); +} + +bool RmlFile::IsFileLoaded(const ea::string& path) +{ + ea::string fullPath; + FileSystem* fs = context_->GetSubsystem<FileSystem>(); + if (IsAbsolutePath(path)) + fullPath = GetAbsolutePath(path); + else + fullPath = GetAbsolutePath(fs->GetCurrentDir() + path); + return loadedFiles_.contains(fullPath); +} + +} // namespace Detail + +} // namespace Urho3D diff --git a/pool/shard007/C++/0091394_xlMD5Test.cpp b/pool/shard007/C++/0091394_xlMD5Test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fcabf8261645390a52a1db7752821f67fa563aa7 --- /dev/null +++ b/pool/shard007/C++/0091394_xlMD5Test.cpp @@ -0,0 +1,51 @@ +//------------------------------------------------------------------------------ +// +// Copyright (C) Streamlet. All rights reserved. +// +// File Name: xlMD5Test.cpp +// Author: Streamlet +// Create Time: 2011-04-30 +// Description: +// +//------------------------------------------------------------------------------ + + +#include "../../../../Include/xl/AppHelper/xlUnitTest.h" +#include "../../../../Include/xl/Common/Cryption/xlMD5.h" +#include "../../../../Include/xl/Common/String/xlString.h" +#include <stdio.h> + +namespace +{ + xl::StringA MD5DigestToString(xl::MD5::Digest digest) + { + xl::CharA szDigest[(xl::MD5::DIGEST_LENGTH + 1) * 2] = {}; + + for (size_t i = 0; i < xl::MD5::DIGEST_LENGTH; ++i) + { + sprintf_s(&szDigest[i * 2], 3, "%02x", digest[i]); + } + + return szDigest; + } + + xl::StringA StringMD5(const xl::StringA &str) + { + xl::MD5::Digest digest; + xl::MD5::Calculate(str, str.Length(), digest); + + return MD5DigestToString(digest); + } + + XL_TEST_CASE() + { + XL_TEST_ASSERT(StringMD5("") == "d41d8cd98f00b204e9800998ecf8427e"); + XL_TEST_ASSERT(StringMD5("a") == "0cc175b9c0f1b6a831c399e269772661"); + XL_TEST_ASSERT(StringMD5("ab") == "187ef4436122d1cc2f40dc2b92f0eba0"); + XL_TEST_ASSERT(StringMD5("abc") == "900150983cd24fb0d6963f7d28e17f72"); + XL_TEST_ASSERT(StringMD5("abcd") == "e2fc714c4727ee9395f324cd2e7f331f"); + XL_TEST_ASSERT(StringMD5("abcde") == "ab56b4d92b40713acc5af89985d4b786"); + XL_TEST_ASSERT(StringMD5("abcdef") == "e80b5017098950fc58aad83c8c14978e"); + XL_TEST_ASSERT(StringMD5("abcdefg") == "7ac66c0f148de9519b8bd264312c4d64"); + } +} diff --git a/pool/shard007/C++/0091399_FrameBuffer.cpp b/pool/shard007/C++/0091399_FrameBuffer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8b90251e65e9a2a7278a7f8188f024320d886cd8 --- /dev/null +++ b/pool/shard007/C++/0091399_FrameBuffer.cpp @@ -0,0 +1,127 @@ +/* + * FrameBuffer.cpp + * + * The MIT License (MIT) + * + * Copyright (c) 2014 FilipeCN + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * +*/ + +#include "FrameBuffer.h" +using namespace aergia::io::resources; + +#include <iostream> +using namespace std; + +FrameBuffer::FrameBuffer(){} + +FrameBuffer::~FrameBuffer() { + if(texColorBuffer) + glDeleteTextures(1, &texColorBuffer); + + glBindFramebuffer(GL_FRAMEBUFFER, 0); + + if(frameBuffer) + glDeleteFramebuffers(1, &frameBuffer); +} + +FrameBuffer::FrameBuffer(vec2 size){ + this->size = vec3(size.x,size.y,0); + + /* + glGenTextures(1, &texColorBuffer); + glBindTexture(GL_TEXTURE_2D, texColorBuffer); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei) size.x, (GLsizei) size.y, 0, + GL_RGB, GL_UNSIGNED_BYTE, NULL); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); +*/ + glGenFramebuffers(1, &frameBuffer); + glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, texColorBuffer, 0); + + CHECK_GL_ERRORS; + CHECK_FRAMEBUFFER; + + glBindFramebuffer(GL_FRAMEBUFFER, 0); +} + +FrameBuffer::FrameBuffer(vec3 size){ + this->size = size; + + glGenFramebuffers(1, &frameBuffer); + glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer); + + glGenTextures(1, &texColorBuffer); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_3D, texColorBuffer); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB16F, (GLsizei) size.x, (GLsizei) size.y, + (GLsizei) size.z, 0, GL_RGB, GL_HALF_FLOAT, NULL); + + CHECK_GL_ERRORS; + + glGenRenderbuffers(1, &renderBuffer); + glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer); + glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, texColorBuffer, 0); + // glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, colorTextureName, + // 0, layer); + + + CHECK_GL_ERRORS; + CHECK_FRAMEBUFFER; + + glClearColor(1, 1, 1, 1); + glClear(GL_COLOR_BUFFER_BIT); + glBindFramebuffer(GL_FRAMEBUFFER, 0); +} + +void FrameBuffer::enable(){ + glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer); + +} + +void FrameBuffer::disable(){ + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glBindRenderbuffer(GL_RENDERBUFFER, 0); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_3D, texColorBuffer); + + int w = -1, h = -1, d = -1; + glGetTexLevelParameteriv(GL_TEXTURE_3D, 0, GL_TEXTURE_WIDTH, &w); + glGetTexLevelParameteriv(GL_TEXTURE_3D, 0, GL_TEXTURE_HEIGHT, &h); + glGetTexLevelParameteriv(GL_TEXTURE_3D, 0, GL_TEXTURE_DEPTH, &d); + cout << "W " << w << endl; + cout << "H " << h << endl; + cout << "D " << d << endl; + CHECK_GL_ERRORS; +} + + diff --git a/pool/shard007/C++/0091401_subprocess.cpp b/pool/shard007/C++/0091401_subprocess.cpp new file mode 100644 index 0000000000000000000000000000000000000000..be795f6bc99d829cc5d00088dc45bedd47afe9ff --- /dev/null +++ b/pool/shard007/C++/0091401_subprocess.cpp @@ -0,0 +1,76 @@ +#include "subprocess.hpp" + +#include <windows.h> + +#include <cassert> +#include <sstream> +#include <stdexcept> +#include <system_error> + +#include <mettle/driver/exit_code.hpp> +#include <mettle/driver/windows/scoped_handle.hpp> +#include <mettle/driver/windows/scoped_pipe.hpp> + +namespace caliber::windows { + + namespace { + const std::size_t BUFSIZE = 4096; + } + + std::string slurp(const char *argv[]) { + assert(argv && "empty argv"); + + mettle::windows::scoped_pipe stdout_pipe; + if(!stdout_pipe.open() || + !stdout_pipe.set_write_inherit(true)) + throw std::system_error(GetLastError(), std::system_category()); + + std::ostringstream cmd_line; + cmd_line << argv[0]; + for(const char **i = argv + 1; *i; i++) + cmd_line << " " << *i; + + STARTUPINFOA startup_info = { sizeof(STARTUPINFOA) }; + startup_info.dwFlags = STARTF_USESTDHANDLES; + startup_info.hStdInput = GetStdHandle(STD_INPUT_HANDLE); + startup_info.hStdOutput = stdout_pipe.write_handle; + startup_info.hStdError = stdout_pipe.write_handle; + + PROCESS_INFORMATION proc_info; + + if(!CreateProcessA( + nullptr, const_cast<char*>(cmd_line.str().c_str()), nullptr, nullptr, + true, 0, nullptr, nullptr, &startup_info, &proc_info + )) { + throw std::system_error(GetLastError(), std::system_category()); + } + mettle::windows::scoped_handle subproc_handles[] = { + proc_info.hProcess, proc_info.hThread + }; + + if(!stdout_pipe.close_write()) + throw std::system_error(GetLastError(), std::system_category()); + + std::string output; + DWORD size; + char buf[BUFSIZE]; + + do { + if(!ReadFile(stdout_pipe.read_handle, buf, sizeof(buf), &size, nullptr)) { + DWORD err = GetLastError(); + if(err != ERROR_BROKEN_PIPE) + throw std::system_error(GetLastError(), std::system_category()); + } + output.append(buf, size); + } while(size != 0); + + DWORD exit_status; + if(!GetExitCodeProcess(proc_info.hProcess, &exit_status)) + throw std::system_error(GetLastError(), std::system_category()); + if(exit_status != 0) + throw std::runtime_error(output); + + return output; + } + +} // namespace caliber::windows diff --git a/pool/shard007/C++/0091406_BPFELFObjectWriter.cpp b/pool/shard007/C++/0091406_BPFELFObjectWriter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a5562c1a933e9bfd2148a88f850997d4b90b516d --- /dev/null +++ b/pool/shard007/C++/0091406_BPFELFObjectWriter.cpp @@ -0,0 +1,53 @@ +//===-- BPFELFObjectWriter.cpp - BPF ELF Writer ---------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "MCTargetDesc/BPFMCTargetDesc.h" +#include "llvm/MC/MCELFObjectWriter.h" +#include "llvm/MC/MCFixup.h" +#include "llvm/Support/ErrorHandling.h" + +using namespace llvm; + +namespace { +class BPFELFObjectWriter : public MCELFObjectTargetWriter { +public: + BPFELFObjectWriter(uint8_t OSABI); + + ~BPFELFObjectWriter() override; + +protected: + unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup, + bool IsPCRel) const override; +}; +} + +BPFELFObjectWriter::BPFELFObjectWriter(uint8_t OSABI) + : MCELFObjectTargetWriter(/*Is64Bit*/ true, OSABI, ELF::EM_NONE, + /*HasRelocationAddend*/ false) {} + +BPFELFObjectWriter::~BPFELFObjectWriter() {} + +unsigned BPFELFObjectWriter::GetRelocType(const MCValue &Target, + const MCFixup &Fixup, + bool IsPCRel) const { + // determine the type of the relocation + switch ((unsigned)Fixup.getKind()) { + default: + llvm_unreachable("invalid fixup kind!"); + case FK_SecRel_8: + return ELF::R_X86_64_64; + case FK_SecRel_4: + return ELF::R_X86_64_PC32; + } +} + +MCObjectWriter *llvm::createBPFELFObjectWriter(raw_pwrite_stream &OS, uint8_t OSABI) { + MCELFObjectTargetWriter *MOTW = new BPFELFObjectWriter(OSABI); + return createELFObjectWriter(MOTW, OS, /*IsLittleEndian=*/true); +} diff --git a/pool/shard007/C++/0091419_update_menue.cpp b/pool/shard007/C++/0091419_update_menue.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1978b885fb9614d936a62377b0b1ab8090d3345d --- /dev/null +++ b/pool/shard007/C++/0091419_update_menue.cpp @@ -0,0 +1,144 @@ +/* + $Id: port of software_update.cpp,v 1.8 2011/04/03 21:56:13 tuxbox-cvs Exp $ + + Neutrino-GUI - DBoxII-Project + + Software update implementation - Neutrino-GUI + + Copyright (C) 2001 Steffen Hehn 'McClean' + and some other guys + Homepage: http://dbox.cyberphoria.org/ + + Rework Copyright (C) 2011 T. Graf 'dbt' + Homepage: http://www.dbox2-tuning.net/ + + License: GPL + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program; if not, write to the + Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <global.h> +#include <neutrino.h> +#include <neutrino_menue.h> + +#include "update_menue.h" +#include "update_settings.h" +#include "gui/opkg_manager.h" +#include <gui/widget/icons.h> +#include <driver/screen_max.h> +#include <system/debug.h> +#include <system/flashtool.h> + +CSoftwareUpdate::CSoftwareUpdate() +{ + width = w_max (40, 10); + fe = new CFlashExpert(); +} + +CSoftwareUpdate::~CSoftwareUpdate() +{ + delete fe; +} + +int CSoftwareUpdate::exec(CMenuTarget* parent, const std::string &/*actionKey*/) +{ + dprintf(DEBUG_DEBUG, "init software-update\n"); + int res = menu_return::RETURN_REPAINT; + + if (parent) + parent->hide(); + + res = showSoftwareUpdate(); + return res; +} + +int CSoftwareUpdate::showSoftwareUpdate() +/* shows the menue and options for software update */ +{ + CMenuForwarder * mf; + CMenuWidget softUpdate(LOCALE_MAINMENU_SERVICE, NEUTRINO_ICON_UPDATE, width, MN_WIDGET_ID_SOFTWAREUPDATE); + + softUpdate.addIntroItems(LOCALE_SERVICEMENU_UPDATE); + + //flashing + CFlashUpdate flash; + + CMenuForwarder *update_item = new CMenuForwarder(LOCALE_FLASHUPDATE_CHECKUPDATE_INTERNET, true, NULL, &flash, "inet", CRCInput::RC_red); + update_item->setHint("", LOCALE_MENU_HINT_SOFTUPDATE_CHECK); + softUpdate.addItem(update_item); + + update_item = new CMenuForwarder(LOCALE_FLASHUPDATE_CHECKUPDATE_LOCAL, true, NULL, &flash, "local", CRCInput::RC_green); + update_item->setHint("", LOCALE_MENU_HINT_SOFTUPDATE_CHECK_LOCAL); + softUpdate.addItem(update_item); + + CUpdateSettings update_settings; + CMenuWidget mtdexpert(LOCALE_FLASHUPDATE_EXPERTFUNCTIONS, NEUTRINO_ICON_UPDATE, width, MN_WIDGET_ID_MTDEXPERT); + //settings + if (!g_settings.easymenu) { + mf = new CMenuForwarder(LOCALE_FLASHUPDATE_SETTINGS, true, NULL, &update_settings, NULL, CRCInput::RC_yellow); + mf->setHint("", LOCALE_MENU_HINT_SOFTUPDATE_SETTINGS); + softUpdate.addItem(mf); + + softUpdate.addItem(GenericMenuSeparatorLine); + + //expert-functions + showSoftwareUpdateExpert(&mtdexpert); + mf = new CMenuForwarder(LOCALE_FLASHUPDATE_EXPERTFUNCTIONS, true, NULL, &mtdexpert, NULL, CRCInput::RC_blue); + mf->setHint("", LOCALE_MENU_HINT_SOFTUPDATE_EXPERT); + softUpdate.addItem(mf); + + //firmware update via opkg + if (COPKGManager::hasOpkgSupport()) { + mf = new CMenuForwarder(LOCALE_OPKG_TITLE, true, NULL, new COPKGManager()); + mf->setHint(NEUTRINO_ICON_HINT_SW_UPDATE, LOCALE_MENU_HINT_OPKG); + softUpdate.addItem(mf); + } + + } + +#ifdef BOXMODEL_APOLLO + softUpdate.addItem(GenericMenuSeparatorLine); + + if (g_settings.easymenu) + mf = new CMenuDForwarder(LOCALE_FLASHUPDATE_CREATEIMAGE_MENU, true, NULL, new CFlashExpertSetup(), NULL, CRCInput::RC_yellow); + else + mf = new CMenuDForwarder(LOCALE_FLASHUPDATE_CREATEIMAGE_MENU, true, NULL, new CFlashExpertSetup(), NULL, CRCInput::convertDigitToKey(1)); + mf->setHint("", LOCALE_MENU_HINT_SOFTUPDATE_CREATEIMAGE_MENU); + softUpdate.addItem(mf); +#endif + + int res = softUpdate.exec (NULL, ""); + return res; +} + +/* shows experts-functions to read/write to the mtd */ +void CSoftwareUpdate::showSoftwareUpdateExpert(CMenuWidget *w_mtd_expert) +{ + CMenuForwarder * mf; + w_mtd_expert->addIntroItems(); + + mf = new CMenuForwarder(LOCALE_FLASHUPDATE_READFLASHMTD , true, NULL, fe, "readflashmtd" , CRCInput::RC_red); + mf->setHint("", LOCALE_MENU_HINT_SOFTUPDATE_EXPERT_READ); + w_mtd_expert->addItem(mf); + mf = new CMenuForwarder(LOCALE_FLASHUPDATE_WRITEFLASHMTD, true, NULL, fe, "writeflashmtd", CRCInput::RC_green); + mf->setHint("", LOCALE_MENU_HINT_SOFTUPDATE_EXPERT_WRITE); + w_mtd_expert->addItem(mf); +} diff --git a/pool/shard007/C++/0091426_InstitutionDepartments.cpp b/pool/shard007/C++/0091426_InstitutionDepartments.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ab8e30648c875b8408a908a47682f9690b868ab0 --- /dev/null +++ b/pool/shard007/C++/0091426_InstitutionDepartments.cpp @@ -0,0 +1,151 @@ +#include "InstitutionDepartments.h" +#include "dao/DepartmentDAO.h" +#include "dao/InstitutionDAO.h" +#include "dao/functions.h" + +#include <QtCore/QtDebug> + +using crrc::InstitutionDepartments; + +void InstitutionDepartments::index( Cutelyst::Context* c ) +{ + const auto& list = dao::isGlobalAdmin( c ) ? + dao::DepartmentDAO().retrieveAll() : + dao::DepartmentDAO().retrieveByInstitution( dao::institutionId( c ) ); + + QVariantList ilist; + if ( dao::isGlobalAdmin( c ) ) ilist = dao::InstitutionDAO().retrieveAll(); + else + { + ilist << dao::InstitutionDAO().retrieve( dao::institutionId( c ) ); + } + + c->stash( { + { "departments", list }, + { "institutions", ilist }, + { "template", "institutions/departments/index.html" } + } ); +} + +void InstitutionDepartments::base( Cutelyst::Context* c ) const +{ + c->response()->setHeader( "Cache-Control", "no-cache, no-store, must-revalidate" ); +} + +void InstitutionDepartments::object( Cutelyst::Context* c, const QString& id ) const +{ + const auto& obj = dao::InstitutionDAO().retrieve( id.toUInt() ); + c->setStash( "object", dao::isGlobalAdmin( c ) ? obj : + ( id.toUInt() == dao::institutionId( c ) ) ? obj : QVariant() ); +} + +void InstitutionDepartments::list( Cutelyst::Context* c ) const +{ + const auto obj = c->stash( "object" ); + const auto ptr = model::Institution::from( c->stash( "object" ) ); + const auto id = ptr ? ptr->getId() : 0; + const auto& list = ptr ? dao::DepartmentDAO().retrieveByInstitution( id ) : QVariantList(); + QVariantList ilist{ obj }; + + c->stash( { + { "departments", list }, + { "institutions", ilist }, + { "template", "institutions/departments/index.html" } + } ); +} + +void InstitutionDepartments::save( Cutelyst::Context* c ) const +{ + const auto& did = c->request()->param( "id" ); + const auto& object = c->stash( "object" ); + + dao::DepartmentDAO dao; + QJsonObject json; + + if ( ! checkAndReturn( c ) ) return; + + if ( did.isEmpty() || ! did.toUInt() ) + { + const uint32_t id = dao.insert( c ); + json.insert( "id", static_cast<int>( id ) ); + json.insert( "status", id > 0 ); + } + else + { + const uint32_t count = dao.update( c ); + json.insert( "id", did.toInt() ); + json.insert( "count", static_cast<int>( count ) ); + json.insert( "status", count > 0 ); + } + + QJsonObject inst; + inst.insert( "id", c->request()->param( "institutionId" ) ); + json.insert( "institution", inst ); + + const auto& error = c->stash( "error_msg" ); + if ( !error.isNull() ) json.insert( "message", error.toString() ); + + dao::sendJson( c, json ); +} + +void InstitutionDepartments::remove( Cutelyst::Context* c ) const +{ + auto id = c->request()->param( "id", "" ); + QJsonObject obj; + + if ( id.isEmpty() ) + { + obj.insert( "status", false ); + dao::sendJson( c, obj ); + return; + } + + if ( ! checkAndReturn( c ) ) return; + + auto const result = dao::DepartmentDAO().remove( id.toUInt() ); + obj.insert( "id", id.toInt() ); + + if ( result ) + { + obj.insert( "count", static_cast<int>( result ) ); + obj.insert( "status", true ); + } + else obj.insert( "status", false ); + + const auto& err = c->stash( "error_msg" ); + if ( !err.isNull() ) obj.insert( "message", err.toString() ); + + dao::sendJson( c, obj ); +} + +bool InstitutionDepartments::canEdit( Cutelyst::Context* c ) const +{ + if ( dao::isGlobalAdmin( c ) ) return true; + const auto iid = c->request()->param( "institutionId" ).toUInt(); + return ( iid && iid == dao::institutionId( c ) ); +} + +bool InstitutionDepartments::checkAndReturn( Cutelyst::Context* c ) const +{ + QJsonObject json; + + if ( ! canEdit( c ) ) + { + json.insert( "message", "Unauthorized. User may not manage departments in other institutions." ); + json.insert( "status", false ); + dao::sendJson( c, json ); + return false; + } + + const auto& iid = c->request()->param( "institutionId" ); + + if ( iid.isEmpty() ) + { + json.insert( "message", "No institution specified" ); + json.insert( "status", false ); + dao::sendJson( c, json ); + return false; + } + + return true; +} diff --git a/pool/shard007/C++/0091435_clangstaticanalyzerunittests.cpp b/pool/shard007/C++/0091435_clangstaticanalyzerunittests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ea6c9cef300c72a2c0d8084c22bc053adef9e57 --- /dev/null +++ b/pool/shard007/C++/0091435_clangstaticanalyzerunittests.cpp @@ -0,0 +1,133 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of Qt Creator. +** +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +****************************************************************************/ + +#include "clangstaticanalyzerunittests.h" + +#include "clangstaticanalyzerdiagnostic.h" +#include "clangstaticanalyzertool.h" +#include "clangstaticanalyzerutils.h" + +#include <cpptools/cppmodelmanager.h> +#include <cpptools/cpptoolstestcase.h> +#include <projectexplorer/kitinformation.h> +#include <projectexplorer/kitmanager.h> +#include <projectexplorer/projectexplorer.h> +#include <projectexplorer/toolchain.h> +#include <utils/fileutils.h> + +#include <QEventLoop> +#include <QSignalSpy> +#include <QTemporaryDir> +#include <QTimer> +#include <QtTest> + +using namespace ProjectExplorer; +using namespace Utils; + +namespace ClangStaticAnalyzer { +namespace Internal { + +ClangStaticAnalyzerUnitTests::ClangStaticAnalyzerUnitTests(ClangStaticAnalyzerTool *analyzerTool, + QObject *parent) + : QObject(parent) + , m_analyzerTool(analyzerTool) + , m_tmpDir(0) +{ +} + +void ClangStaticAnalyzerUnitTests::initTestCase() +{ + const QList<Kit *> allKits = KitManager::kits(); + if (allKits.count() != 1) + QSKIP("This test requires exactly one kit to be present"); + const ToolChain * const toolchain = ToolChainKitInformation::toolChain(allKits.first(), + ToolChain::Language::Cxx); + if (!toolchain) + QSKIP("This test requires that there is a kit with a toolchain."); + bool hasClangExecutable; + clangExecutableFromSettings(toolchain->typeId(), &hasClangExecutable); + if (!hasClangExecutable) + QSKIP("No clang suitable for analyzing found"); + + m_tmpDir = new CppTools::Tests::TemporaryCopiedDir(QLatin1String(":/unit-tests")); + QVERIFY(m_tmpDir->isValid()); +} + +void ClangStaticAnalyzerUnitTests::cleanupTestCase() +{ + delete m_tmpDir; +} + +void ClangStaticAnalyzerUnitTests::testProject() +{ + QFETCH(QString, projectFilePath); + QFETCH(int, expectedDiagCount); + + CppTools::Tests::ProjectOpenerAndCloser projectManager; + const CppTools::ProjectInfo projectInfo = projectManager.open(projectFilePath, true); + QVERIFY(projectInfo.isValid()); + m_analyzerTool->startTool(); + QSignalSpy waiter(m_analyzerTool, SIGNAL(finished(bool))); + QVERIFY(waiter.wait(30000)); + const QList<QVariant> arguments = waiter.takeFirst(); + QVERIFY(arguments.first().toBool()); + QCOMPARE(m_analyzerTool->diagnostics().count(), expectedDiagCount); +} + +void ClangStaticAnalyzerUnitTests::testProject_data() +{ + QTest::addColumn<QString>("projectFilePath"); + QTest::addColumn<int>("expectedDiagCount"); + + QTest::newRow("simple qbs project") + << QString(m_tmpDir->absolutePath("simple/simple.qbs")) << 1; + QTest::newRow("simple qmake project") + << QString(m_tmpDir->absolutePath("simple/simple.pro")) << 1; + + QTest::newRow("simple qbs library project") + << QString(m_tmpDir->absolutePath("simple-library/simple-library.qbs")) << 0; + QTest::newRow("simple qmake library project") + << QString(m_tmpDir->absolutePath("simple-library/simple-library.pro")) << 0; + + QTest::newRow("stdc++11-includes qbs project") + << QString(m_tmpDir->absolutePath("stdc++11-includes/stdc++11-includes.qbs")) << 0; + QTest::newRow("stdc++11-includes qmake project") + << QString(m_tmpDir->absolutePath("stdc++11-includes/stdc++11-includes.pro")) << 0; + + QTest::newRow("qt-widgets-app qbs project") + << QString(m_tmpDir->absolutePath("qt-widgets-app/qt-widgets-app.qbs")) << 0; + QTest::newRow("qt-widgets-app qmake project") + << QString(m_tmpDir->absolutePath("qt-widgets-app/qt-widgets-app.pro")) << 0; + + QTest::newRow("qt-essential-includes qbs project") + << QString(m_tmpDir->absolutePath("qt-essential-includes/qt-essential-includes.qbs")) + << 0; + QTest::newRow("qt-essential-includes qmake project") + << QString(m_tmpDir->absolutePath("qt-essential-includes/qt-essential-includes.pro")) + << 0; +} + +} // namespace Internal +} // namespace ClangStaticAnalyzerPlugin diff --git a/pool/shard007/C++/0091438_hud_basetimer.cpp b/pool/shard007/C++/0091438_hud_basetimer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c575bff04351b6806e18babdd11f304857e7a5ec --- /dev/null +++ b/pool/shard007/C++/0091438_hud_basetimer.cpp @@ -0,0 +1,84 @@ +//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// +// +// Purpose: Draws a timer in the format "Minutes:Seconds" +// Seconds are padded with zeros +// +//=============================================================================// + +#include "cbase.h" +#include "hudelement.h" +#include <vgui_controls/Panel.h> +#include <vgui/isurface.h> +#include "hud_basetimer.h" + +// memdbgon must be the last include file in a .cpp file!!! +#include "tier0/memdbgon.h" + +using namespace vgui; + +CHudBaseTimer::CHudBaseTimer(vgui::Panel *parent, const char *name) : BaseClass(parent, name) +{ + m_iMinutes = 0; + m_iSeconds = 0; + SetLabelText(L""); +} + +void CHudBaseTimer::SetMinutes(int minutes) +{ + m_iMinutes = minutes; +} + +void CHudBaseTimer::SetSeconds(int seconds) +{ + m_iSeconds = seconds; +} + +void CHudBaseTimer::PaintTime(HFont font, int xpos, int ypos, int mins, int secs) +{ + surface()->DrawSetTextFont(font); + wchar_t unicode[6]; + swprintf(unicode, L"%d:%.2d", mins, secs); + + surface()->DrawSetTextPos(xpos, ypos); + surface()->DrawUnicodeString( unicode ); +} + +void CHudBaseTimer::Paint() +{ + float alpha = m_flAlphaOverride / 255; + Color fgColor = GetFgColor(); + fgColor[3] *= alpha; + SetFgColor( fgColor ); + + surface()->DrawSetTextColor(GetFgColor()); + PaintTime( m_hNumberFont, digit_xpos, digit_ypos, m_iMinutes, m_iSeconds ); + + // draw the overbright blur + for (float fl = m_flBlur; fl > 0.0f; fl -= 1.0f) + { + if (fl >= 1.0f) + { + PaintTime(m_hNumberGlowFont, digit_xpos, digit_ypos, m_iMinutes, m_iSeconds); + } + else + { + // draw a percentage of the last one + Color col = GetFgColor(); + col[3] *= fl; + surface()->DrawSetTextColor(col); + PaintTime(m_hNumberGlowFont, digit_xpos, digit_ypos, m_iMinutes, m_iSeconds); + } + } + + BaseClass::PaintLabel(); +} + +void CHudBaseTimer::SetToPrimaryColor() +{ + SetFgColor(m_TextColor); +} + +void CHudBaseTimer::SetToSecondaryColor() +{ + SetFgColor(m_FlashColor); +} diff --git a/pool/shard007/C++/0091439_addressblockdelegate.cpp b/pool/shard007/C++/0091439_addressblockdelegate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62319b55122ca8d66c93b5e454aacd8c068266a9 --- /dev/null +++ b/pool/shard007/C++/0091439_addressblockdelegate.cpp @@ -0,0 +1,127 @@ +//----------------------------------------------------------------------------- +// File: addressblockdelegate.cpp +//----------------------------------------------------------------------------- +// Project: Kactus2 +// Author: Antti Kamppi +// Date: 24.08.2012 +// +// Description: +// The delegate that provides editors to add/remove/edit the details of address block. +//----------------------------------------------------------------------------- + +#include "addressblockdelegate.h" + +#include <common/widgets/booleanComboBox/booleancombobox.h> +#include <common/widgets/accessComboBox/accesscombobox.h> + +//----------------------------------------------------------------------------- +// Function: AddressBlockDelegate::AddressBlockDelegate() +//----------------------------------------------------------------------------- +AddressBlockDelegate::AddressBlockDelegate(QCompleter* parameterNameCompleter, + QSharedPointer<ParameterFinder> parameterFinder, QObject *parent): +ExpressionDelegate(parameterNameCompleter, parameterFinder, parent) +{ + +} + +//----------------------------------------------------------------------------- +// Function: AddressBlockDelegate::~AddressBlockDelegate() +//----------------------------------------------------------------------------- +AddressBlockDelegate::~AddressBlockDelegate() +{ + +} + +//----------------------------------------------------------------------------- +// Function: AddressBlockDelegate::createEditor() +//----------------------------------------------------------------------------- +QWidget* AddressBlockDelegate::createEditor(QWidget* parent, QStyleOptionViewItem const& option, + QModelIndex const& index ) const +{ + if (index.column() == AddressBlockColumns::VOLATILE) + { + return new BooleanComboBox(parent); + } + else if (index.column() == AddressBlockColumns::REGISTER_ACCESS) + { + return new AccessComboBox(parent); + } + else + { + return ExpressionDelegate::createEditor(parent, option, index); + } +} + +//----------------------------------------------------------------------------- +// Function: AddressBlockDelegate::setEditorData() +//----------------------------------------------------------------------------- +void AddressBlockDelegate::setEditorData(QWidget* editor, QModelIndex const& index) const +{ + if (index.column() == AddressBlockColumns::VOLATILE) + { + BooleanComboBox* boolBox = qobject_cast<BooleanComboBox*>(editor); + Q_ASSERT(boolBox); + + QString value = index.model()->data(index, Qt::DisplayRole).toString(); + boolBox->setCurrentValue(value); + } + else if (index.column() == AddressBlockColumns::REGISTER_ACCESS) + { + AccessComboBox* accessBox = qobject_cast<AccessComboBox*>(editor); + Q_ASSERT(accessBox); + + AccessTypes::Access access = AccessTypes::str2Access( + index.model()->data(index, Qt::DisplayRole).toString(), AccessTypes::ACCESS_COUNT); + accessBox->setCurrentValue(access); + } + else + { + ExpressionDelegate::setEditorData(editor, index); + } +} + +//----------------------------------------------------------------------------- +// Function: AddressBlockDelegate::setModelData() +//----------------------------------------------------------------------------- +void AddressBlockDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, QModelIndex const& index) const +{ + if (index.column() == AddressBlockColumns::VOLATILE) + { + BooleanComboBox* boolBox = qobject_cast<BooleanComboBox*>(editor); + Q_ASSERT(boolBox); + + QString value = boolBox->getCurrentValue(); + model->setData(index, value, Qt::EditRole); + } + else if (index.column() == AddressBlockColumns::REGISTER_ACCESS) + { + AccessComboBox* accessBox = qobject_cast<AccessComboBox*>(editor); + Q_ASSERT(accessBox); + + AccessTypes::Access access = accessBox->getCurrentValue(); + model->setData(index, AccessTypes::access2Str(access), Qt::EditRole); + } + else + { + ExpressionDelegate::setModelData(editor, model, index); + } +} + +//----------------------------------------------------------------------------- +// Function: AddressBlockDelegate::descriptionColumn() +//----------------------------------------------------------------------------- +int AddressBlockDelegate::descriptionColumn() const +{ + return AddressBlockColumns::DESCRIPTION; +} + +//----------------------------------------------------------------------------- +// Function: AddressBlockDelegate::columnAcceptsExpression() +//----------------------------------------------------------------------------- +bool AddressBlockDelegate::columnAcceptsExpression(int column) const +{ + return column == AddressBlockColumns::REGISTER_DIMENSION || + column == AddressBlockColumns::REGISTER_SIZE || + column == AddressBlockColumns::REGISTER_OFFSET || + column == AddressBlockColumns::IS_PRESENT; +} diff --git a/pool/shard007/C++/0091444_AWCProperty.cpp b/pool/shard007/C++/0091444_AWCProperty.cpp new file mode 100644 index 0000000000000000000000000000000000000000..088d37182e0060e6eb6dc660e4db1ecb4638daa3 --- /dev/null +++ b/pool/shard007/C++/0091444_AWCProperty.cpp @@ -0,0 +1,129 @@ +///////////////////////////////////////////////////////////////////////// +// +// Amuse World Creator +// Copyright (c) 2014. All Rights Reserved +// +// File: AWCProperty.cpp +// Author: Gianluca Belardelli +// Date: 18/05/2016 +// +///////////////////////////////////////////////////////////////////////// +#include <stdafx.h> +#include <AWCGui.h> +#include <AWCProperty.h> + +//IMPLEMENT_MSGHANDLER( AWCPropertyI, PropertyChange ); + +AWCPropertyI *createProperty( CString strPropName, CString strDisplayName, CString strClass, CString strType, unsigned int uiOffset, int nSize, void *lpObj, unsigned int uiFlags ) +{ + AWCPropertyI *lpRes = nullptr; + + if( !wcscmp( strType, AWCPROPSTRING ) ) + { + lpRes = (AWCPropertyI *)new AWCPropertyString(); + } + else if( !wcscmp( strType, AWCPROPFILE ) ) + { + lpRes = (AWCPropertyI *)new AWCPropertyString( AWCPropertyType::AWCPROP_FILE ); + } + else if( !wcscmp( strType, AWCPROPINT ) ) + { + lpRes = (AWCPropertyI *)new AWCPropertyInt(); + } + + if( lpRes ) + { + lpRes->m_strName = strPropName; + lpRes->m_strDisplayName = strDisplayName; + lpRes->m_nOffset = uiOffset; + lpRes->m_uiSize = nSize; + lpRes->m_lpObject = lpObj; + lpRes->m_uiFlags = uiFlags; + + //IAWCEditorObject *lpObject = (IAWCEditorObject *)lpObj; + //lpObject->m_strClassName = strClass; + } + + return lpRes; +} + +bool AWCPropertyI::AddPropertyChangeHandler( Functor1<LPAWCCALLBACKPARAMS> &fnHandler ) +{ + + /*for( unsigned int i=0; i<m_stlPropertyChangeHandlers.size(); ++i ) + { + Functor1<LPAWCCALLBACKPARAMS> fnHandlerReg = m_stlPropertyChangeHandlers[i]; + if( fnHandlerReg == fnHandler ) + return false; + }*/ + + m_stlPropertyChangeHandlers.push_back( fnHandler ); + return true; +} + +bool AWCPropertyI::onPropertyChange( void ) +{ + AWCCALLBACKPARAMS params; + + int n=m_stlPropertyChangeHandlers.size(); + params.lpPARAM1 = (void *)this; + PROCESS_HANDLERS( PropertyChange, ¶ms ); + + return true; +} + +AWCPropertyString::AWCPropertyString( int nForceType ) +{ + if( nForceType == 0 ) + m_eType = AWCPROP_STRING; + else + m_eType = (AWCPropertyType)nForceType; + +} + +void AWCPropertyString::SetValue( CString strFromText, void *lpObj ) +{ + if( lpObj ) + m_lpObject = lpObj; + + CString *lpDestStr = (CString*)( (unsigned char *)m_lpObject + m_nOffset ); + lpDestStr->SetString( strFromText ); + onPropertyChange(); +} + +void AWCPropertyString::GetValue( CString *lpstrToText, void *lpObj ) +{ + if( lpObj ) + m_lpObject = lpObj; + + CString *lpSrcStr = (CString*)( (unsigned char *)m_lpObject + m_nOffset ); + lpstrToText->Append( *lpSrcStr ); +} + + +AWCPropertyInt::AWCPropertyInt( void ) +{ + m_eType = AWCPROP_INT; +} + +void AWCPropertyInt::SetValue( CString strFromText, void *lpObj ) +{ + if( lpObj ) + m_lpObject = lpObj; + + DWORD *lpDestStr = (DWORD*)( (unsigned char *)m_lpObject + m_nOffset ); + *lpDestStr = _wtoi( strFromText ); + onPropertyChange(); +} + +void AWCPropertyInt::GetValue( CString *lpstrToText, void *lpObj ) +{ + if( lpObj ) + m_lpObject = lpObj; + + DWORD *lpSrcStr = (DWORD*)( (unsigned char *)m_lpObject + m_nOffset ); + + wchar_t temp[128]; + wsprintf( temp, _T("%d"), *lpSrcStr ); + lpstrToText->Append( temp ); +} \ No newline at end of file diff --git a/pool/shard007/C++/0091456_LogFormatter.cpp b/pool/shard007/C++/0091456_LogFormatter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9a334f5ed855e7caeddb43e174bd7120f970a636 --- /dev/null +++ b/pool/shard007/C++/0091456_LogFormatter.cpp @@ -0,0 +1,71 @@ +#include "LogFormatter.h" + +#include <QDebug> + +LogFormatter::LogFormatter() + : m_logger(0) +{ + +} + +LogFormatter::LogFormatter(Logger *logger) + : m_logger(logger) +{ + m_format = logger->format(); +} + +LogFormatter::LogFormatter(QString format, Logger *logger) + : m_logger(logger), + m_format(format) +{ + +} + +LogFormatter::LogFormatter(const LogFormatter &other) +{ + m_logger = other.m_logger; + m_format = other.m_format; +} + +LogFormatter& LogFormatter::set(QString var, QString val) +{ + m_format.replace("$" + var, val); + + return *this; +} + +LogFormatter& LogFormatter::set(QString var, int val) +{ + return set(var, QString::number(val)); +} + +LogFormatter& LogFormatter::set(QString var, quint64 val) +{ + return set(var, QString::number(val)); +} + +void LogFormatter::log(Logger::Level level) +{ + if(!isValid()) + return; + + m_logger->log(level, m_format); +} + +void LogFormatter::log(Logger::Level level, QString msg) +{ + if(!isValid()) + return; + + m_logger->log(level, msg); +} + +bool LogFormatter::isValid() const +{ + return m_logger; +} + +QString LogFormatter::format() +{ + return m_format; +} diff --git a/pool/shard007/C++/0091461_MiddleEnemysView.cpp b/pool/shard007/C++/0091461_MiddleEnemysView.cpp new file mode 100644 index 0000000000000000000000000000000000000000..96db42d8a779989bba13f4a7e3c1752162ed094e --- /dev/null +++ b/pool/shard007/C++/0091461_MiddleEnemysView.cpp @@ -0,0 +1,136 @@ +// +// MiddleEnemysView.cpp +// Fighter +// +// Created by zhouyizirui on 9/5/14. +// +// + +#include "MiddleEnemysView.h" +#include "Constants.h" +MiddleEnemysView::MiddleEnemysView(): +enemysArray(NULL) +{ + +} + +MiddleEnemysView::~MiddleEnemysView() +{ + CC_SAFE_RELEASE(enemysArray); + //CC_SAFE_RELEASE(batchNode); + CCNotificationCenter::sharedNotificationCenter()->removeAllObservers(this); +} + +bool MiddleEnemysView::init() +{ + enemysArray = CCArray::create(); + enemysArray->retain(); + + /* + CCTextureCache::sharedTextureCache()->addImage("enemy2.png"); + batchNode = CCSpriteBatchNode::createWithTexture(CCTextureCache::sharedTextureCache()->textureForKey("enemy2.png")); + batchNode->setPosition(CCPointZero); + batchNode->retain(); + this->addChild(batchNode); + */ + + CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(MiddleEnemysView::onCreateEnemy), ADD_MIDDLE_ENEMY, NULL); + CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(MiddleEnemysView::onMoveStep), MOVE_MIDDLE_ENEMY, NULL); + CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(MiddleEnemysView::onRemoveEnemy), REMOVE_MIDDLE_ENEMY, NULL); + CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(MiddleEnemysView::onCrashEnemy), CRASH_MIDDLE_ENEMY, NULL); + CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(MiddleEnemysView::onHitten), HIT_MIDDLE_ENEMY, NULL); + return true; +} + +void MiddleEnemysView::onCreateEnemy(CCObject* setPoint) +{ + CCSprite* sprite = CCSprite::createWithSpriteFrameName("enemy2.png"); + + //CCSprite* sprite = CCSprite::createWithTexture(batchNode->getTexture()); + + //CCLOG("The small bouding box %f, %f, %f, %f", sprite->boundingBox().getMaxX(), sprite->boundingBox().getMaxY(), sprite->boundingBox().getMinX(), sprite->boundingBox().getMinY()); + enemysArray->addObject(sprite); + CCPoint startPoint = *(CCPoint*)setPoint; + sprite->setPosition(startPoint); + //CCMoveTo* moveTo = CCMoveTo::create(SMALL_ENEMY_SPEED, ccp(startPoint.x, -1)); + //sprite->runAction(moveTo); + this->addChild(sprite); + //batchNode->addChild(sprite); +} + +void MiddleEnemysView::onMoveStep() +{ + //CCLOG("Move it!"); + //CCLOG("The number of enmey %d", enemysArray->count()); + for(int i=0; i<enemysArray->count(); i++) + { + CCSprite* middle = (CCSprite*)enemysArray->objectAtIndex(i); + CCPoint currentPos = middle->getPosition(); + middle->setPosition(ccp(currentPos.x, currentPos.y-FRAME_INTERVAL*MIDDLE_ENEMY_SPEED)); + } +} + +void MiddleEnemysView::onRemoveEnemy(CCObject* index) +{ + //CCLOG("Remove it!"); + int reIndex = *(int*)index; + CCSprite* sprite = (CCSprite*)enemysArray->objectAtIndex(reIndex); + enemysArray->removeObjectAtIndex(reIndex); + this->removeChild(sprite); + //batchNode->removeChild(sprite, true); +} + +//Think about the CCObject pointer index, why to use the local variable pointer +void MiddleEnemysView::onCrashEnemy(CCObject* index) +{ + int reIndex = *(int*)index; + CCSprite* sprite = (CCSprite*)enemysArray->objectAtIndex(reIndex); + CCArray* aniFrames = CCArray::createWithCapacity(MIDDLE_ENEMY_BLOW_COUNT); + for(int i = 0; i<MIDDLE_ENEMY_BLOW_COUNT; i++) + { + char name[30] = {0}; + sprintf(name, "enemy2_down%d.png", i+1); + CCSpriteFrame* spriteFrame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(name); + CC_BREAK_IF(!spriteFrame); + aniFrames->addObject(spriteFrame); + } + CCAnimation* animation = CCAnimation::createWithSpriteFrames(aniFrames, 0.05f); + CCAnimate* animate = CCAnimate::create(animation); + CCSequence* sequence = CCSequence::create(animate, CCCallFuncN::create(this, callfuncN_selector(MiddleEnemysView::remove)), NULL); + sprite->runAction(sequence); + enemysArray->removeObjectAtIndex(reIndex); + //CCDirector::sharedDirector()->pause(); +} + +void MiddleEnemysView::onHitten(CCObject* index) +{ + int reIndex = *(int*)index; + CCSprite* sprite = (CCSprite*)enemysArray->objectAtIndex(reIndex); + CCArray* aniFrames = CCArray::createWithCapacity(2); + for(int i=0; i<MIDDLE_ENEMY_HIT_COUNT; i++) + { + char name[30] = {0}; + sprintf(name, "enemy2_hit.png"); + CCSpriteFrame* spriteFrame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(name); + CC_BREAK_IF(!spriteFrame); + aniFrames->addObject(spriteFrame); + } + CCSpriteFrame* spriteFrame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("enemy2.png"); + aniFrames->addObject(spriteFrame); + CCAnimation* animation = CCAnimation::createWithSpriteFrames(aniFrames, 0.05f); + CCAnimate* animate = CCAnimate::create(animation); + //CCSequence* sequence = CCSequence::create(animate, NULL); + sprite->runAction(animate); +} + +void MiddleEnemysView::remove(CCNode* node) +{ + //CCLOG("HAHAHAH REMOVE The fucking "); + if(node!=0) node->removeFromParentAndCleanup(true); + /* + int reIndex = *(int*)index; + CCSprite* sprite = (CCSprite*)enemysArray->objectAtIndex(reIndex); + enemysArray->removeObjectAtIndex(reIndex); + this->removeChild(sprite); + */ +} diff --git a/pool/shard007/C++/0091463_threadLocalStorage.cpp b/pool/shard007/C++/0091463_threadLocalStorage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0cdc48a0a6e619bb64610ebb47c73513bde65b1d --- /dev/null +++ b/pool/shard007/C++/0091463_threadLocalStorage.cpp @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "precompiled.hpp" +#include "runtime/threadLocalStorage.hpp" +#ifdef TARGET_OS_FAMILY_linux +# include "os_linux.inline.hpp" +# include "thread_linux.inline.hpp" +#endif +#ifdef TARGET_OS_FAMILY_solaris +# include "os_solaris.inline.hpp" +# include "thread_solaris.inline.hpp" +#endif +#ifdef TARGET_OS_FAMILY_windows +# include "os_windows.inline.hpp" +# include "thread_windows.inline.hpp" +#endif +#ifdef TARGET_OS_FAMILY_bsd +# include "os_bsd.inline.hpp" +# include "thread_bsd.inline.hpp" +#endif + +// static member initialization +int ThreadLocalStorage::_thread_index = -1; + +Thread* ThreadLocalStorage::get_thread_slow() { + return (Thread*) os::thread_local_storage_at(ThreadLocalStorage::thread_index()); +} + +void ThreadLocalStorage::set_thread(Thread* thread) { + pd_set_thread(thread); + + // The following ensure that any optimization tricks we have tried + // did not backfire on us: + guarantee(get_thread() == thread, "must be the same thread, quickly"); + guarantee(get_thread_slow() == thread, "must be the same thread, slowly"); +} + +void ThreadLocalStorage::init() { + assert(!is_initialized(), + "More than one attempt to initialize threadLocalStorage"); + pd_init(); + set_thread_index(os::allocate_thread_local_storage()); + generate_code_for_get_thread(); +} + +bool ThreadLocalStorage::is_initialized() { + return (thread_index() != -1); +} diff --git a/pool/shard007/C++/0091466_roundtrip_udp.cc b/pool/shard007/C++/0091466_roundtrip_udp.cc new file mode 100644 index 0000000000000000000000000000000000000000..89d6ce3a7f90de9e23fbc9253177229d0cf2fd57 --- /dev/null +++ b/pool/shard007/C++/0091466_roundtrip_udp.cc @@ -0,0 +1,153 @@ +#include <muduo/base/Logging.h> +#include <muduo/net/Channel.h> +#include <muduo/net/EventLoop.h> +#include <muduo/net/Socket.h> +#include <muduo/net/SocketsOps.h> +#include <muduo/net/TcpClient.h> +#include <muduo/net/TcpServer.h> + +#include <boost/bind.hpp> + +#include <stdio.h> + +using namespace muduo; +using namespace muduo::net; + +const size_t frameLen = 2*sizeof(int64_t); + +int createNonblockingUDP() +{ + int sockfd = ::socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_UDP); + if (sockfd < 0) + { + LOG_SYSFATAL << "::socket"; + } + return sockfd; +} + +/////////////////////////////// Server /////////////////////////////// + +void serverReadCallback(int sockfd, muduo::Timestamp receiveTime) +{ + int64_t message[2]; + struct sockaddr peerAddr; + bzero(&peerAddr, sizeof peerAddr); + socklen_t addrLen = sizeof peerAddr; + ssize_t nr = ::recvfrom(sockfd, message, sizeof message, 0, &peerAddr, &addrLen); + + char addrStr[64]; + sockets::toIpPort(addrStr, sizeof addrStr, &peerAddr); + LOG_DEBUG << "received " << nr << " bytes from " << addrStr; + + if (nr < 0) + { + LOG_SYSERR << "::recvfrom"; + } + else if (implicit_cast<size_t>(nr) == frameLen) + { + message[1] = receiveTime.microSecondsSinceEpoch(); + ssize_t nw = ::sendto(sockfd, message, sizeof message, 0, &peerAddr, addrLen); + if (nw < 0) + { + LOG_SYSERR << "::sendto"; + } + else if (implicit_cast<size_t>(nw) != frameLen) + { + LOG_ERROR << "Expect " << frameLen << " bytes, wrote " << nw << " bytes."; + } + } + else + { + LOG_ERROR << "Expect " << frameLen << " bytes, received " << nr << " bytes."; + } +} + +void runServer(uint16_t port) +{ + Socket sock(createNonblockingUDP()); + sock.bindAddress(InetAddress(port)); + EventLoop loop; + Channel channel(&loop, sock.fd()); + channel.setReadCallback(boost::bind(&serverReadCallback, sock.fd(), _1)); + channel.enableReading(); + loop.loop(); +} + +/////////////////////////////// Client /////////////////////////////// + +void clientReadCallback(int sockfd, muduo::Timestamp receiveTime) +{ + int64_t message[2]; + ssize_t nr = sockets::read(sockfd, message, sizeof message); + + if (nr < 0) + { + LOG_SYSERR << "::read"; + } + else if (implicit_cast<size_t>(nr) == frameLen) + { + int64_t send = message[0]; + int64_t their = message[1]; + int64_t back = receiveTime.microSecondsSinceEpoch(); + int64_t mine = (back+send)/2; + LOG_INFO << "round trip " << back - send + << " clock error " << their - mine; + } + else + { + LOG_ERROR << "Expect " << frameLen << " bytes, received " << nr << " bytes."; + } +} + +void sendMyTime(int sockfd) +{ + int64_t message[2] = { 0, 0 }; + message[0] = Timestamp::now().microSecondsSinceEpoch(); + ssize_t nw = sockets::write(sockfd, message, sizeof message); + if (nw < 0) + { + LOG_SYSERR << "::write"; + } + else if (implicit_cast<size_t>(nw) != frameLen) + { + LOG_ERROR << "Expect " << frameLen << " bytes, wrote " << nw << " bytes."; + } +} + +void runClient(const char* ip, uint16_t port) +{ + Socket sock(createNonblockingUDP()); + InetAddress serverAddr(ip, port); + int ret = sockets::connect(sock.fd(), serverAddr.getSockAddr()); + if (ret < 0) + { + LOG_SYSFATAL << "::connect"; + } + EventLoop loop; + Channel channel(&loop, sock.fd()); + channel.setReadCallback(boost::bind(&clientReadCallback, sock.fd(), _1)); + channel.enableReading(); + loop.runEvery(0.2, boost::bind(sendMyTime, sock.fd())); + loop.loop(); +} + +int main(int argc, char* argv[]) +{ + if (argc > 2) + { + uint16_t port = static_cast<uint16_t>(atoi(argv[2])); + if (strcmp(argv[1], "-s") == 0) + { + runServer(port); + } + else + { + runClient(argv[1], port); + } + } + else + { + printf("Usage:\n%s -s port\n%s ip port\n", argv[0], argv[0]); + } +} + diff --git a/pool/shard007/C++/0091467_8754861.cpp b/pool/shard007/C++/0091467_8754861.cpp new file mode 100644 index 0000000000000000000000000000000000000000..85fd6bb413e5cf2fed4f0d66a5cdd6768cb0ce9c --- /dev/null +++ b/pool/shard007/C++/0091467_8754861.cpp @@ -0,0 +1,66 @@ +//Language: GNU C++ + + +/* +//如何写一份可以提交的代码?以A+B为例 +#include <iostream> +using namespace std; +int main() +{ + int a, b; //定义两个变量名 + cin >> a >> b; //从标准输入流中输入两个整数 + cout << a + b << endl; //输出到标准输出流中 + return 0; +} +// 完成程序以后,点击下方的提交,即可看到测试结果 +*/ +#include<iostream> +#include<cstdio> +#include<cstdlib> +#include<cstring> +#include<algorithm> +using namespace std; + +int n,m,a,b,ans,p; + +int an[3100],head[3100],go[31000],nex[31000],use[3100]; + +void dfs(int a,int d) +{ + if (d==2) + { + + ans+=an[a]++; + return; + } + use[a]=1; + for (int i=head[a];i;i=nex[i]) + if (!use[go[i]]) dfs(go[i],d+1); + use[a]=0; +} + +void build(int a,int b) +{ + go[++p]=b; + nex[p]=head[a]; + head[a]=p; +} + +int main() +{ + + scanf("%d%d",&n,&m); + for (int i=1;i<=m;i++) + { + scanf("%d%d",&a,&b); + build(a,b); + } + for (int i=1;i<=n;i++) + { + for (int j=1;j<=n;j++) + an[j]=0; + dfs(i,0); + } + printf("%d\n",ans); + return 0; +} \ No newline at end of file diff --git a/pool/shard007/C++/0091479_general_loss_algorithm.cc b/pool/shard007/C++/0091479_general_loss_algorithm.cc new file mode 100644 index 0000000000000000000000000000000000000000..69623b0362a32de3abdbbc68d891b774f07ef7d3 --- /dev/null +++ b/pool/shard007/C++/0091479_general_loss_algorithm.cc @@ -0,0 +1,108 @@ +// 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. + +#include "net/quic/congestion_control/general_loss_algorithm.h" + +#include "net/quic/congestion_control/rtt_stats.h" +#include "net/quic/quic_bug_tracker.h" +#include "net/quic/quic_protocol.h" + +namespace net { + +namespace { + +// The minimum delay before a packet will be considered lost, +// regardless of SRTT. Half of the minimum TLP, since the loss algorithm only +// triggers when a nack has been receieved for the packet. +static const size_t kMinLossDelayMs = 5; + +// How many RTTs the algorithm waits before determining a packet is lost due +// to early retransmission or by time based loss detection. +static const double kLossDelayMultiplier = 1.25; + +} // namespace + +GeneralLossAlgorithm::GeneralLossAlgorithm() + : loss_type_(kNack), loss_detection_timeout_(QuicTime::Zero()) {} + +GeneralLossAlgorithm::GeneralLossAlgorithm(LossDetectionType loss_type) + : loss_type_(loss_type), loss_detection_timeout_(QuicTime::Zero()) {} + +LossDetectionType GeneralLossAlgorithm::GetLossDetectionType() const { + return loss_type_; +} + +// Uses nack counts to decide when packets are lost. +void GeneralLossAlgorithm::DetectLosses( + const QuicUnackedPacketMap& unacked_packets, + QuicTime time, + const RttStats& rtt_stats, + SendAlgorithmInterface::CongestionVector* packets_lost) { + const QuicPacketNumber largest_observed = unacked_packets.largest_observed(); + loss_detection_timeout_ = QuicTime::Zero(); + QuicTime::Delta loss_delay = QuicTime::Delta::Max( + QuicTime::Delta::FromMilliseconds(kMinLossDelayMs), + QuicTime::Delta::Max(rtt_stats.smoothed_rtt(), rtt_stats.latest_rtt()) + .Multiply(kLossDelayMultiplier)); + + QuicPacketNumber packet_number = unacked_packets.GetLeastUnacked(); + for (QuicUnackedPacketMap::const_iterator it = unacked_packets.begin(); + it != unacked_packets.end() && packet_number <= largest_observed; + ++it, ++packet_number) { + if (!it->in_flight) { + continue; + } + + // TODO(ianswett): Combine this and the time based detection for FACK. + if (loss_type_ == kTime) { + QuicTime when_lost = it->sent_time.Add(loss_delay); + if (time < when_lost) { + loss_detection_timeout_ = when_lost; + break; + } + packets_lost->push_back(std::make_pair(packet_number, it->bytes_sent)); + continue; + } + + // FACK based loss detection. + QUIC_BUG_IF(it->nack_count == 0 && it->sent_time.IsInitialized()) + << "All packets less than largest observed should have been nacked." + << " packet_number:" << packet_number + << " largest_observed:" << largest_observed; + if (it->nack_count >= kNumberOfNacksBeforeRetransmission) { + packets_lost->push_back(std::make_pair(packet_number, it->bytes_sent)); + continue; + } + + // NACK-based loss detection allows for a max reordering window of 1 RTT. + if (it->sent_time.Add(rtt_stats.smoothed_rtt()) < + unacked_packets.GetTransmissionInfo(largest_observed).sent_time) { + packets_lost->push_back(std::make_pair(packet_number, it->bytes_sent)); + continue; + } + + // Only early retransmit(RFC5827) when the last packet gets acked and + // there are retransmittable packets in flight. + // This also implements a timer-protected variant of FACK. + if (!it->retransmittable_frames.empty() && + unacked_packets.largest_sent_packet() == largest_observed) { + // Early retransmit marks the packet as lost once 1.25RTTs have passed + // since the packet was sent and otherwise sets an alarm. + if (time >= it->sent_time.Add(loss_delay)) { + packets_lost->push_back(std::make_pair(packet_number, it->bytes_sent)); + } else { + // Set the timeout for the earliest retransmittable packet where early + // retransmit applies. + loss_detection_timeout_ = it->sent_time.Add(loss_delay); + break; + } + } + } +} + +QuicTime GeneralLossAlgorithm::GetLossTimeout() const { + return loss_detection_timeout_; +} + +} // namespace net diff --git a/pool/shard007/C++/0091480_KaaTcpParser.cpp b/pool/shard007/C++/0091480_KaaTcpParser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..db0488f26c6a23c2f44b8ac54a43fb5ae1ad2cf9 --- /dev/null +++ b/pool/shard007/C++/0091480_KaaTcpParser.cpp @@ -0,0 +1,101 @@ +/* + * Copyright 2014 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "kaa/kaatcp/KaaTcpParser.hpp" +#include "kaa/logging/Log.hpp" +#include "kaa/logging/LoggingUtils.hpp" + +namespace kaa { + +void KaaTcpParser::onMessageDone() +{ + KAA_LOG_DEBUG("KaaTcp: payload is fully received"); + messages_.push_back(std::make_pair(messageType_, std::make_pair(messagePayload_, messageLength_))); + resetParser(); +} + +void KaaTcpParser::processByte(char byte) +{ + switch (state_) { + case KaaTcpParserState::NONE: + retrieveMessageType(byte); + KAA_LOG_DEBUG(boost::format("KaaTcp: retrieved message's type %1%") % (int) messageType_); + state_ = KaaTcpParserState::PROCESSING_LENGTH; + break; + case KaaTcpParserState::PROCESSING_LENGTH: + messageLength_ += ((std::uint8_t)byte & ~KaaTcpCommon::FIRST_BIT) * lenghtMultiplier_; + lenghtMultiplier_ *= KaaTcpCommon::FIRST_BIT; + if (!((std::uint8_t)byte & KaaTcpCommon::FIRST_BIT)) { + KAA_LOG_DEBUG(boost::format("KaaTcp: retrieved message's size %1%") % (std::uint32_t) messageLength_); + if (messageLength_) { + messagePayload_.reset(new char[messageLength_]); + state_ = KaaTcpParserState::PROCESSING_PAYLOAD; + } else { + onMessageDone(); + } + } + break; + default: + break; + } +} + +void KaaTcpParser::retrieveMessageType(char byte) +{ + messageType_ = (KaaTcpMessageType) ((std::uint8_t)(byte) >> 4); +} + +void KaaTcpParser::parseBuffer(const char *buffer, std::uint32_t size) +{ + auto cursor = buffer; + while (cursor != buffer + size) { + if (state_ == KaaTcpParserState::PROCESSING_PAYLOAD) { + std::uint32_t remainingSize = messageLength_ - processedPayloadLength_; + std::uint32_t bufferRemainingSize = buffer + size - cursor; + std::uint32_t bytesToRead = (remainingSize > bufferRemainingSize) ? bufferRemainingSize : remainingSize; + std::copy(cursor, cursor + bytesToRead, messagePayload_.get() + processedPayloadLength_); + cursor += bytesToRead; + processedPayloadLength_ += bytesToRead; + KAA_LOG_DEBUG(boost::format("KaaTcp: processed payload. Remaining buffer size is %1%") % ((buffer + size) - cursor)); + if (messageLength_ == processedPayloadLength_) { + onMessageDone(); + } + } else { + processByte(*(cursor++)); + } + } +} + +MessageRecordList KaaTcpParser::releaseMessages() +{ + MessageRecordList result = messages_; + messages_.clear(); + return result; +} + +void KaaTcpParser::resetParser() +{ + state_ = KaaTcpParserState::NONE; + messagePayload_.reset(); + messageLength_ = 0; + processedPayloadLength_ = 0; + messageType_ = KaaTcpMessageType::MESSAGE_UNKNOWN; + lenghtMultiplier_ = 1; +} + +} + + diff --git a/pool/shard007/C++/0091487_boss_drakkisath.cpp b/pool/shard007/C++/0091487_boss_drakkisath.cpp new file mode 100644 index 0000000000000000000000000000000000000000..43cfd6eac03093d8a96c893d9911022cce5840f3 --- /dev/null +++ b/pool/shard007/C++/0091487_boss_drakkisath.cpp @@ -0,0 +1,106 @@ +/* + * Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/> + * Copyright (C) 2010-2012 Oregon <http://www.oregoncore.com/> + * Copyright (C) 2006-2008 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> + * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +/* ScriptData +SDName: Boss_Drakkisath +SD%Complete: 100 +SDComment: +SDCategory: Blackrock Spire +EndScriptData */ + +#include "ScriptPCH.h" + +#define SPELL_FIRENOVA 23462 +#define SPELL_CLEAVE 20691 +#define SPELL_CONFLIGURATION 16805 +#define SPELL_THUNDERCLAP 15548 //Not sure if right ID. 23931 would be a harder possibility. + +struct boss_drakkisathAI : public ScriptedAI +{ + boss_drakkisathAI(Creature *c) : ScriptedAI(c) {} + + uint32 FireNova_Timer; + uint32 Cleave_Timer; + uint32 Confliguration_Timer; + uint32 Thunderclap_Timer; + + void Reset() + { + FireNova_Timer = 6000; + Cleave_Timer = 8000; + Confliguration_Timer = 15000; + Thunderclap_Timer = 17000; + } + + void EnterCombat(Unit * /*who*/) + { + } + + void UpdateAI(const uint32 diff) + { + //Return since we have no target + if (!UpdateVictim()) + return; + + //FireNova_Timer + if (FireNova_Timer <= diff) + { + DoCast(me->getVictim(), SPELL_FIRENOVA); + FireNova_Timer = 10000; + } else FireNova_Timer -= diff; + + //Cleave_Timer + if (Cleave_Timer <= diff) + { + DoCast(me->getVictim(), SPELL_CLEAVE); + Cleave_Timer = 8000; + } else Cleave_Timer -= diff; + + //Confliguration_Timer + if (Confliguration_Timer <= diff) + { + DoCast(me->getVictim(), SPELL_CONFLIGURATION); + Confliguration_Timer = 18000; + } else Confliguration_Timer -= diff; + + //Thunderclap_Timer + if (Thunderclap_Timer <= diff) + { + DoCast(me->getVictim(), SPELL_THUNDERCLAP); + Thunderclap_Timer = 20000; + } else Thunderclap_Timer -= diff; + + DoMeleeAttackIfReady(); + } +}; +CreatureAI* GetAI_boss_drakkisath(Creature* creature) +{ + return new boss_drakkisathAI (creature); +} + +void AddSC_boss_drakkisath() +{ + Script *newscript; + newscript = new Script; + newscript->Name = "boss_drakkisath"; + newscript->GetAI = &GetAI_boss_drakkisath; + newscript->RegisterSelf(); +} + diff --git a/pool/shard007/C++/0091490_TestLib.cpp b/pool/shard007/C++/0091490_TestLib.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f96ce4da097bfb69ba75c283d0a01c4c72b36bc2 --- /dev/null +++ b/pool/shard007/C++/0091490_TestLib.cpp @@ -0,0 +1,43 @@ +#include <iostream> +#include <cstring> + +#include "TestLib.h" + +using namespace std; +using namespace test; + +int test::runAllTests(char *filter) { + const std::vector<TestCase*> &testCases = TestCase::getCases(); + int tested = 0; + int passed = 0; + const char *prevFixture = ""; + + for (int i = 0; i < testCases.size(); i++) { + TestCase *tc = testCases[i]; + if (filter != NULL && strstr(tc->fixture, filter) == NULL && strstr(tc->name, filter) == NULL) { + // Test name does not pass filter + continue; + } + tested++; + if (strcmp(tc->fixture, prevFixture) != 0) { + if (strlen(prevFixture) != 0) { + cout << endl; + } + cout << tc->fixture << ":" << endl; + prevFixture = tc->fixture; + } + cout << "- " << tc->name << ": " << flush; + try { + tc->run(); + cout << "[OK]" << endl; + passed++; + } catch (TestFailedException &e) { + cout << "[FAILED]" << endl; + cout << " " << e.message << endl; + cout << " (" << e.file << ":" << e.line << ")" << endl; + } + } + + cout << endl << passed << " / " << tested << " tests passed." << endl; + return (passed == tested ? 0 : 1); +} diff --git a/pool/shard007/C++/0091499_paymentserver.cpp b/pool/shard007/C++/0091499_paymentserver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1e8ae890db35d27b71d8b517181ddecd20898c0b --- /dev/null +++ b/pool/shard007/C++/0091499_paymentserver.cpp @@ -0,0 +1,165 @@ +// Copyright (c) 2009-2012 The Bitcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include <QApplication> + +#include "paymentserver.h" + +#include "guiconstants.h" +#include "ui_interface.h" +#include "util.h" + +#include <QByteArray> +#include <QDataStream> +#include <QDebug> +#include <QFileOpenEvent> +#include <QHash> +#include <QLocalServer> +#include <QLocalSocket> +#include <QStringList> +#include <QUrl> + +using namespace boost; + +const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds +const QString BITCOIN_IPC_PREFIX("alexium:"); + +// +// Create a name that is unique for: +// testnet / non-testnet +// data directory +// +static QString ipcServerName() +{ + QString name("AlexiumQt"); + + // Append a simple hash of the datadir + // Note that GetDataDir(true) returns a different path + // for -testnet versus main net + QString ddir(GetDataDir(true).string().c_str()); + name.append(QString::number(qHash(ddir))); + + return name; +} + +// +// This stores payment requests received before +// the main GUI window is up and ready to ask the user +// to send payment. +// +static QStringList savedPaymentRequests; + +// +// Sending to the server is done synchronously, at startup. +// If the server isn't already running, startup continues, +// and the items in savedPaymentRequest will be handled +// when uiReady() is called. +// +bool PaymentServer::ipcSendCommandLine() +{ + bool fResult = false; + + const QStringList& args = qApp->arguments(); + for (int i = 1; i < args.size(); i++) + { + if (!args[i].startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) + continue; + savedPaymentRequests.append(args[i]); + } + + foreach (const QString& arg, savedPaymentRequests) + { + QLocalSocket* socket = new QLocalSocket(); + socket->connectToServer(ipcServerName(), QIODevice::WriteOnly); + if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT)) + return false; + + QByteArray block; + QDataStream out(&block, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_0); + out << arg; + out.device()->seek(0); + socket->write(block); + socket->flush(); + + socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT); + socket->disconnectFromServer(); + delete socket; + fResult = true; + } + return fResult; +} + +PaymentServer::PaymentServer(QApplication* parent) : QObject(parent), saveURIs(true) +{ + // Install global event filter to catch QFileOpenEvents on the mac (sent when you click bitcoin: links) + parent->installEventFilter(this); + + QString name = ipcServerName(); + + // Clean up old socket leftover from a crash: + QLocalServer::removeServer(name); + + uriServer = new QLocalServer(this); + + if (!uriServer->listen(name)) + qDebug() << tr("Cannot start alexium: click-to-pay handler"); + else + connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection())); +} + +bool PaymentServer::eventFilter(QObject *object, QEvent *event) +{ + // clicking on bitcoin: URLs creates FileOpen events on the Mac: + if (event->type() == QEvent::FileOpen) + { + QFileOpenEvent* fileEvent = static_cast<QFileOpenEvent*>(event); + if (!fileEvent->url().isEmpty()) + { + if (saveURIs) // Before main window is ready: + savedPaymentRequests.append(fileEvent->url().toString()); + else + emit receivedURI(fileEvent->url().toString()); + return true; + } + } + return false; +} + +void PaymentServer::uiReady() +{ + saveURIs = false; + foreach (const QString& s, savedPaymentRequests) + emit receivedURI(s); + savedPaymentRequests.clear(); +} + +void PaymentServer::handleURIConnection() +{ + QLocalSocket *clientConnection = uriServer->nextPendingConnection(); + + while (clientConnection->bytesAvailable() < (int)sizeof(quint32)) + clientConnection->waitForReadyRead(); + + connect(clientConnection, SIGNAL(disconnected()), + clientConnection, SLOT(deleteLater())); + + QDataStream in(clientConnection); + in.setVersion(QDataStream::Qt_4_0); + if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) { + return; + } + QString message; + in >> message; + + if (saveURIs) + savedPaymentRequests.append(message); + else + emit receivedURI(message); +} + +void PaymentServer::setOptionsModel(OptionsModel *optionsModel) +{ + this->optionsModel = optionsModel; +} diff --git a/pool/shard007/C++/0091504_hostconfig.cpp b/pool/shard007/C++/0091504_hostconfig.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1b965419d7108a0bb2c5de7763e957c6314a80c1 --- /dev/null +++ b/pool/shard007/C++/0091504_hostconfig.cpp @@ -0,0 +1,152 @@ +/* This file is part of the KDE project + Copyright (C) 2003 Simon Hausmann <hausmann@kde.org> + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "hostconfig.h" + +#include <kstringhandler.h> + +#include <netdb.h> + +using namespace KSim::Snmp; + +static int defaultSnmpPort() +{ + servent *ent = getservbyname( "snmp", 0 ); + if ( !ent ) + return 161; + return ent->s_port; +} + +bool HostConfig::load( KConfigBase &config ) +{ + name = config.readEntry( "Host" ); + if ( name.isEmpty() ) + return false; + + port = config.readNumEntry( "Port", defaultSnmpPort() ); + + bool ok = false; + version = stringToSnmpVersion( config.readEntry( "Version" ), &ok ); + if ( !ok ) + return false; + + if ( version != SnmpVersion3 ) { + community = config.readEntry( "Community" ); + return true; + } + + securityName = config.readEntry( "SecurityName" ); + + securityLevel = stringToSecurityLevel( config.readEntry( "SecurityLevel" ), &ok ); + if ( !ok ) + return false; + + if ( securityLevel == NoAuthPriv ) + return true; + + authentication.protocol = stringToAuthenticationProtocol( config.readEntry( "AuthType" ), &ok ); + if ( !ok ) + return false; + authentication.key = KStringHandler::obscure( config.readEntry( "AuthPassphrase" ) ); + + if ( securityLevel == AuthNoPriv ) + return true; + + privacy.protocol = stringToPrivacyProtocol( config.readEntry( "PrivType" ), &ok ); + if ( !ok ) + return false; + privacy.key = KStringHandler::obscure( config.readEntry( "PrivPassphrase" ) ); + + return true; +} + +void HostConfig::save( KConfigBase &config ) const +{ + if ( isNull() ) + return; + + config.writeEntry( "Host", name ); + if ( port != 0 ) + config.writeEntry( "Port", port ); + + config.writeEntry( "Version", snmpVersionToString( version ) ); + + if ( version != SnmpVersion3 ) { + writeIfNotEmpty( config, "Community", community ); + return; + } + + writeIfNotEmpty( config, "SecurityName", securityName ); + + config.writeEntry( "SecurityLevel", securityLevelToString( securityLevel ) ); + + if ( securityLevel == NoAuthPriv ) + return; + + writeIfNotEmpty( config, "AuthType", authenticationProtocolToString( authentication.protocol ) ); + writeIfNotEmpty( config, "AuthPassphrase", KStringHandler::obscure( authentication.key ) ); + + if ( securityLevel == AuthNoPriv ) + return; + + writeIfNotEmpty( config, "PrivType", privacyProtocolToString( privacy.protocol ) ); + writeIfNotEmpty( config, "PrivPassphrase", KStringHandler::obscure( privacy.key ) ); +} + +void HostConfig::writeIfNotEmpty( KConfigBase &config, const QString &name, const QString &value ) +{ + if ( value.isEmpty() ) + return; + + config.writeEntry( name, value ); +} + +void HostConfigMap::load( KConfigBase &config, const QStringList &hosts ) +{ + clear(); + + for ( QStringList::ConstIterator it = hosts.begin(); it != hosts.end(); ++it ) { + config.setGroup( "Host " + *it ); + + HostConfig src; + if ( !src.load( config ) ) + continue; + + insert( *it, src ); + } +} + +QStringList HostConfigMap::save( KConfigBase &config ) const +{ + QStringList hostList; + + for ( ConstIterator it = begin(); it != end(); ++it ) { + QString host = it.key(); + + hostList << host; + + config.setGroup( "Host " + host ); + ( *it ).save( config ); + } + + return hostList; +} + +/* vim: et sw=4 ts=4 + */ diff --git a/pool/shard007/C++/0091511_server_request_call_test.cc b/pool/shard007/C++/0091511_server_request_call_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..9831c0617664f665bb9ad45a35e8479e65dc6af8 --- /dev/null +++ b/pool/shard007/C++/0091511_server_request_call_test.cc @@ -0,0 +1,163 @@ +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <thread> + +#include <grpcpp/impl/codegen/config.h> + +#include <grpcpp/server.h> +#include <grpcpp/server_builder.h> + +#include <grpcpp/create_channel.h> +#include <grpcpp/security/credentials.h> + +#include <grpc/support/log.h> + +#include "src/proto/grpc/testing/echo.grpc.pb.h" +#include "test/core/util/port.h" + +#include <gtest/gtest.h> + +namespace grpc { +namespace { + +TEST(ServerRequestCallTest, ShortDeadlineDoesNotCauseOkayFalse) { + std::mutex mu; + bool shutting_down = false; + + // grpc server config. + std::ostringstream s; + int p = grpc_pick_unused_port_or_die(); + s << "[::1]:" << p; + const string address = s.str(); + testing::EchoTestService::AsyncService service; + ServerBuilder builder; + builder.AddListeningPort(address, InsecureServerCredentials()); + auto cq = builder.AddCompletionQueue(); + builder.RegisterService(&service); + auto server = builder.BuildAndStart(); + + // server thread. + std::thread t([address, &service, &cq, &mu, &shutting_down] { + for (int n = 0; true; n++) { + ServerContext ctx; + testing::EchoRequest req; + ServerAsyncResponseWriter<testing::EchoResponse> responder(&ctx); + + // if shutting down, don't enqueue a new request. + { + std::lock_guard<std::mutex> lock(mu); + if (!shutting_down) { + service.RequestEcho(&ctx, &req, &responder, cq.get(), cq.get(), + (void*)1); + } + } + + bool ok; + void* tag; + if (!cq->Next(&tag, &ok)) { + break; + } + + EXPECT_EQ((void*)1, tag); + // If not shutting down, ok must be true for new requests. + { + std::lock_guard<std::mutex> lock(mu); + if (!shutting_down && !ok) { + gpr_log(GPR_INFO, "!ok on request %d", n); + abort(); + } + if (shutting_down && !ok) { + // Failed connection due to shutdown, continue flushing the CQ. + continue; + } + } + + // Send a simple response after a small delay that would ensure the client + // deadline is exceeded. + gpr_log(GPR_INFO, "Got request %d", n); + testing::EchoResponse response; + response.set_message("foobar"); + // A bit of sleep to make sure the deadline elapses. + gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC), + gpr_time_from_millis(50, GPR_TIMESPAN))); + { + std::lock_guard<std::mutex> lock(mu); + if (shutting_down) { + gpr_log(GPR_INFO, + "shut down while processing call, not calling Finish()"); + // Continue flushing the CQ. + continue; + } + gpr_log(GPR_INFO, "Finishing request %d", n); + responder.Finish(response, grpc::Status::OK, (void*)2); + if (!cq->Next(&tag, &ok)) { + break; + } + EXPECT_EQ((void*)2, tag); + } + } + }); + + auto stub = testing::EchoTestService::NewStub( + CreateChannel(address, InsecureChannelCredentials())); + + for (int i = 0; i < 100; i++) { + gpr_log(GPR_INFO, "Sending %d.", i); + testing::EchoRequest request; + + ///////// + // Comment out the following line to get ok=false due to invalid request. + // Otherwise, ok=false due to deadline being exceeded. + ///////// + request.set_message("foobar"); + + // A simple request with a short deadline. The server will always exceed the + // deadline, whether due to the sleep or because the server was unable to + // even fetch the request from the CQ before the deadline elapsed. + testing::EchoResponse response; + ::grpc::ClientContext ctx; + ctx.set_fail_fast(false); + ctx.set_deadline(std::chrono::system_clock::now() + + std::chrono::milliseconds(1)); + grpc::Status status = stub->Echo(&ctx, request, &response); + EXPECT_EQ(DEADLINE_EXCEEDED, status.error_code()); + gpr_log(GPR_INFO, "Success."); + } + gpr_log(GPR_INFO, "Done sending RPCs."); + + // Shut down everything properly. + gpr_log(GPR_INFO, "Shutting down."); + { + std::lock_guard<std::mutex> lock(mu); + shutting_down = true; + } + server->Shutdown(); + cq->Shutdown(); + server->Wait(); + + t.join(); +} + +} // namespace +} // namespace grpc + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/pool/shard007/C++/0091513_adjlist_build_test.cpp b/pool/shard007/C++/0091513_adjlist_build_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c0919419355b24a2805ce41c387c623a062a197c --- /dev/null +++ b/pool/shard007/C++/0091513_adjlist_build_test.cpp @@ -0,0 +1,245 @@ +// Copyright (C) 2007 Douglas Gregor + +// Use, modification and distribution is subject to the Boost Software +// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +#include <boost/graph/use_mpi.hpp> +#include <boost/config.hpp> +#include <boost/throw_exception.hpp> +#include <boost/graph/distributed/adjacency_list.hpp> +#include <boost/graph/distributed/mpi_process_group.hpp> +#include <boost/test/minimal.hpp> +#include <boost/random/linear_congruential.hpp> +#include <boost/graph/erdos_renyi_generator.hpp> +#include <boost/lexical_cast.hpp> +#include <ctime> + +using namespace boost; +using boost::graph::distributed::mpi_process_group; + +#ifdef BOOST_NO_EXCEPTIONS +void +boost::throw_exception(std::exception const& ex) +{ + std::cout << ex.what() << std::endl; + abort(); +} +#endif + + +int test_main(int argc, char** argv) +{ + boost::mpi::environment env(argc, argv); + + int n = 10000; + double p = 3e-3; + int seed = std::time(0); + int immediate_response_percent = 10; + + if (argc > 1) n = lexical_cast<int>(argv[1]); + if (argc > 2) p = lexical_cast<double>(argv[2]); + if (argc > 3) seed = lexical_cast<int>(argv[3]); + + typedef adjacency_list<listS, + distributedS<mpi_process_group, vecS>, + bidirectionalS> Graph; + + mpi_process_group pg; + int rank = process_id(pg); + int numprocs = num_processes(pg); + bool i_am_root = rank == 0; + + // broadcast the seed + broadcast(pg, seed, 0); + + // Random number generator + minstd_rand gen; + minstd_rand require_response_gen; + + if (i_am_root) { + std::cout << "n = " << n << ", p = " << p << ", seed = " << seed + << "\nBuilding graph with the iterator constructor... "; + std::cout.flush(); + } + + // Build a graph using the iterator constructor, where each of the + // processors has exactly the same information. + gen.seed(seed); + Graph g1(erdos_renyi_iterator<minstd_rand, Graph>(gen, n, p), + erdos_renyi_iterator<minstd_rand, Graph>(), + n, pg, Graph::graph_property_type()); + // NGE: Grrr, the default graph property is needed to resolve an + // ambiguous overload in the adjaceny list constructor + + // Build another, identical graph using add_edge + if (i_am_root) { + std::cout << "done.\nBuilding graph with add_edge from the root..."; + std::cout.flush(); + } + + gen.seed(seed); + require_response_gen.seed(1); + Graph g2(n, pg); + if (i_am_root) { + // The root will add all of the edges, some percentage of which + // will require an immediate response from the owner of the edge. + for (erdos_renyi_iterator<minstd_rand, Graph> first(gen, n, p), last; + first != last; ++first) { + Graph::lazy_add_edge lazy + = add_edge(vertex(first->first, g2), vertex(first->second, g2), g2); + + if (require_response_gen() % 100 < immediate_response_percent) { + // Send out-of-band to require a response + std::pair<graph_traits<Graph>::edge_descriptor, bool> result(lazy); + BOOST_CHECK(source(result.first, g2) == vertex(first->first, g2)); + BOOST_CHECK(target(result.first, g2) == vertex(first->second, g2)); + } + } + } + + if (i_am_root) { + std::cout << "synchronizing..."; + std::cout.flush(); + } + + synchronize(g2); + + // Verify that the two graphs are indeed identical. + if (i_am_root) { + std::cout << "done.\nVerifying graphs..."; + std::cout.flush(); + } + + // Check the number of vertices + if (num_vertices(g1) != num_vertices(g2)) { + std::cerr << g1.processor() << ": g1 has " << num_vertices(g1) + << " vertices, g2 has " << num_vertices(g2) << " vertices.\n"; + communicator(pg).abort(-1); + } + + // Check the number of edges + if (num_edges(g1) != num_edges(g2)) { + std::cerr << g1.processor() << ": g1 has " << num_edges(g1) + << " edges, g2 has " << num_edges(g2) << " edges.\n"; + communicator(pg).abort(-1); + } + + // Check the in-degree and out-degree of each vertex + graph_traits<Graph>::vertex_iterator vfirst1, vlast1, vfirst2, vlast2; + boost::tie(vfirst1, vlast1) = vertices(g1); + boost::tie(vfirst2, vlast2) = vertices(g2); + for(; vfirst1 != vlast1 && vfirst2 != vlast2; ++vfirst1, ++vfirst2) { + if (out_degree(*vfirst1, g1) != out_degree(*vfirst2, g2)) { + std::cerr << g1.processor() << ": out-degree mismatch (" + << out_degree(*vfirst1, g1) << " vs. " + << out_degree(*vfirst2, g2) << ").\n"; + communicator(pg).abort(-1); + } + + if (in_degree(*vfirst1, g1) != in_degree(*vfirst2, g2)) { + std::cerr << g1.processor() << ": in-degree mismatch (" + << in_degree(*vfirst1, g1) << " vs. " + << in_degree(*vfirst2, g2) << ").\n"; + communicator(pg).abort(-1); + } + } + + // TODO: Check the actual edge targets + + // Build another, identical graph using add_edge + if (i_am_root) { + std::cout << "done.\nBuilding graph with add_edge from everywhere..."; + std::cout.flush(); + } + + gen.seed(seed); + require_response_gen.seed(1); + Graph g3(n, pg); + + { + // Each processor will take a chunk of incoming edges and add + // them. Some percentage of the edge additions will require an + // immediate response from the owner of the edge. This should + // create a lot of traffic when building the graph, but should + // produce a graph identical to the other graphs. + typedef graph_traits<Graph>::edges_size_type edges_size_type; + + erdos_renyi_iterator<minstd_rand, Graph> first(gen, n, p); + edges_size_type chunk_size = edges_size_type(p*n*n)/numprocs; + edges_size_type start = chunk_size * rank; + edges_size_type remaining_edges = + (rank < numprocs - 1? chunk_size + : edges_size_type(p*n*n) - start); + + // Spin the generator to the first edge we're responsible for + for (; start; ++first, --start) ; + + for (; remaining_edges; --remaining_edges, ++first) { + Graph::lazy_add_edge lazy + = add_edge(vertex(first->first, g3), vertex(first->second, g3), g3); + + if (require_response_gen() % 100 < immediate_response_percent) { + // Send out-of-band to require a response + std::pair<graph_traits<Graph>::edge_descriptor, bool> result(lazy); + BOOST_CHECK(source(result.first, g3) == vertex(first->first, g3)); + BOOST_CHECK(target(result.first, g3) == vertex(first->second, g3)); + } + } + } + + if (i_am_root) { + std::cout << "synchronizing..."; + std::cout.flush(); + } + + synchronize(g3); + + // Verify that the two graphs are indeed identical. + if (i_am_root) { + std::cout << "done.\nVerifying graphs..."; + std::cout.flush(); + } + + // Check the number of vertices + if (num_vertices(g1) != num_vertices(g3)) { + std::cerr << g1.processor() << ": g1 has " << num_vertices(g1) + << " vertices, g3 has " << num_vertices(g3) << " vertices.\n"; + communicator(pg).abort(-1); + } + + // Check the number of edges + if (num_edges(g1) != num_edges(g3)) { + std::cerr << g1.processor() << ": g1 has " << num_edges(g1) + << " edges, g3 has " << num_edges(g3) << " edges.\n"; + communicator(pg).abort(-1); + } + + // Check the in-degree and out-degree of each vertex + boost::tie(vfirst1, vlast1) = vertices(g1); + boost::tie(vfirst2, vlast2) = vertices(g3); + for(; vfirst1 != vlast1 && vfirst2 != vlast2; ++vfirst1, ++vfirst2) { + if (out_degree(*vfirst1, g1) != out_degree(*vfirst2, g3)) { + std::cerr << g1.processor() << ": out-degree mismatch (" + << out_degree(*vfirst1, g1) << " vs. " + << out_degree(*vfirst2, g3) << ").\n"; + communicator(pg).abort(-1); + } + + if (in_degree(*vfirst1, g1) != in_degree(*vfirst2, g3)) { + std::cerr << g1.processor() << ": in-degree mismatch (" + << in_degree(*vfirst1, g1) << " vs. " + << in_degree(*vfirst2, g3) << ").\n"; + communicator(pg).abort(-1); + } + } + + // TODO: Check the actual edge targets + + if (i_am_root) { + std::cout << "done.\n"; + std::cout.flush(); + } + + return 0; +} diff --git a/pool/shard007/C++/0091516_flow_fun.cpp b/pool/shard007/C++/0091516_flow_fun.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2fa34211633744a586897efd698cd3ff7b37dd18 --- /dev/null +++ b/pool/shard007/C++/0091516_flow_fun.cpp @@ -0,0 +1,59 @@ +/* file "bvd/flow_fun.cpp" */ + +/* + Copyright (c) 2000 The President and Fellows of Harvard College + + All rights reserved. + + This software is provided under the terms described in + the "machine/copyright.h" include file. +*/ + +#include <machine/copyright.h> + +#ifdef USE_PRAGMA_INTERFACE +#pragma implementation "bvd/flow_fun.h" +#endif + +#include <bvd/flow_fun.h> + +#ifdef USE_DMALLOC +#include <dmalloc.h> +#define new D_NEW +#endif + +FlowFun::FlowFun(int num_slots_hint) + : _id(false, num_slots_hint), _cs(false, num_slots_hint) +{ + // set up identity function on bit vectors + _id.insert_all(); + _cs.remove_all(); +} + +FlowFun::FlowFun(const FlowFun &other) +{ + _id = other._id; + _cs = other._cs; +} + +void +FlowFun::operator=(const FlowFun &other) +{ + _id = other._id; + _cs = other._cs; +} + +void +FlowFun::print(int bound, FILE *fp) { + + putc('{', fp); + + for (int i = 0; i < bound; i++) { + if (!_id.contains(i)) + fprintf(fp, "%s", (_cs.contains(i) ? "1" : "0")); + else + fprintf(fp, "%s", (_cs.contains(i) ? "x" : "i")); + } + + putc('}', fp); +} diff --git a/pool/shard007/C++/0091519_AppDelegate.cpp b/pool/shard007/C++/0091519_AppDelegate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..96b463a53d9abe9e4dba45a7de1f5c3248289e52 --- /dev/null +++ b/pool/shard007/C++/0091519_AppDelegate.cpp @@ -0,0 +1,100 @@ +#include "AppDelegate.h" +#include "MainScene.h" + +USING_NS_CC; + +static cocos2d::Size designResolutionSize = cocos2d::Size(480, 320); +static cocos2d::Size smallResolutionSize = cocos2d::Size(480, 320); +static cocos2d::Size mediumResolutionSize = cocos2d::Size(1024, 768); +static cocos2d::Size largeResolutionSize = cocos2d::Size(2048, 1536); + +AppDelegate::AppDelegate() +{ +} + +AppDelegate::~AppDelegate() +{ +} + +//if you want a different context,just modify the value of glContextAttrs +//it will takes effect on all platforms +void AppDelegate::initGLContextAttrs() +{ + //set OpenGL context attributions,now can only set six attributions: + //red,green,blue,alpha,depth,stencil + GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8}; + + GLView::setGLContextAttrs(glContextAttrs); +} + +// If you want to use packages manager to install more packages, +// don't modify or remove this function +static int register_all_packages() +{ + return 0; //flag for packages manager +} + +bool AppDelegate::applicationDidFinishLaunching() { + // initialize director + auto director = Director::getInstance(); + auto glview = director->getOpenGLView(); + if(!glview) { +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) + glview = GLViewImpl::createWithRect("cocotest", Rect(0, 0, 480, 320)); +#else + glview = GLViewImpl::create("cocotest"); +#endif + director->setOpenGLView(glview); + } + + // turn on display FPS + director->setDisplayStats(false); + + // set FPS. the default value is 1.0/60 if you don't call this + director->setAnimationInterval(1.0 / 60); + + // Set the design resolution + glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::NO_BORDER); + Size frameSize = glview->getFrameSize(); + // if the frame's height is larger than the height of medium size. + if (frameSize.height > mediumResolutionSize.height) + { + director->setContentScaleFactor(MIN(largeResolutionSize.height/designResolutionSize.height, largeResolutionSize.width/designResolutionSize.width)); + } + // if the frame's height is larger than the height of small size. + else if (frameSize.height > smallResolutionSize.height) + { + director->setContentScaleFactor(MIN(mediumResolutionSize.height/designResolutionSize.height, mediumResolutionSize.width/designResolutionSize.width)); + } + // if the frame's height is smaller than the height of medium size. + else + { + director->setContentScaleFactor(MIN(smallResolutionSize.height/designResolutionSize.height, smallResolutionSize.width/designResolutionSize.width)); + } + + register_all_packages(); + + // create a scene. it's an autorelease object + auto scene = MainScene::createScene(); + + // run + director->runWithScene(scene); + + return true; +} + +// This function will be called when the app is inactive. When comes a phone call,it's be invoked too +void AppDelegate::applicationDidEnterBackground() { + Director::getInstance()->stopAnimation(); + + // if you use SimpleAudioEngine, it must be pause + // SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); +} + +// this function will be called when the app is active again +void AppDelegate::applicationWillEnterForeground() { + Director::getInstance()->startAnimation(); + + // if you use SimpleAudioEngine, it must resume here + // SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); +} diff --git a/pool/shard007/C++/0091523_BillboardGob.cpp b/pool/shard007/C++/0091523_BillboardGob.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d210e90316f3a69a193634f9e8a3dfe94be5969a --- /dev/null +++ b/pool/shard007/C++/0091523_BillboardGob.cpp @@ -0,0 +1,72 @@ +//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt. + +#include "BillboardGob.h" + + +#include "../Renderer/ShapeLib.h" +#include "../Renderer/RenderBuffer.h" +#include "../Renderer/Model.h" +#include "../VectorMath/Camera.h" + + +namespace LvEdEngine +{ + +// --------------------------------------------------------------------------------------------- +// push Renderable nodes +//virtual +bool BillboardGob::GetRenderables(RenderableNodeCollector* collector, RenderContext* context) +{ + if ( !IsVisible(context->Cam().GetFrustum()) ) + { + return false; + } + + + RenderableNode renderable; + SetupRenderable(&renderable, context); + + // // test + //Mesh* quad = ShapeLibGetMesh(RenderShape::Quad); + //m_localBounds = quad->bounds; + //m_bounds = m_localBounds; + //m_bounds.Transform(m_world); + //renderable.bounds = m_bounds; + //renderable.mesh = quad; + //renderable.WorldXform = m_world; + //// end of test + + + RenderFlagsEnum flags = RenderFlags::Textured; + collector->Add( renderable, flags, Shaders::BillboardShader ); + return true; +} + +// --------------------------------------------------------------------------------------------- +void BillboardGob::SetupRenderable(RenderableNode* r, RenderContext* context) +{ + Matrix billboard = m_world; + { + float sx = length( float3(&m_world.M11) ); + float sy = length( float3(&m_world.M21) ); + float sz = length( float3(&m_world.M31) ); + Matrix scaleM = Matrix::CreateScale(sx,sy,sz); + + float3 objectPos = &m_world.M41; + Camera& cam = context->Cam(); + Matrix b = Matrix::CreateBillboard(objectPos,cam.CamPos(),cam.CamUp(),cam.CamLook()); + billboard = scaleM * b; + } + + PrimitiveShapeGob::SetupRenderable(r, context); + r->WorldXform = billboard; + r->diffuse = float4(m_intensity, m_intensity, m_intensity, m_intensity); + + // special case compute AABB + m_localBounds = AABB(float3(-0.5f,-0.5f,-0.5f),float3(0.5f,0.5f,0.5f)); + m_bounds = m_localBounds; + m_bounds.Transform(billboard); + r->bounds = m_bounds; +} + +}; // namespace diff --git a/pool/shard007/C++/0091525_CWE415_Double_Free__new_delete_int64_t_52a.cpp b/pool/shard007/C++/0091525_CWE415_Double_Free__new_delete_int64_t_52a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cd51eb2a780fa42158c0daf8b2498edb88a3c7ca --- /dev/null +++ b/pool/shard007/C++/0091525_CWE415_Double_Free__new_delete_int64_t_52a.cpp @@ -0,0 +1,108 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE415_Double_Free__new_delete_int64_t_52a.cpp +Label Definition File: CWE415_Double_Free__new_delete.label.xml +Template File: sources-sinks-52a.tmpl.cpp +*/ +/* + * @description + * CWE: 415 Double Free + * BadSource: Allocate data using new and Deallocae data using delete + * GoodSource: Allocate data using new + * Sinks: + * GoodSink: do nothing + * BadSink : Deallocate data using delete + * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files + * + * */ + +#include "std_testcase.h" + +#include <wchar.h> + +namespace CWE415_Double_Free__new_delete_int64_t_52 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink_b(int64_t * data); + +void bad() +{ + int64_t * data; + /* Initialize data */ + data = NULL; + data = new int64_t; + /* POTENTIAL FLAW: delete data in the source - the bad sink deletes data as well */ + delete data; + badSink_b(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink_b(int64_t * data); + +static void goodG2B() +{ + int64_t * data; + /* Initialize data */ + data = NULL; + data = new int64_t; + /* FIX: Do NOT delete data in the source - the bad sink deletes data */ + goodG2BSink_b(data); +} + +/* goodB2G uses the BadSource with the GoodSink */ +void goodB2GSink_b(int64_t * data); + +static void goodB2G() +{ + int64_t * data; + /* Initialize data */ + data = NULL; + data = new int64_t; + /* POTENTIAL FLAW: delete data in the source - the bad sink deletes data as well */ + delete data; + goodB2GSink_b(data); +} + +void good() +{ + goodG2B(); + goodB2G(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +using namespace CWE415_Double_Free__new_delete_int64_t_52; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard007/C++/0091526_tod.cpp b/pool/shard007/C++/0091526_tod.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3428aaa2c8d3d022f55c95edfa1dc2810b49f59a --- /dev/null +++ b/pool/shard007/C++/0091526_tod.cpp @@ -0,0 +1,198 @@ +/* + * This file is part of libsidplayfp, a SID player engine. + * + * Copyright 2011-2014 Leandro Nini <drfiemost@users.sourceforge.net> + * Copyright 2009-2014 VICE Project + * Copyright 2007-2010 Antti Lankila + * Copyright 2000 Simon White + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#include "tod.h" + +#include <cstring> + +#include "mos6526.h" + +void Tod::reset() +{ + cycles = 0; + + memset(clock, 0, sizeof(clock)); + clock[HOURS] = 1; // the most common value + memcpy(latch, clock, sizeof(latch)); + memset(alarm, 0, sizeof(alarm)); + + isLatched = false; + isStopped = true; + + event_context.schedule(*this, 0, EVENT_CLOCK_PHI1); +} + +uint8_t Tod::read(uint_least8_t reg) +{ + // TOD clock is latched by reading Hours, and released + // upon reading Tenths of Seconds. The counter itself + // keeps ticking all the time. + // Also note that this latching is different from the input one. + if (!isLatched) + memcpy(latch, clock, sizeof(latch)); + + if (reg == TENTHS) + isLatched = false; + else if (reg == HOURS) + isLatched = true; + + return latch[reg]; +} + +void Tod::write(uint_least8_t reg, uint8_t data) +{ + switch (reg) + { + case TENTHS: // Time Of Day clock 1/10 s + data &= 0x0f; + break; + case SECONDS: // Time Of Day clock sec + // deliberate run on + case MINUTES: // Time Of Day clock min + data &= 0x7f; + break; + case HOURS: // Time Of Day clock hour + // force bits 6-5 = 0 + data &= 0x9f; + // Flip AM/PM on hour 12 + // Flip AM/PM only when writing time, not when writing alarm + if ((data & 0x1f) == 0x12 && !(crb & 0x80)) + data ^= 0x80; + break; + } + + if (crb & 0x80) + { + // set alarm + alarm[reg] = data; + } + else + { + // set time + if (reg == TENTHS) + isStopped = false; + else if (reg == HOURS) + isStopped = true; + + clock[reg] = data; + } + + // check alarm + if (!isStopped) + { + checkAlarm(); + } +} + +void Tod::event() +{ + // Reload divider according to 50/60 Hz flag + // Only performed on expiry according to Frodo + cycles += period * (cra & 0x80 ? 5 : 6); + + // Fixed precision 25.7 + event_context.schedule(*this, cycles >> 7); + cycles &= 0x7F; // Just keep the decimal part + + if (!isStopped) + { + // advance the counters. + // - individual counters are all 4 bit + uint8_t t0 = clock[TENTHS] & 0x0f; + uint8_t t1 = clock[SECONDS] & 0x0f; + uint8_t t2 = (clock[SECONDS] >> 4) & 0x0f; + uint8_t t3 = clock[MINUTES] & 0x0f; + uint8_t t4 = (clock[MINUTES] >> 4) & 0x0f; + uint8_t t5 = clock[HOURS] & 0x0f; + uint8_t t6 = (clock[HOURS] >> 4) & 0x01; + uint8_t pm = clock[HOURS] & 0x80; + + // tenth seconds (0-9) + t0 = (t0 + 1) & 0x0f; + if (t0 == 10) + { + t0 = 0; + // seconds (0-59) + t1 = (t1 + 1) & 0x0f; // x0...x9 + if (t1 == 10) + { + t1 = 0; + t2 = (t2 + 1) & 0x07; // 0x...5x + if (t2 == 6) + { + t2 = 0; + // minutes (0-59) + t3 = (t3 + 1) & 0x0f; // x0...x9 + if (t3 == 10) + { + t3 = 0; + t4 = (t4 + 1) & 0x07; // 0x...5x + if (t4 == 6) + { + t4 = 0; + // hours (1-12) + t5 = (t5 + 1) & 0x0f; + if (t6) + { + // toggle the am/pm flag when going from 11 to 12 (!) + if (t5 == 2) + { + pm ^= 0x80; + } + // wrap 12h -> 1h (FIXME: when hour became x3 ?) + if (t5 == 3) + { + t5 = 1; + t6 = 0; + } + } + else + { + if (t5 == 10) + { + t5 = 0; + t6 = 1; + } + } + } + } + } + } + } + + clock[TENTHS] = t0; + clock[SECONDS] = t1 | (t2 << 4); + clock[MINUTES] = t3 | (t4 << 4); + clock[HOURS] = t5 | (t6 << 4) | pm; + + checkAlarm(); + } +} + +void Tod::checkAlarm() +{ + if (!memcmp(alarm, clock, sizeof(alarm))) + { + parent->todInterrupt(); + } +} diff --git a/pool/shard007/C++/0091527_helper.cpp b/pool/shard007/C++/0091527_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c7cdf8ad7f8d582fb060ba07e4e6115d6063a789 --- /dev/null +++ b/pool/shard007/C++/0091527_helper.cpp @@ -0,0 +1,248 @@ +#include "helper.h" +#include "rect.h" +#include "point.h" +#include "pixmap.h" +#include "font.h" +#include "core_imp.h" +#include "SkRect.h" +#include "SkBitmap.h" +#include "SkPixelRef.h" +#include "SkPaint.h" +#include "SkTypeface.h" + + +namespace bones +{ + + +Rect Helper::ToRect(const RECT & wr) +{ + return Rect::MakeLTRB(static_cast<Scalar>(wr.left), + static_cast<Scalar>(wr.top), + static_cast<Scalar>(wr.right), + static_cast<Scalar>(wr.bottom)); +} + +Point Helper::ToPoint(const POINT & wp) +{ + return Point::Make(static_cast<Scalar>(wp.x), + static_cast<Scalar>(wp.y)); +} + +SkRect Helper::ToSkRect(const Rect & rect) +{ + SkRect r; + r.setLTRB(rect.left(), rect.top(), rect.right(), rect.bottom()); + return r; +} + +SkIRect Helper::ToSkIRect(const Rect & rect) +{ + SkIRect r; + r.setLTRB(static_cast<int>(rect.left()), + static_cast<int>(rect.top()), + static_cast<int>(rect.right()), + static_cast<int>(rect.bottom())); + return r; +} + +SkPoint Helper::ToSkPoint(const Point & pt) +{ + SkPoint p; + p.set(pt.x(), pt.y()); + return p; +} + +SkBitmap Helper::ToSkBitmap(Pixmap & pm) +{ + SkBitmap bitmap; + SkBitmap subset; + if (pm.isValid()) + { + bitmap.setConfig(pm.pixel_ref_->info(), pm.pixel_ref_->rowBytes()); + bitmap.setPixelRef(pm.pixel_ref_); + bitmap.extractSubset(&subset, ToSkIRect(pm.subset_)); + } + return subset; +} + +void Helper::ToSkPaint(const Font & font, SkPaint & paint) +{ + auto style = font.getStyle(); + paint.setTextSize(font.getSize()); + paint.setTextEncoding(SkPaint::kUTF16_TextEncoding); + paint.setAntiAlias(Core::AntiAliasEnable()); + //paint.setDistanceFieldTextTEMP(true); + paint.setUnderlineText(!!(style & Font::kUnderline)); + paint.setStrikeThruText(!!(style & Font::kStrikeOut)); + + bool bold = !!(Font::kBold & style); + bool italic = !!(Font::kItalic & style); + + SkTypeface::Style st = SkTypeface::kNormal; + if (bold && italic) + st = SkTypeface::kBoldItalic; + else if (bold) + st = SkTypeface::kBold; + else if (italic) + st = SkTypeface::kItalic; + + SkTypeface * type_face = SkTypeface::CreateFromName(font.getFamily(), st); + if (type_face) + { + paint.setTypeface(type_face); + type_face->unref(); + } +} + +POINT Helper::ToPoint(const Point & pt) +{ + POINT wp; + wp.x = static_cast<LONG>(pt.x()); + wp.y = static_cast<LONG>(pt.y()); + return wp; +} + +RECT Helper::ToRect(const Rect & r) +{ + RECT wr; + wr.left = static_cast<LONG>(r.left()); + wr.top = static_cast<LONG>(r.top()); + wr.right = static_cast<LONG>(r.right()); + wr.bottom = static_cast<LONG>(r.bottom()); + return wr; +} + +HBITMAP Helper::ToHBITMAP(const Surface & sf) +{ + if (sf.hbm_) + return sf.hbm_; + return NULL; +} + +HMODULE Helper::GetModule() +{ + + DWORD flags = GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT | + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS; + HMODULE module = 0; + GetModuleHandleEx(flags, (LPCWSTR)_ReturnAddress(), &module); + return module; +} + +std::string Helper::JoinPath(const char ** path, int count) +{ + if (!path || !count) + return ""; + std::string paths; + for (auto i = 0; i < count; ++i) + { + if (nullptr == path[i]) + break; + + if (0 == i) + { + paths = path[0]; + continue; + } + //如果path 末尾不是斜杆 那么加1个斜杆 + char last_char = paths[paths.length() - 1]; + if ('\\' != last_char || '/' != last_char) + paths.append("\\"); + paths.append(path[i]); + } + return paths; +} + +std::string Helper::GetPathFromFullName(const char * fullname) +{ + std::string path; + auto last_backslash = std::strrchr(fullname, '\\'); + auto last_slash = std::strrchr(fullname, '/'); + auto slash = last_backslash > last_slash ? last_backslash : last_slash; + if (!slash) + return path; + return path.assign(fullname, slash - fullname); +} + +uint64_t Helper::GetTickCount() +{ + typedef ULONGLONG(WINAPI *TGetTickCount64)(); + typedef DWORD(WINAPI *TGetTickCount32)(); + + static FARPROC tf = nullptr; + static bool support_64 = false; + if (!tf) + { + tf = GetProcAddress(GetModuleHandle(L"kernel32.dll"), "GetTickCount64"); + support_64 = true; + if (!tf) + tf = GetProcAddress(GetModuleHandle(L"kernel32.dll"), "GetTickCount"); + + assert(tf); + } + if (!tf) + return 0; + return support_64 ? ((TGetTickCount64)tf)() : ((TGetTickCount32)tf)(); +} + + +WPARAM Helper::ToKeyStateForMouse(int flags) +{ + WPARAM wp = 0; + + if (flags & kEF_LEFT_MOUSE_DOWN) + wp |= MK_LBUTTON; + if (flags & kEF_RIGHT_MOUSE_DOWN) + wp |= MK_RBUTTON; + if (flags & kEF_MIDDLE_MOUSE_DOWN) + wp |= MK_MBUTTON; + if (flags & kEF_CONTROL_DOWN) + wp |= MK_CONTROL; + if (flags & kEF_SHIFT_DOWN) + wp |= MK_SHIFT; + return wp; +} + +LPARAM Helper::ToCoordinateForMouse(const Point & pt) +{ + return MAKELPARAM(pt.x(), pt.y()); +} + +UINT Helper::ToMsgForMouse(EventType type, MouseButton button) +{ + if (kET_MOUSE_MOVE == type) + return WM_MOUSEMOVE; + if (kET_MOUSE_DOWN == type) + { + if (kMB_LEFT == button) + return WM_LBUTTONDOWN; + if (kMB_RIGHT == button) + return WM_RBUTTONDOWN; + if (kMB_MIDDLE == button) + return WM_MBUTTONDOWN; + } + if (kET_MOUSE_UP == type) + { + if (kMB_LEFT == button) + return WM_LBUTTONUP; + if (kMB_RIGHT == button) + return WM_RBUTTONUP; + if (kMB_MIDDLE == button) + return WM_MBUTTONUP; + } + if (kET_MOUSE_LEAVE == type) + return WM_MOUSELEAVE; + + return WM_NULL; +} + +LPARAM Helper::ToKeyStateForKey(const KeyState & state) +{ + return (LPARAM)state.state; +} + + + + +} \ No newline at end of file diff --git a/pool/shard007/C++/0091529_main.cpp b/pool/shard007/C++/0091529_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b26583994d4be1a4ceb82b7774263aaf0b62558 --- /dev/null +++ b/pool/shard007/C++/0091529_main.cpp @@ -0,0 +1,149 @@ +#include <jni.h> +#include <android/log.h> +#include "PluginJniHelper.h" +#include "PluginChannel.h" +#include "Analytics.h" +#include "Ads.h" +#include "Share.h" +#include "Social.h" +#include "AgentManager.h" + +#define LOG_TAG "main" +#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) + +using namespace anysdk::framework; + +extern "C" +{ + +jint JNI_OnLoad(JavaVM *vm, void *reserved) +{ + PluginJniHelper::setJavaVM(vm); // for plugins + return JNI_VERSION_1_4; +} + +void Java_com_anysdk_sample_wrapper_nativeInitPlugins(JNIEnv* env, jobject thiz) +{ + PluginChannel::getInstance()->loadPlugins(); +} + +void Java_com_anysdk_sample_wrapper_nativeUnLoadPlugins(JNIEnv* env, jobject thiz) +{ + PluginChannel::getInstance()->unloadPlugins(); + PluginChannel::purge(); +} + + +void Java_com_anysdk_sample_wrapper_nativeLogin(JNIEnv* env, jobject thiz) +{ + PluginChannel::getInstance()->login(); +} +void Java_com_anysdk_sample_wrapper_nativeLogout(JNIEnv* env, jobject thiz) +{ + PluginChannel::getInstance()->logout(); +} +void Java_com_anysdk_sample_wrapper_nativeAccountSwitch(JNIEnv* env, jobject thiz) +{ + PluginChannel::getInstance()->accountSwitch(); +} +void Java_com_anysdk_sample_wrapper_nativeDestroy(JNIEnv* env, jobject thiz) +{ + PluginChannel::getInstance()->destroy(); +} + +void Java_com_anysdk_sample_wrapper_nativeEnterPlatform(JNIEnv* env, jobject thiz) +{ + PluginChannel::getInstance()->enterPlatform(); +} + +void Java_com_anysdk_sample_wrapper_nativePay(JNIEnv* env, jobject thiz) +{ + PluginChannel::getInstance()->pay(); +} + +void Java_com_anysdk_sample_wrapper_nativeResetPayState(JNIEnv* env, jobject thiz) +{ + PluginChannel::getInstance()->resetPayState(); +} + +void Java_com_anysdk_sample_wrapper_nativeShowToolBar(JNIEnv* env, jobject thiz) +{ + PluginChannel::getInstance()->showToolBar(kToolBarTopLeft); +} + +void Java_com_anysdk_sample_wrapper_nativeHideToolBar(JNIEnv* env, jobject thiz) +{ + PluginChannel::getInstance()->hideToolBar(); +} + +void Java_com_anysdk_sample_wrapper_nativePause(JNIEnv* env, jobject thiz) +{ + PluginChannel::getInstance()->pause(); +} + +void Java_com_anysdk_sample_wrapper_nativeExit(JNIEnv* env, jobject thiz) +{ + PluginChannel::getInstance()->Exit(); +} + +void Java_com_anysdk_sample_wrapper_nativeRealNameRegister(JNIEnv* env, jobject thiz) +{ + PluginChannel::getInstance()->realNameRegister(); +} + +void Java_com_anysdk_sample_wrapper_nativeAntiAddictionQuery(JNIEnv* env, jobject thiz) +{ + + PluginChannel::getInstance()->antiAddictionQuery(); +} + +void Java_com_anysdk_sample_wrapper_nativePayMode(JNIEnv* env, jobject thiz, jstring code) +{ + std::string strClassName = PluginJniHelper::jstring2string(code); + PluginChannel::getInstance()->payMode(strClassName); +} + + + + +jboolean +Java_com_anysdk_sample_wrapper_nativeIsSupportFunction(JNIEnv* env, jobject thiz, jstring code) +{ + std::string strClassName = PluginJniHelper::jstring2string(code); + return (jboolean)PluginChannel::getInstance()->isSupportFunction(strClassName); +} + +void +Java_com_anysdk_sample_wrapper_nativeExcuteFunction(JNIEnv* env, jobject thiz, jstring code) +{ + std::string strClassName = PluginJniHelper::jstring2string(code); + + if (PluginChannel::getInstance()->isSupportFunction(strClassName)) { + AgentManager::getInstance()->getUserPlugin()->callFuncWithParam(strClassName.c_str(),NULL); + } + +} + +jstring +Java_com_anysdk_sample_wrapper_nativeGetChannelId(JNIEnv* env, jobject thiz) +{ + + return env->NewStringUTF(PluginChannel::getInstance()->getChannelId().c_str()); +} + +jstring +Java_com_anysdk_sample_wrapper_nativeGetCustomParam(JNIEnv* env, jobject thiz) +{ + + return env->NewStringUTF(AgentManager::getInstance()->getCustomParam().c_str()); +} + +void Java_com_anysdk_sample_wrapper_nativeSubmitLoginGameRole(JNIEnv* env, jobject thiz) +{ + PluginChannel::getInstance()->submitLoginGameRole(); +} + + + + +} diff --git a/pool/shard007/C++/0091533_ServerWin32.cpp b/pool/shard007/C++/0091533_ServerWin32.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b5de8587ef2dd9e44918e52589393640b2b3f2c8 --- /dev/null +++ b/pool/shard007/C++/0091533_ServerWin32.cpp @@ -0,0 +1,125 @@ +/************************************************************************* +* UrBackup - Client/Server backup system +* Copyright (C) 2011-2016 Martin Raiber +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU Affero General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU Affero General Public License for more details. +* +* You should have received a copy of the GNU Affero General Public License +* along with this program. If not, see <http://www.gnu.org/licenses/>. +**************************************************************************/ +#define __ICondition_INTERFACE_DEFINED__ +#include "vld.h" +#include "Server.h" +#include "stringtools.h" +#include <windows.h> +#include <dbghelp.h> +#include <shellapi.h> +#include <shlobj.h> +#include <Strsafe.h> +#include <sstream> + +bool CServer::LoadDLL(const std::string &name) +{ + HMODULE dll = LoadLibraryA( name.c_str() ); + + if(dll==NULL) + { + Server->Log("Loading DLL \""+name+"\" failed. Error Code: "+convert((int)GetLastError()), LL_ERROR); + return false; + } + + unload_handles.push_back( dll ); + + LOADACTIONS load_func=NULL; + load_func=(LOADACTIONS)GetProcAddress(dll,"LoadActions"); + unload_functs.insert(std::pair<std::string, UNLOADACTIONS>(name, (UNLOADACTIONS) GetProcAddress(dll,"UnloadActions") ) ); + + if(load_func==NULL) + return false; + + load_func(this); + return true; +} + +void CServer::UnloadDLLs2(void) +{ + for(size_t i=0;i<unload_handles.size();++i) + { + FreeLibrary( unload_handles[i] ); + } +} + +int CServer::WriteDump(void* pExceptionPointers) +{ + PEXCEPTION_POINTERS exc_ptrs = (EXCEPTION_POINTERS*)pExceptionPointers; + + PEXCEPTION_RECORD curr_exc_rec = NULL; + if (exc_ptrs != NULL) + { + curr_exc_rec = exc_ptrs->ExceptionRecord; + } + + while (curr_exc_rec != NULL) + { + std::ostringstream ss; + ss << "0x" << std::hex << curr_exc_rec->ExceptionAddress; + + Server->Log("Fatal exception code " + convert((int64)curr_exc_rec->ExceptionCode) + + " at address " + ss.str(), LL_ERROR); + + curr_exc_rec = curr_exc_rec->ExceptionRecord; + } + + BOOL bMiniDumpSuccessful; + WCHAR szPath[MAX_PATH]; + WCHAR szFileName[MAX_PATH]; + WCHAR* szAppName = L"UrBackup"; + WCHAR* szVersion = L"v2.0.0"; + DWORD dwBufferSize = MAX_PATH; + HANDLE hDumpFile; + SYSTEMTIME stLocalTime; + MINIDUMP_EXCEPTION_INFORMATION ExpParam; + + GetLocalTime( &stLocalTime ); + GetTempPath( dwBufferSize, szPath ); + + StringCchPrintf( szFileName, MAX_PATH, L"%s%s", szPath, szAppName ); + CreateDirectory( szFileName, NULL ); + + StringCchPrintf( szFileName, MAX_PATH, L"%s%s\\%s-%04d%02d%02d-%02d%02d%02d-%ld-%ld.dmp", + szPath, szAppName, szVersion, + stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay, + stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond, + GetCurrentProcessId(), GetCurrentThreadId()); + hDumpFile = CreateFile(szFileName, GENERIC_READ|GENERIC_WRITE, + FILE_SHARE_WRITE|FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0); + + if(hDumpFile!=INVALID_HANDLE_VALUE) + { + ExpParam.ThreadId = GetCurrentThreadId(); + ExpParam.ExceptionPointers = exc_ptrs; + ExpParam.ClientPointers = TRUE; + + bMiniDumpSuccessful = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), + hDumpFile, MiniDumpWithFullMemory, &ExpParam, NULL, NULL); + + if(!bMiniDumpSuccessful) + { + Server->Log("Writing minidump failed: Last error="+convert((int)GetLastError()), LL_ERROR); + } + + CloseHandle(hDumpFile); + } + + Server->Log("Fatal exception (APPLICATION CRASHED). Crash dump written to \""+Server->ConvertFromWchar(szFileName)+"\"", LL_ERROR); + + return EXCEPTION_EXECUTE_HANDLER; +} \ No newline at end of file diff --git a/pool/shard007/C++/0091542_image.cpp b/pool/shard007/C++/0091542_image.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0e6718129611d6590ffb2fc22ff7e4531983111 --- /dev/null +++ b/pool/shard007/C++/0091542_image.cpp @@ -0,0 +1,130 @@ +#include <stdio.h> +#include <iostream> +#include <opencv2/imgproc/imgproc.hpp> +#include <opencv2/highgui/highgui.hpp> +#include <opencv2/core/utility.hpp> + +using namespace cv; // all the new API is put into "cv" namespace. Export its content +using namespace std; + +static void help() +{ + cout << + "\nThis program shows how to use cv::Mat and IplImages converting back and forth.\n" + "It shows reading of images, converting to planes and merging back, color conversion\n" + "and also iterating through pixels.\n" + "Call:\n" + "./image [image-name Default: ../data/lena.jpg]\n" << endl; +} + +// enable/disable use of mixed API in the code below. +#define DEMO_MIXED_API_USE 1 + +#ifdef DEMO_MIXED_API_USE +# include <opencv2/highgui/highgui_c.h> +# include <opencv2/imgcodecs/imgcodecs_c.h> +#endif + +int main( int argc, char** argv ) +{ + help(); + const char* imagename = argc > 1 ? argv[1] : "../data/lena.jpg"; +#if DEMO_MIXED_API_USE + //! [iplimage] + Ptr<IplImage> iplimg(cvLoadImage(imagename)); // Ptr<T> is safe ref-counting pointer class + if(!iplimg) + { + fprintf(stderr, "Can not load image %s\n", imagename); + return -1; + } + Mat img = cv::cvarrToMat(iplimg); // cv::Mat replaces the CvMat and IplImage, but it's easy to convert + // between the old and the new data structures (by default, only the header + // is converted, while the data is shared) + //! [iplimage] +#else + Mat img = imread(imagename); // the newer cvLoadImage alternative, MATLAB-style function + if(img.empty()) + { + fprintf(stderr, "Can not load image %s\n", imagename); + return -1; + } +#endif + + if( img.empty() ) // check if the image has been loaded properly + return -1; + + Mat img_yuv; + cvtColor(img, img_yuv, COLOR_BGR2YCrCb); // convert image to YUV color space. The output image will be created automatically + + vector<Mat> planes; // Vector is template vector class, similar to STL's vector. It can store matrices too. + split(img_yuv, planes); // split the image into separate color planes + +#if 1 + // method 1. process Y plane using an iterator + MatIterator_<uchar> it = planes[0].begin<uchar>(), it_end = planes[0].end<uchar>(); + for(; it != it_end; ++it) + { + double v = *it*1.7 + rand()%21-10; + *it = saturate_cast<uchar>(v*v/255.); + } + + // method 2. process the first chroma plane using pre-stored row pointer. + // method 3. process the second chroma plane using individual element access + for( int y = 0; y < img_yuv.rows; y++ ) + { + uchar* Uptr = planes[1].ptr<uchar>(y); + for( int x = 0; x < img_yuv.cols; x++ ) + { + Uptr[x] = saturate_cast<uchar>((Uptr[x]-128)/2 + 128); + uchar& Vxy = planes[2].at<uchar>(y, x); + Vxy = saturate_cast<uchar>((Vxy-128)/2 + 128); + } + } + +#else + Mat noise(img.size(), CV_8U); // another Mat constructor; allocates a matrix of the specified size and type + randn(noise, Scalar::all(128), Scalar::all(20)); // fills the matrix with normally distributed random values; + // there is also randu() for uniformly distributed random number generation + GaussianBlur(noise, noise, Size(3, 3), 0.5, 0.5); // blur the noise a bit, kernel size is 3x3 and both sigma's are set to 0.5 + + const double brightness_gain = 0; + const double contrast_gain = 1.7; +#if DEMO_MIXED_API_USE + // it's easy to pass the new matrices to the functions that only work with IplImage or CvMat: + // step 1) - convert the headers, data will not be copied + IplImage cv_planes_0 = planes[0], cv_noise = noise; + // step 2) call the function; do not forget unary "&" to form pointers + cvAddWeighted(&cv_planes_0, contrast_gain, &cv_noise, 1, -128 + brightness_gain, &cv_planes_0); +#else + addWeighted(planes[0], contrast_gain, noise, 1, -128 + brightness_gain, planes[0]); +#endif + const double color_scale = 0.5; + // Mat::convertTo() replaces cvConvertScale. One must explicitly specify the output matrix type (we keep it intact - planes[1].type()) + planes[1].convertTo(planes[1], planes[1].type(), color_scale, 128*(1-color_scale)); + // alternative form of cv::convertScale if we know the datatype at compile time ("uchar" here). + // This expression will not create any temporary arrays and should be almost as fast as the above variant + planes[2] = Mat_<uchar>(planes[2]*color_scale + 128*(1-color_scale)); + + // Mat::mul replaces cvMul(). Again, no temporary arrays are created in case of simple expressions. + planes[0] = planes[0].mul(planes[0], 1./255); +#endif + + // now merge the results back + merge(planes, img_yuv); + // and produce the output RGB image + cvtColor(img_yuv, img, COLOR_YCrCb2BGR); + + // this is counterpart for cvNamedWindow + namedWindow("image with grain", WINDOW_AUTOSIZE); +#if DEMO_MIXED_API_USE + // this is to demonstrate that img and iplimg really share the data - the result of the above + // processing is stored in img and thus in iplimg too. + cvShowImage("image with grain", iplimg); +#else + imshow("image with grain", img); +#endif + waitKey(); + + return 0; + // all the memory will automatically be released by Vector<>, Mat and Ptr<> destructors. +} diff --git a/pool/shard007/C++/0091548_windowfunction.cpp b/pool/shard007/C++/0091548_windowfunction.cpp new file mode 100644 index 0000000000000000000000000000000000000000..941fff9115523faa955662ae0dcd768d537f936e --- /dev/null +++ b/pool/shard007/C++/0091548_windowfunction.cpp @@ -0,0 +1,261 @@ +/* + Copyright (c) 2017, MariaDB + Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. +*/ + +//#define NDEBUG +#include <cassert> +#include <sstream> +#include <iomanip> +using namespace std; + +#include <boost/shared_ptr.hpp> + +#include "loggingid.h" +#include "errorcodes.h" +#include "idberrorinfo.h" +using namespace logging; + +#include "rowgroup.h" +using namespace rowgroup; + +#include "idborderby.h" +using namespace ordering; + +#include "windowfunctionstep.h" +using namespace joblist; + +#include "windowfunctiontype.h" +#include "framebound.h" +#include "windowframe.h" +#include "windowfunction.h" + +namespace windowfunction +{ +WindowFunction::WindowFunction(boost::shared_ptr<WindowFunctionType>& f, + boost::shared_ptr<ordering::EqualCompData>& p, + boost::shared_ptr<OrderByData>& o, boost::shared_ptr<WindowFrame>& w, + const RowGroup& g, const Row& r) + : fFunctionType(f), fPartitionBy(p), fOrderBy(o), fFrame(w), fRowGroup(g), fRow(r) +{ +} + +WindowFunction::~WindowFunction() +{ +} + +void WindowFunction::operator()() +{ + try + { + fRowData.reset(new vector<RowPosition>(fStep->getRowData())); + + if (fOrderBy->rule().fCompares.size() > 0) + sort(fRowData->begin(), fRowData->size()); + + // get partitions + if (fPartitionBy.get() != NULL && !fStep->cancelled()) + { + int64_t i = 0; + int64_t j = 1; + int64_t rowCnt = fRowData->size(); + + for (j = 1; j < rowCnt; j++) + { + if ((*(fPartitionBy.get()))(getPointer((*fRowData)[j - 1]), getPointer((*fRowData)[j]))) + continue; + + fPartition.push_back(make_pair(i, j - 1)); + i = j; + } + + fPartition.push_back(make_pair(i, j - 1)); + } + else + { + fPartition.push_back(make_pair(0, fRowData->size())); + } + + // compute partition by partition + int64_t uft = fFrame->upper()->boundType(); + int64_t lft = fFrame->lower()->boundType(); + bool upperUbnd = (uft == WF__UNBOUNDED_PRECEDING || uft == WF__UNBOUNDED_FOLLOWING); + bool lowerUbnd = (lft == WF__UNBOUNDED_PRECEDING || lft == WF__UNBOUNDED_FOLLOWING); + bool upperCnrw = (uft == WF__CURRENT_ROW); + bool lowerCnrw = (lft == WF__CURRENT_ROW); + fFunctionType->setRowData(fRowData); + fFunctionType->setRowMetaData(fRowGroup, fRow); + fFrame->setRowData(fRowData); + fFrame->setRowMetaData(fRowGroup, fRow); + + for (uint64_t k = 0; k < fPartition.size() && !fStep->cancelled(); k++) + { + fFunctionType->resetData(); + fFunctionType->partition(fPartition[k]); + + int64_t begin = fPartition[k].first; + int64_t end = fPartition[k].second; + + if (upperUbnd && lowerUbnd) + { + fFunctionType->operator()(begin, end, WF__BOUND_ALL); + } + else if (upperUbnd && lowerCnrw) + { + if (fFrame->unit() == WF__FRAME_ROWS) + { + for (int64_t i = begin; i <= end && !fStep->cancelled(); i++) + { + fFunctionType->operator()(begin, i, i); + } + } + else + { + for (int64_t i = begin; i <= end && !fStep->cancelled(); i++) + { + pair<int64_t, int64_t> w = fFrame->getWindow(begin, end, i); + int64_t j = i; + + if (w.second > i) + j = w.second; + + fFunctionType->operator()(begin, j, i); + } + } + } + else if (upperCnrw && lowerUbnd) + { + if (fFrame->unit() == WF__FRAME_ROWS) + { + for (int64_t i = end; i >= begin && !fStep->cancelled(); i--) + { + fFunctionType->operator()(i, end, i); + } + } + else + { + for (int64_t i = end; i >= begin && !fStep->cancelled(); i--) + { + pair<int64_t, int64_t> w = fFrame->getWindow(begin, end, i); + int64_t j = i; + + if (w.first < i) + j = w.first; + + fFunctionType->operator()(j, end, i); + } + } + } + else + { + pair<int64_t, int64_t> w; + pair<int64_t, int64_t> prevFrame; + int64_t b, e; + bool firstTime = true; + + for (int64_t i = begin; i <= end && !fStep->cancelled(); i++) + { + w = fFrame->getWindow(begin, end, i); + b = w.first; + e = w.second; + + if (firstTime) + { + prevFrame = w; + } + + // UDAnF functions may have a dropValue function implemented. + // If they do, we can optimize by calling dropValue() for those + // values leaving the window and nextValue for those entering, rather + // than a resetData() and then iterating over the entire window. + // Built-in functions may have this functionality added in the future. + // If b > e then the frame is entirely outside of the partition + // and there's no values to drop + if (!firstTime && (b <= e) && fFunctionType->dropValues(prevFrame.first, w.first)) + { + // Adjust the beginning of the frame for nextValue + // to start where the previous frame left off. + b = prevFrame.second + 1; + } + else + { + // If dropValues failed or doesn't exist, + // calculate the entire frame. + fFunctionType->resetData(); + } + fFunctionType->operator()(b, e, i); // UDAnF: Calls nextValue and evaluate + prevFrame = w; + firstTime = false; + } + } + } + } + catch (...) + { + fStep->handleException(std::current_exception(), logging::ERR_EXECUTE_WINDOW_FUNCTION, + logging::ERR_WF_DATA_SET_TOO_BIG, "WindowFunction::operator()"); + } +} + +void WindowFunction::setCallback(joblist::WindowFunctionStep* step, int id) +{ + fStep = step; + fId = id; + fFunctionType->setCallback(step); + fFrame->setCallback(step); +} + +const Row& WindowFunction::getRow() const +{ + return fRow; +} + +void WindowFunction::sort(std::vector<RowPosition>::iterator v, uint64_t n) +{ + // recursive function termination condition. + if (n < 2 || fStep->cancelled()) + return; + + RowPosition p = *(v + n / 2); // pivot value + vector<RowPosition>::iterator l = v; // low address + vector<RowPosition>::iterator h = v + (n - 1); // high address + + while (l <= h && !(fStep->cancelled())) + { + // Can use while here, but need check boundary and cancel status. + if (fOrderBy->operator()(getPointer(*l), getPointer(p))) + { + l++; + } + else if (fOrderBy->operator()(getPointer(p), getPointer(*h))) + { + h--; + } + else + { + RowPosition t = *l; // temp value for swap + *l++ = *h; + *h-- = t; + } + } + + sort(v, std::distance(v, h) + 1); + sort(l, std::distance(l, v) + n); +} + +} // namespace windowfunction diff --git a/pool/shard007/C++/0091552_no_destructor_test.cc b/pool/shard007/C++/0091552_no_destructor_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..3eaa4d6d9dbedd5f6c929587659418ecff9d2f96 --- /dev/null +++ b/pool/shard007/C++/0091552_no_destructor_test.cc @@ -0,0 +1,168 @@ +// +// Copyright 2018 ZetaSQL Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#include "zetasql/base/no_destructor.h" + +#include <initializer_list> + +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "zetasql/base/logging.h" + +namespace zetasql_base { +namespace { + +struct Blob { + Blob() : val(42) {} + Blob(int x, int y) : val(x + y) {} + Blob(std::initializer_list<int> xs) { + val = 0; + for (auto& x : xs) val += x; + } + + Blob(const Blob& /*b*/) = delete; + Blob(Blob&& b) noexcept : val(b.val) { + b.moved_out = true; + } // moving is fine + + // no crash: NoDestructor indeed does not destruct (the moved-out Blob + // temporaries do get destroyed though) + ~Blob() { CHECK(moved_out) << "~Blob"; } + + int val; + bool moved_out = false; +}; + +struct TypeWithDeletedDestructor { + ~TypeWithDeletedDestructor() = delete; +}; + +TEST(NoDestructorTest, DestructorNeverCalled) { + NoDestructor<TypeWithDeletedDestructor> a; + (void)a; +} + +TEST(NoDestructorTest, Noncopyable) { + using T = NoDestructor<int>; + + EXPECT_FALSE((std::is_constructible<T, T>::value)); + EXPECT_FALSE((std::is_constructible<T, const T>::value)); + EXPECT_FALSE((std::is_constructible<T, T&>::value)); + EXPECT_FALSE((std::is_constructible<T, const T&>::value)); + + EXPECT_FALSE((std::is_assignable<T&, T>::value)); + EXPECT_FALSE((std::is_assignable<T&, const T>::value)); + EXPECT_FALSE((std::is_assignable<T&, T&>::value)); + EXPECT_FALSE((std::is_assignable<T&, const T&>::value)); +} + +TEST(NoDestructorTest, Interface) { + EXPECT_TRUE(std::is_trivially_destructible<NoDestructor<Blob>>::value); + EXPECT_TRUE(std::is_trivially_destructible<NoDestructor<const Blob>>::value); + { + NoDestructor<Blob> b; // default c-tor + // access: *, ->, get() + EXPECT_EQ(42, (*b).val); + (*b).val = 55; + EXPECT_EQ(55, b->val); + b->val = 66; + EXPECT_EQ(66, b.get()->val); + b.get()->val = 42; + EXPECT_EQ(42, (*b).val); + } + { + NoDestructor<const Blob> b(70, 7); // regular c-tor, const + EXPECT_EQ(77, (*b).val); + EXPECT_EQ(77, b->val); + EXPECT_EQ(77, b.get()->val); + } + { + const NoDestructor<Blob> b{{20, 28, 40}}; // init-list c-tor, deep const + // This only works in clang, not in gcc: + // const NoDestructor<Blob> b({20, 28, 40}); + EXPECT_EQ(88, (*b).val); + EXPECT_EQ(88, b->val); + EXPECT_EQ(88, b.get()->val); + } +} + +// ========================================================================= // + +std::string* Str0() { + static NoDestructor<std::string> x; + return x.get(); +} + +extern const std::string& Str2(); + +const char* Str1() { + static NoDestructor<std::string> x(Str2() + "_Str1"); + return x->c_str(); +} + +const std::string& Str2() { + static NoDestructor<std::string> x("Str2"); + return *x; +} + +const std::string& Str2Copy() { + static NoDestructor<std::string> x(Str2()); // exercise copy construction + return *x; +} + +typedef std::array<std::string, 3> MyArray; +const MyArray& Array() { + static NoDestructor<MyArray> x{{{"foo", "bar", "baz"}}}; + // This only works in clang, not in gcc: + // static NoDestructor<MyArray> x({{"foo", "bar", "baz"}}); + return *x; +} + +typedef std::vector<int> MyVector; +const MyVector& Vector() { + static NoDestructor<MyVector> x{{1, 2, 3}}; + return *x; +} + +const int& Int() { + static NoDestructor<int> x; + return *x; +} + +TEST(NoDestructorTest, StaticPattern) { + EXPECT_TRUE(std::is_trivially_destructible<NoDestructor<std::string>>::value); + EXPECT_TRUE(std::is_trivially_destructible<NoDestructor<MyArray>>::value); + EXPECT_TRUE(std::is_trivially_destructible<NoDestructor<MyVector>>::value); + EXPECT_TRUE(std::is_trivially_destructible<NoDestructor<int>>::value); + + EXPECT_EQ(*Str0(), ""); + Str0()->append("foo"); + EXPECT_EQ(*Str0(), "foo"); + + EXPECT_EQ(std::string(Str1()), "Str2_Str1"); + + EXPECT_EQ(Str2(), "Str2"); + EXPECT_EQ(Str2Copy(), "Str2"); + + EXPECT_THAT(Array(), testing::ElementsAre("foo", "bar", "baz")); + + EXPECT_THAT(Vector(), testing::ElementsAre(1, 2, 3)); + + EXPECT_EQ(0, Int()); // should get zero-initialized +} + +} // namespace +} // namespace zetasql_base diff --git a/pool/shard007/C++/0091559_ast_node_builder.cpp b/pool/shard007/C++/0091559_ast_node_builder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ae17fe866362cbb54b03094be43ecb55e389af9a --- /dev/null +++ b/pool/shard007/C++/0091559_ast_node_builder.cpp @@ -0,0 +1,232 @@ +#include "ast_node_builder.h" + +/////////////////////////////// +/// ast_builder class +/////////////////////////////// +ast_builder::ast_builder () + : m_meta_root (new ast_node_list {}) +{ + push_node (m_meta_root.get ()); +} + +/////////////////////////////// +ast_builder& +ast_builder::add_reader_macro (const reader_macro_fn& reader_macro) +{ + m_current_stack.back ().m_reader_macros.emplace_back (reader_macro, back_node ()->size ()); + return *this; +} + +/////////////////////////////// +ast_builder& +ast_builder::open_list () +{ + auto child = mal::make_list (); + ast_node_list* child_ref = child.get (); + + back_node ()->add_child (child); + push_node (child_ref); + return *this; +} + +/////////////////////////////// +ast_builder& +ast_builder::close_list () +{ + back_node ()->as_or_throw<ast_node_list, mal_exception_parse_error> (); + pop_node (); + return *this; +} + +/////////////////////////////// +ast_builder& +ast_builder::open_vector () +{ + auto child = mal::make_vector (); + ast_node_vector* child_ref = child.get (); + + back_node ()->add_child (child); + push_node (child_ref); + return *this; +} + +/////////////////////////////// +ast_builder& +ast_builder::close_vector () +{ + back_node ()->as_or_throw<ast_node_vector, mal_exception_parse_error> (); + pop_node (); + return *this; +} + +/////////////////////////////// +ast_builder& +ast_builder::add_symbol (std::string value) +{ + ast_node::ptr child { new ast_node_symbol {std::move (value)} }; + back_node ()->add_child (child); + return *this; +} + +/////////////////////////////// +ast_builder& +ast_builder::add_keyword (std::string keyword) +{ + ast_node::ptr child { new ast_node_keyword {std::move (keyword)} }; + back_node ()->add_child (child); + return *this; +} + +/////////////////////////////// +ast_builder& +ast_builder::add_int (int64_t value) +{ + ast_node::ptr child { new ast_node_int { value } }; + back_node ()->add_child (child); + return *this; +} + +/////////////////////////////// +ast_builder& +ast_builder::add_bool (bool value) +{ + back_node ()->add_child (value ? ast_node::true_node : ast_node::false_node); + return *this; +} + +/////////////////////////////// +ast_builder& +ast_builder::add_nil () +{ + back_node ()->add_child (ast_node::nil_node); + return *this; +} + +/////////////////////////////// +ast_builder& +ast_builder::add_node (ast_node::ptr node) +{ + back_node ()->add_child (node); + return *this; +} + +/////////////////////////////// +ast_builder& +ast_builder::add_string (std::string str) +{ + ast_node::ptr child { new ast_node_string {std::move (str)} }; + back_node ()->add_child (child); + return *this; +} + +/////////////////////////////// +ast_builder& +ast_builder::start_string () +{ + m_picewise_string = ""; + return *this; +} + +/////////////////////////////// +ast_builder& +ast_builder::append_string (const std::string &piece) +{ + m_picewise_string += piece; + return *this; +} + +/////////////////////////////// +ast_builder& +ast_builder::finish_string () +{ + add_string (m_picewise_string); + return *this; +} + +/////////////////////////////// +ast_builder& +ast_builder::open_hashmap () +{ + add_reader_macro ( + [] (ast_node_container_base* listToModify, size_t listIdx) -> void + { + auto newNode = mal::make_hashmap ((*listToModify) [listIdx]->as_or_throw<ast_node_ht_list, mal_exception_parse_error> ()); + listToModify->replace (listIdx, newNode); + }); + + auto child = mal::make_ht_list (); + auto child_ref = child.get (); + + back_node ()->add_child (child); + push_node (child_ref); + return *this; +} + +/////////////////////////////// +ast_builder& +ast_builder::close_hashmap () +{ + back_node ()->as_or_throw<ast_node_ht_list, mal_exception_parse_error> (); + pop_node (); + return *this; +} + +/////////////////////////////// +ast +ast_builder::build() +{ + if (m_current_stack.size () != 1) + raise<mal_exception_parse_error> (); + + apply_reader_macro (); + + const size_t level0_count = m_meta_root->size (); + if (level0_count > 1) + raise<mal_exception_parse_error> (m_meta_root->to_string ()); + + if (level0_count == 0) + return ast_node::invalid_node; + + assert (m_meta_root->size () > 0); + ast_node::ptr retVal = (*m_meta_root) [0]; + m_current_stack.clear (); + m_meta_root.reset (); + + return retVal; +} + +/////////////////////////////// +void +ast_builder::pop_node () +{ + apply_reader_macro (); + m_current_stack.pop_back (); + if (m_current_stack.size () == 0) + raise<mal_exception_parse_error> (); +} + +/////////////////////////////// +void +ast_builder::push_node (ast_node_container_base* child_ref) +{ + m_current_stack.emplace_back (); + m_current_stack.back ().m_builder = child_ref; + +} + +/////////////////////////////// +void +ast_builder::apply_reader_macro () +{ + auto & entry = m_current_stack.back (); + for (auto iter = entry.m_reader_macros.rbegin (), e = entry.m_reader_macros.rend (); iter != e; ++iter) + { + const auto listIdx = iter->second; + if (listIdx >= entry.m_builder->size ()) + raise<mal_exception_parse_error> (entry.m_builder->to_string ()); + + iter->first (entry.m_builder, listIdx); + } +} + + diff --git a/pool/shard007/C++/0091565_LoRaWANGatewayMetadata.cpp b/pool/shard007/C++/0091565_LoRaWANGatewayMetadata.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7b53d3c2b5a000cd70aa26346b7d4164b669c121 --- /dev/null +++ b/pool/shard007/C++/0091565_LoRaWANGatewayMetadata.cpp @@ -0,0 +1,93 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include <aws/iotwireless/model/LoRaWANGatewayMetadata.h> +#include <aws/core/utils/json/JsonSerializer.h> + +#include <utility> + +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +namespace Aws +{ +namespace IoTWireless +{ +namespace Model +{ + +LoRaWANGatewayMetadata::LoRaWANGatewayMetadata() : + m_gatewayEuiHasBeenSet(false), + m_snr(0.0), + m_snrHasBeenSet(false), + m_rssi(0.0), + m_rssiHasBeenSet(false) +{ +} + +LoRaWANGatewayMetadata::LoRaWANGatewayMetadata(JsonView jsonValue) : + m_gatewayEuiHasBeenSet(false), + m_snr(0.0), + m_snrHasBeenSet(false), + m_rssi(0.0), + m_rssiHasBeenSet(false) +{ + *this = jsonValue; +} + +LoRaWANGatewayMetadata& LoRaWANGatewayMetadata::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("GatewayEui")) + { + m_gatewayEui = jsonValue.GetString("GatewayEui"); + + m_gatewayEuiHasBeenSet = true; + } + + if(jsonValue.ValueExists("Snr")) + { + m_snr = jsonValue.GetDouble("Snr"); + + m_snrHasBeenSet = true; + } + + if(jsonValue.ValueExists("Rssi")) + { + m_rssi = jsonValue.GetDouble("Rssi"); + + m_rssiHasBeenSet = true; + } + + return *this; +} + +JsonValue LoRaWANGatewayMetadata::Jsonize() const +{ + JsonValue payload; + + if(m_gatewayEuiHasBeenSet) + { + payload.WithString("GatewayEui", m_gatewayEui); + + } + + if(m_snrHasBeenSet) + { + payload.WithDouble("Snr", m_snr); + + } + + if(m_rssiHasBeenSet) + { + payload.WithDouble("Rssi", m_rssi); + + } + + return payload; +} + +} // namespace Model +} // namespace IoTWireless +} // namespace Aws diff --git a/pool/shard007/C++/0091568_VertexBuffer.cpp b/pool/shard007/C++/0091568_VertexBuffer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..603695a3e4a8cd6f9c8aaa95f84d30c5325382c7 --- /dev/null +++ b/pool/shard007/C++/0091568_VertexBuffer.cpp @@ -0,0 +1,67 @@ +#include <base/gl/VertexBuffer.h> + +namespace base { +namespace gl { +VertexBuffer::VertexBuffer() + : Buffer(Target::Array) +{ +} + +VertexBuffer::VertexBuffer(Usage usage) + : Buffer(Target::Array, usage) +{ +} + +VertexBuffer::VertexBuffer(VertexBuffer&& vbo) + : Buffer(std::move(vbo)) +{ + std::swap(_attributePointers, vbo._attributePointers); +} + +VertexBuffer::~VertexBuffer() +{ +} + +VertexBuffer& VertexBuffer::operator=(VertexBuffer&& vbo) +{ + std::swap(_usage, vbo._usage); + std::swap(_target, vbo._target); + std::swap(_bufferID, vbo._bufferID); + std::swap(_isCreated, vbo._isCreated); + std::swap(_attributePointers, vbo._attributePointers); + + return *this; +} + +void VertexBuffer::bind() const +{ + glBindBuffer(static_cast<GLenum>(Buffer::Target::Array), getID()); +} + +void VertexBuffer::setData(const VertexBuffer::Data& data) +{ + Buffer::setData(data.size, data.data); + setAttributes(data.pointers); +} + +void VertexBuffer::setTarget() +{ + _target = Target::Array; +} + +void VertexBuffer::setAttributes(std::vector<VertexAttrib> attributes) +{ + _attributePointers = std::move(attributes); +} + +Buffer::Target VertexBuffer::getTarget() const +{ + return Target::Array; +} + +const std::vector<VertexAttrib>& VertexBuffer::getAttributes() const +{ + return _attributePointers; +} +} +} diff --git a/pool/shard007/C++/0091578_qzuestest.cpp b/pool/shard007/C++/0091578_qzuestest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4319828efcf5b65b78f9b44f74a273a0d326abe0 --- /dev/null +++ b/pool/shard007/C++/0091578_qzuestest.cpp @@ -0,0 +1,43 @@ +#include "qzuestest.h" +#include <QTimer> +QZuesTest::QZuesTest(QWidget *parent) + : QMainWindow(parent) +{ + ui.setupUi(this); + ui.lblZues->setType(LABEL_TYPE_MARQUEE); + ui.txtZues->setText("testssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"); + StackWidgetAnimationTypes animationTypes = STACK_WIDGET_ANIMATION_GRADIENT; + animationTypes |= STACK_WIDGET_ANIMATION_TOP; + animationTypes |= STACK_WIDGET_ANIMATION_SIZE; + ui.stkTest->setAnimationTypes(animationTypes); + //ui.stkTest->setAnimationDuration(10); + QTimer::singleShot(1000, [&](){ + initStackWidget(); + }); + + +} + +QZuesTest::~QZuesTest() +{ + +} + +void QZuesTest::on_btnReset_clicked() +{ + ui.txtZues->reset(); +} + +void QZuesTest::on_btnNextPage_clicked() +{ + QWidget*nxtWidget = ui.stkTest->nextWidget(ui.stkTest->currentIndex()); + ui.stkTest->setCurrentWidget(nxtWidget); +} + +void QZuesTest::initStackWidget() +{ + InfoDisplay *infos = new InfoDisplay(this); + qDebug()<< ui.stkTest->addWidget(infos); + AddInfo *addInfo = new AddInfo(this); + qDebug() << ui.stkTest->addWidget(addInfo); +} diff --git a/pool/shard007/C++/0091583_SynMultiPathDriver.cpp b/pool/shard007/C++/0091583_SynMultiPathDriver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8ed8d117b884eb980164fba1d117e5e01d17c3eb --- /dev/null +++ b/pool/shard007/C++/0091583_SynMultiPathDriver.cpp @@ -0,0 +1,129 @@ +#include <algorithm> + +#include "chrono/core/ChMathematics.h" +#include "chrono/assets/ChLineShape.h" +#include "chrono/geometry/ChLineBezier.h" +#include "chrono/utils/ChUtilsInputOutput.h" + +#include "chrono_synchrono/controller/driver/SynMultiPathDriver.h" + +using namespace chrono::vehicle; + +namespace chrono { +namespace synchrono { + +ChMultiPathFollowerACCDriver::ChMultiPathFollowerACCDriver( + ChVehicle& vehicle, + std::vector<std::pair<std::shared_ptr<ChBezierCurve>, bool>> path_pairs, + const std::string& path_name, + double target_speed, + double target_following_time, + double target_min_distance, + double current_distance) + : ChDriver(vehicle), + m_steeringPID(path_pairs, 0), + m_pathName(path_name), + m_target_speed(target_speed), + m_target_following_time(target_following_time), + m_target_min_distance(target_min_distance), + m_current_distance(current_distance), + m_throttle_threshold(0.2) { + Create(); +} + +void ChMultiPathFollowerACCDriver::Create() { + // Reset the steering and speed controllers + m_steeringPID.Reset(m_vehicle); + m_speedPID.Reset(m_vehicle); + + // Create a fixed body to carry a visualization asset for the path + auto road = std::shared_ptr<ChBody>(m_vehicle.GetSystem()->NewBody()); + road->SetBodyFixed(true); + m_vehicle.GetSystem()->AddBody(road); + + auto bezier_curve = m_steeringPID.GetPath(); + for (int i = 0; i < bezier_curve.size(); i++) { + auto num_points = static_cast<unsigned int>(bezier_curve[i]->getNumPoints()); + auto path_asset = chrono_types::make_shared<ChLineShape>(); + path_asset->SetLineGeometry(chrono_types::make_shared<geometry::ChLineBezier>(bezier_curve[i])); + path_asset->SetColor(ChColor(0.8f, 0.8f, 0.0f)); + path_asset->SetName(m_pathName); + path_asset->SetNumRenderPoints(std::max<unsigned int>(2 * num_points, 400)); + road->AddAsset(path_asset); + } +} + +void ChMultiPathFollowerACCDriver::Reset() { + m_steeringPID.Reset(m_vehicle); + m_speedPID.Reset(m_vehicle); +} + +void ChMultiPathFollowerACCDriver::Advance(double step) { + // Set the throttle and braking values based on the output from the speed controller. + double out_speed = m_speedPID.Advance(m_vehicle, m_target_speed, m_target_following_time, m_target_min_distance, + m_current_distance, step); + ChClampValue(out_speed, -1.0, 1.0); + + if (out_speed > 0) { + // Vehicle moving too slow + m_braking = 0; + m_throttle = out_speed; + } else if (m_throttle > m_throttle_threshold) { + // Vehicle moving too fast: reduce throttle + m_braking = 0; + m_throttle = 1 + out_speed; + } else { + // Vehicle moving too fast: apply brakes + m_braking = -out_speed; + m_throttle = 0; + } + // Set the steering value based on the output from the steering controller. + double out_steering = m_steeringPID.Advance(m_vehicle, step); + ChClampValue(out_steering, -1.0, 1.0); + m_steering = out_steering; +} + +void ChMultiPathFollowerACCDriver::ExportPathPovray(const std::string& out_dir) { + for (int i = 0; i < m_steeringPID.GetPath().size(); i++) { + utils::WriteCurvePovray(*(m_steeringPID.GetPath()[i]), m_pathName, out_dir, 0.04, ChColor(0.8f, 0.5f, 0.0f)); + } +} + +// ----------------------------------------------------------------------------- +// Implementation of the derived class ChMultiplePathSteeringController. +// ----------------------------------------------------------------------------- +ChMultiplePathSteeringController::ChMultiplePathSteeringController( + std::vector<std::pair<std::shared_ptr<ChBezierCurve>, bool>> path_pairs, + int lane) + : m_lane(lane) { + for (const auto& path_pair : path_pairs) { + auto tracker_element = chrono_types::make_shared<ChBezierCurveTracker>(path_pair.first, path_pair.second); + m_tracker.push_back(tracker_element); + m_path.push_back(path_pair.first); + } +} + +void ChMultiplePathSteeringController::CalcTargetLocation() { + // Let the underlying tracker do its magic. + m_tracker[m_lane]->calcClosestPoint(m_sentinel, m_target); +} + +void ChMultiplePathSteeringController::Reset(const ChVehicle& vehicle) { + // Let the base class calculate the current location of the sentinel point. + ChSteeringController::Reset(vehicle); + + // Reset the path tracker with the new sentinel location + for (int i = 0; i < m_tracker.size(); i++) { + m_tracker[i]->reset(m_sentinel); + } +} + +unsigned ChMultiplePathSteeringController::addPath(std::shared_ptr<ChBezierCurve> path, bool isClosedPath) { + m_path.push_back(path); + auto m_tracker_element = chrono_types::make_shared<ChBezierCurveTracker>(path, isClosedPath); + m_tracker.push_back(m_tracker_element); + return (unsigned)(m_tracker.size() - 1); +} + +} // namespace synchrono +} // namespace chrono diff --git a/pool/shard007/C++/0091586_main.cpp b/pool/shard007/C++/0091586_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c52e1b77bfd9ccc90acfcf4a34feb1221ebc038e --- /dev/null +++ b/pool/shard007/C++/0091586_main.cpp @@ -0,0 +1,39 @@ +//Author: Aguilera Dario, dario_21_06@hotmail.com +#include <QtGui> + +#include "tageditor.h" + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); + QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); + + //all the translation stuff was taken from minitube + const QString locale = QLocale::system().name(); + + // app translations +#ifdef PKGDATADIR + QString dataDir = QLatin1String(PKGDATADIR); +#else + QString dataDir = ""; +#endif + + QString localeDir = qApp->applicationDirPath() + QDir::separator()+ "locale"; + //qDebug() << "Using locale dir" << localeDir << locale; + if (!QFile::exists(localeDir)) { + localeDir = dataDir + QDir::separator() + "locale"; + } + //qDebug() << "Using locale dir" << localeDir << locale; + QTranslator translator; + translator.load(locale, localeDir); + app.installTranslator(&translator); + + TagEditor tagEditor; + tagEditor.show(); + if(argc>=2){ + tagEditor.passFileName(QApplication::arguments().at(1)); + } + return app.exec(); +} diff --git a/pool/shard007/C++/0091588_FMod.cpp b/pool/shard007/C++/0091588_FMod.cpp new file mode 100644 index 0000000000000000000000000000000000000000..005f10c1890530a804e08118eee22e80c3c187d6 --- /dev/null +++ b/pool/shard007/C++/0091588_FMod.cpp @@ -0,0 +1,141 @@ +#include "Main.h" + +#include "..\FMod\lib\minifmod.h" + +//#define FMOD_FROM_FILE + +FMUSIC_MODULE *fmodMod = NULL; +void *fmodData; +int fmodLength; +int fmodPos; +unsigned char fmodMusic; + +#ifdef FMOD_FROM_FILE + +unsigned int memopen(char *name) +{ + return (unsigned int)fopen(name, "rb"); +} + +void memclose(unsigned int handle) +{ + fclose((FILE *)handle); +} + +int memread(void *buffer, int size, unsigned int handle) +{ + return fread(buffer, 1, size, (FILE *)handle); +} + +void memseek(unsigned int handle, int pos, signed char mode) +{ + fseek((FILE *)handle, pos, mode); +} + +int memtell(unsigned int handle) +{ + return ftell((FILE *)handle); +} + +#else + +unsigned int memopen(char * name) +{ + fmodPos = 0; + return 1; +} + +void memclose(unsigned int handle) +{ +} + +int memread(void *buffer, int size, unsigned int handle) +{ + if (fmodPos + size >= fmodLength) + size = fmodLength - fmodPos; + + memcpy(buffer, (char *)fmodData+fmodPos, size); + fmodPos += size; + + return size; +} + +void memseek(unsigned int handle, int pos, signed char mode) +{ + if (mode == SEEK_SET) + fmodPos = pos; + else if (mode == SEEK_CUR) + fmodPos += pos; + else if (mode == SEEK_END) + fmodPos = fmodLength; + + if (fmodPos > fmodLength) + fmodPos = fmodLength; +} + +int memtell(unsigned int handle) +{ + return fmodPos; +} + +#endif + + +void fmodLoadMod(void* data, int length) +{ + fmodData = data; + fmodLength = length; + + FSOUND_File_SetCallbacks(memopen, memclose, memread, memseek, memtell); + + if (!FSOUND_Init(44100, 0)) + { + return; + //uniQuit("Your soundcard is... gone?!"); + } + + fmodMod = FMUSIC_LoadSong((char*)data, NULL); + + if (!fmodMod) + { + return; + //uniQuit("Unable to load XM"); + } +} + +void fmodPlay(int iOrder) +{ + if (!fmodMod) + { + return; + } + + FMUSIC_PlaySong(fmodMod, iOrder); +} + +void fmodStop() +{ + if (!fmodMod) + { + return; + } + + FMUSIC_FreeSong(fmodMod); + FSOUND_Close(); +} + +void fmodGetInfo(int &order, int &row, int &sync) +{ + if (!fmodMod) + { + return; + } + + FMUSIC_GetOrderAndRow(fmodMod, &order, &row); + + //order = FMUSIC_GetOrder(fmodMod); + //row = FMUSIC_GetRow(fmodMod); + //sync = FMUSIC_GetTime(fmodMod); + + +} \ No newline at end of file diff --git a/pool/shard007/C++/0091591_PrintNamesCmd.cpp b/pool/shard007/C++/0091591_PrintNamesCmd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b48559621048bdc30de02c95e106080796caf690 --- /dev/null +++ b/pool/shard007/C++/0091591_PrintNamesCmd.cpp @@ -0,0 +1,198 @@ +/* + * This file is part of Hootenanny. + * + * Hootenanny is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + * -------------------------------------------------------------------- + * + * The following copyright notices are generated automatically. If you + * have a new notice to add, please use the format: + * " * @copyright Copyright ..." + * This will properly maintain the copyright information. DigitalGlobe + * copyrights will be updated automatically. + * + * @copyright Copyright (C) 2013, 2014, 2015 DigitalGlobe (http://www.digitalglobe.com/) + */ + +// Hoot +#include <hoot/core/Factory.h> +#include <hoot/core/MapReprojector.h> +#include <hoot/core/cmd/BaseCommand.h> +#include <hoot/core/elements/ElementVisitor.h> +#include <hoot/core/io/OsmMapReaderFactory.h> +#include <hoot/core/io/PartialOsmMapReader.h> +#include <hoot/core/io/WordCount.h> +#include <hoot/core/io/WordCountWriter.h> + +// Standard +#include <iomanip> +#include <map> + +namespace hoot +{ + +using namespace std; + +bool greaterThanWordCount(const WordCount& left, const WordCount& right) +{ + return left.count > right.count; +} + +class PrintNamesCmd : public BaseCommand +{ +public: + static string className() { return "hoot::PrintNamesCmd"; } + + class NameCountVisitor : public ElementVisitor + { + public: + NameCountVisitor(std::map<QString, int>& counts) : _counts(counts) + { + _nonWord.setPattern("[^\\w]"); + } + + virtual void visit(const ConstElementPtr& e) + { + QStringList names = e->getTags().getNames(); + + for (int i = 0; i < names.size(); i++) + { + QStringList words = names[i].split(" "); + for (int i = 0; i < words.size(); i++) + { + // See wikipedia for a description of what this does, but we're trying to group words + // that are effectively the same together in the same hash bin. + // http://en.wikipedia.org/wiki/Unicode_equivalence + QString word = words[i].toLower().normalized(QString::NormalizationForm_C); + // remove all the non-word characters (e.g. "(", "-", etc.) + QString noSymbols = word; + noSymbols.replace(_nonWord, ""); + // if there is still a word left then use the word w/o symbols. + // E.g. don't remove "&" if it is all by itself. + if (noSymbols.isEmpty() == false) + { + word = noSymbols; + } + // ignore any empty words. This may happen when there are multiple consecutive spaces. + if (word.isEmpty() == false) + { + _counts[word]++; + } + } + } + } + + private: + map<QString, int>& _counts; + QRegExp _nonWord; + }; + + PrintNamesCmd() {} + + QString getHelp() const + { + // 80 columns + // | <--- ---> | + return getName() + " (input) [inputs...] [--write outputBase]\n" + " Reads input and write out a list of names ordered by frequency.\n" + " * input - One or more input map paths.\n" + " * outputBase - Write out the counts to a .frequent and .all dictionary."; + } + + virtual QString getName() const { return "names"; } + + int runSimple(QStringList args) + { + if (args.size() == 0) + { + cout << getHelp() << endl << endl; + throw HootException(QString("%1 takes one or more parameters.").arg(getName())); + } + + bool writeFile = false; + QString output; + if (args.size() >= 3 && args[args.size() - 2] == "--write") + { + writeFile = true; + output = args[args.size() - 1]; + } + + // adding the source datetime just makes things really slow. + conf().set(ConfigOptions().getReaderAddSourceDatetimeKey(), false); + + shared_ptr<OsmMap> map(new OsmMap()); + + std::map<QString, int> counts; + NameCountVisitor v(counts); + map->visitRo(v); + + int inputCount = writeFile ? args.size() - 2 : args.size(); + for (int i = 0; i < inputCount; i++) + { + if (OsmMapReaderFactory::getInstance().hasPartialReader(args[i])) + { + shared_ptr<OsmMapReader> reader = OsmMapReaderFactory::getInstance().createReader(args[i]); + shared_ptr<PartialOsmMapReader> pomr = dynamic_pointer_cast<PartialOsmMapReader>(reader); + + pomr->open(args[i]); + + while (pomr->hasMoreElements()) + { + ElementPtr e = pomr->readNextElement(); + v.visit(e); + } + } + else + { + shared_ptr<OsmMap> map(new OsmMap()); + loadMap(map, args[i], false, Status::Unknown1); + map->visitRo(v); + } + } + + long total = 0; + QVector<WordCount> wc; + wc.reserve(counts.size()); + for (std::map<QString, int>::iterator it = counts.begin(); it != counts.end(); it++) + { + wc.push_back(WordCount(it->first, it->second)); + total += it->second; + } + + if (writeFile) + { + WordCountWriter writer(10 * 1000 * 1000); + writer.write(output, wc); + } + else + { + cout << "Total word count: " << total << endl; + + sort(wc.begin(), wc.end(), greaterThanWordCount); + + for (int i = 0; i < wc.size(); i++) + { + double p = (double)wc[i].count / (double)total; + cout << setprecision(2); + cout << wc[i].count << " (" << p << ") : " << wc[i].word.toUtf8().data() << endl; + } + } + + return 0; + } +}; + +HOOT_FACTORY_REGISTER(Command, PrintNamesCmd) + +} diff --git a/pool/shard007/C++/0091592_controller.cpp b/pool/shard007/C++/0091592_controller.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e453733add79719a4bb6d0a2e8d2e9669feac420 --- /dev/null +++ b/pool/shard007/C++/0091592_controller.cpp @@ -0,0 +1,290 @@ +/***************************************************************************//** +* \file controller.cpp +* +* \brief Simple PID controller with dynamic reconfigure and diagnostics +* \author Andy Zelenak +* \date March 8, 2015 +* +* \section license License (BSD-3) +* Copyright (c) 2015, Andy Zelenak\n +* 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 Willow Garage, 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 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. +******************************************************************************/ + +// Subscribe to a topic about the state of a dynamic system and calculate feedback to +// stabilize it. + +#include <pid/controller.h> +#include <pid/PidConfig.h> + +#include <dynamic_reconfigure/server.h> +#include <ros/time.h> + +void setpoint_callback(const std_msgs::Float64& setpoint_msg) +{ + setpoint = setpoint_msg.data; +} + +void plant_state_callback(const std_msgs::Float64& state_msg) +{ + + if ( !((Kp<=0. && Ki<=0. && Kd<=0.) || (Kp>=0. && Ki>=0. && Kd>=0.)) ) // All 3 gains should have the same sign + { + ROS_WARN("All three gains (Kp, Ki, Kd) should have the same sign for stability."); + } + + plant_state = state_msg.data; + + error.at(2) = error.at(1); + error.at(1) = error.at(0); + error.at(0) = setpoint - plant_state; // Current error goes to slot 0 + + // calculate delta_t + if (!prev_time.isZero()) // Not first time through the program + { + delta_t = ros::Time::now() - prev_time; + prev_time = ros::Time::now(); + if (0 == delta_t.toSec()) + { + ROS_ERROR("delta_t is 0, skipping this loop. Possible overloaded cpu at time: %f", ros::Time::now().toSec()); + return; + } + } + else + { + ROS_INFO("prev_time is 0, doing nothing"); + prev_time = ros::Time::now(); + return; + } + + // integrate the error + error_integral += error.at(0) * delta_t.toSec(); + + // Apply windup limit to limit the size of the integral term + if ( error_integral > fabsf(windup_limit)) + error_integral = fabsf(windup_limit); + + if ( error_integral < -fabsf(windup_limit)) + error_integral = -fabsf(windup_limit); + + // My filter reference was Julius O. Smith III, Intro. to Digital Filters With Audio Applications. + if (cutoff_frequency != -1) + { + // Check if tan(_) is really small, could cause c = NaN + tan_filt = tan( (cutoff_frequency*6.2832)*delta_t.toSec()/2 ); + + // Avoid tan(0) ==> NaN + if ( (tan_filt<=0.) && (tan_filt>-0.01) ) + tan_filt = -0.01; + if ( (tan_filt>=0.) && (tan_filt<0.01) ) + tan_filt = 0.01; + + c = 1/tan_filt; + } + + filtered_error.at(2) = filtered_error.at(1); + filtered_error.at(1) = filtered_error.at(0); + filtered_error.at(0) = (1/(1+c*c+1.414*c))*(error.at(2)+2*error.at(1)+error.at(0)-(c*c-1.414*c+1)*filtered_error.at(2)-(-2*c*c+2)*filtered_error.at(1)); + + // Take derivative of error + // First the raw, unfiltered data: + error_deriv.at(2) = error_deriv.at(1); + error_deriv.at(1) = error_deriv.at(0); + error_deriv.at(0) = (error.at(0)-error.at(1))/delta_t.toSec(); + + filtered_error_deriv.at(2) = filtered_error_deriv.at(1); + filtered_error_deriv.at(1) = filtered_error_deriv.at(0); + + if ( loop_counter>2 ) // Let some data accumulate + filtered_error_deriv.at(0) = (1/(1+c*c+1.414*c))*(error_deriv.at(2)+2*error_deriv.at(1)+error_deriv.at(0)-(c*c-1.414*c+1)*filtered_error_deriv.at(2)-(-2*c*c+2)*filtered_error_deriv.at(1)); + else + loop_counter++; + + // calculate the control effort + proportional = Kp * filtered_error.at(0); + integral = Ki * error_integral; + derivative = Kd * filtered_error_deriv.at(0); + control_effort = proportional + integral + derivative; + + // Apply saturation limits + if (control_effort > upper_limit) + control_effort = upper_limit; + if (control_effort < lower_limit) + control_effort = lower_limit; + + ++measurements_received; + diags->freq_status.tick(); + diags->diag_updater.update(); + + // Publish the stabilizing control effort if the controller is enabled + if (pid_enabled) + { + control_msg.data = control_effort; + + control_effort_pub.publish(control_msg); + } + else + { + error_integral = 0.0; + } + + return; +} + +void pid_enable_callback(const std_msgs::Bool& pid_enable_msg) +{ + pid_enabled = pid_enable_msg.data; +} + +bool first_reconfig = true; + +void reconfigure_callback(pid::PidConfig &config, uint32_t level) +{ + if (first_reconfig) + { + first_reconfig = false; + return; // Ignore the first call to reconfigure which happens at startup + } + + Kp = config.Kp * config.Kp_scale; + Ki = config.Ki * config.Ki_scale; + Kd = config.Kd * config.Kd_scale; + ROS_INFO("Pid reconfigure request: Kp: %f, Ki: %f, Kd: %f", Kp, Ki, Kd); +} + +void get_pid_diag_status(diagnostic_updater::DiagnosticStatusWrapper& pid_diag_status) +{ + pid_diag_status.summary(diagnostic_msgs::DiagnosticStatus::OK, "PID controller nominal"); + pid_diag_status.add("Setpoint", setpoint); + pid_diag_status.add("Pid Controller input", plant_state); + pid_diag_status.add("Error", error.at(0)); + pid_diag_status.add("Control output effort", control_effort); + pid_diag_status.add("Proportional effort", proportional); + pid_diag_status.add("Integral effort", integral); + pid_diag_status.add("Derivative effort", derivative); + pid_diag_status.add("Measurements received", measurements_received); +} + + //////////////////////////////////// + // Error checking + //////////////////////////////////// + +bool validate_parameters() +{ + if ( lower_limit > upper_limit ) + { + ROS_ERROR("The lower saturation limit cannot be greater than the upper saturation limit."); + return(false); + } + + return true;; +} + + //////////////////////////////////// + // Display parameters + //////////////////////////////////// +void print_parameters() +{ + std::cout<< std::endl<<"PID PARAMETERS"<<std::endl<<"-----------------------------------------"<<std::endl; + std::cout << "Kp: " << Kp << ", Ki: " << Ki << ", Kd: " << Kd << std::endl; + if ( cutoff_frequency== -1) // If the cutoff frequency was not specified by the user + std::cout<<"LPF cutoff frequency: 1/4 of sampling rate"<<std::endl; + else + std::cout<<"LPF cutoff frequency: "<< cutoff_frequency << std::endl; + std::cout << "pid node name: " << ros::this_node::getName() << std::endl; + std::cout << "Name of topic from controller: " << topic_from_controller << std::endl; + std::cout << "Name of topic from the plant: " << topic_from_plant << std::endl; + std::cout << "Name of setpoint topic: " << setpoint_topic << std::endl; + std::cout << "Integral-windup limit: " << windup_limit << std::endl; + std::cout << "Saturation limits: " << upper_limit << "/" << lower_limit << std::endl; + std::cout << "-----------------------------------------" << std::endl; + + return; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// Main +//////////////////////////////////////////////////////////////////////////////////////// + +int main(int argc, char **argv) +{ + ROS_INFO("Starting pid with node name %s", node_name.c_str()); + + // Initialize ROS stuff + ros::init(argc, argv, node_name); // Note node_name can be overidden by launch file + ros::NodeHandle node; + ros::NodeHandle node_priv("~"); + + while (ros::Time(0) == ros::Time::now()) + { + ROS_INFO("controller spinning waiting for time to become non-zero"); + sleep(1); + } + + // Get params if specified in launch file or as params on command-line, set defaults + node_priv.param<double>("Kp", Kp, 1.0); + node_priv.param<double>("Ki", Ki, 0.0); + node_priv.param<double>("Kd", Kd, 0.0); + node_priv.param<double>("upper_limit", upper_limit, 1000.0); + node_priv.param<double>("lower_limit", lower_limit, -1000.0); + node_priv.param<double>("windup_limit", windup_limit, 1000.0); + node_priv.param<double>("cutoff_frequency", cutoff_frequency, -1.0); + node_priv.param<std::string>("topic_from_controller", topic_from_controller, "control_effort"); + node_priv.param<std::string>("topic_from_plant", topic_from_plant, "state"); + node_priv.param<std::string>("setpoint_topic", setpoint_topic, "setpoint"); + + // Update params if specified as command-line options, & print settings + print_parameters(); + if (not validate_parameters()) + { + std::cout << "Error: invalid parameter\n"; + } + + // instantiate publishers & subscribers + control_effort_pub = node.advertise<std_msgs::Float64>(topic_from_controller, 1); + + ros::Subscriber sub = node.subscribe(topic_from_plant, 1, plant_state_callback ); + ros::Subscriber setpoint_sub = node.subscribe(setpoint_topic, 1, setpoint_callback ); + ros::Subscriber pid_enabled_sub = node.subscribe("pid_enable", 1, pid_enable_callback ); + + // configure dynamic reconfiguration + dynamic_reconfigure::Server<pid::PidConfig> config_server; + dynamic_reconfigure::Server<pid::PidConfig>::CallbackType f; + f = boost::bind(&reconfigure_callback, _1, _2); + config_server.setCallback(f); + + // initialize diagnostics updaters + diags = new PidControllerDiags; + + diags->diag_updater.setHardwareID(node_name); + diags->diag_updater.add(diags->freq_status); + diags->diag_updater.add("PID status", get_pid_diag_status); + + // Respond to inputs until shut down + ros::spin(); + + return 0; +} + diff --git a/pool/shard007/C++/0091596_postEffectTask.cpp b/pool/shard007/C++/0091596_postEffectTask.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9fa665af55aa7872721962284925f623a466df3b --- /dev/null +++ b/pool/shard007/C++/0091596_postEffectTask.cpp @@ -0,0 +1,57 @@ +#include "stdafx.h" +#include "postEffectTask.h" +#include "app/renderer.h" +#include "app/renderPass/postEffectPass.h" + +namespace luna{ + LUNA_IMPLEMENT_CONCRETE(luna::PostEffectTask); + + PostEffectTask::PostEffectTask() + { + } + + PostEffectTask::~PostEffectTask() + { + } + + bool PostEffectTask::load() + { + return true; + } + + void PostEffectTask::fixup() + { + auto& context = Renderer::instance().getContext(); + + Renderer::instance().getPostEffect().addTask(this); + } + + void PostEffectTask::update() + { + const f32 ratio = getRatio(); + + } + + void PostEffectTask::fixedUpdate() + { + const f32 ratio = getRatio(); + + } + + void PostEffectTask::draw(Renderer& renderer) + { + const f32 ratio = getRatio(); + } + + void PostEffectTask::onRender(const luna::TypeInfo& type, RenderPassContext& rpc, Renderer& renderer, u32& arg) + { + const f32 ratio = getRatio(); + + } + + void PostEffectTask::reset() + { + + } +} + diff --git a/pool/shard007/C++/0091614_Text.cpp b/pool/shard007/C++/0091614_Text.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1db039b6dd2d74256bbe9a896e9a8fffe1612a97 --- /dev/null +++ b/pool/shard007/C++/0091614_Text.cpp @@ -0,0 +1,42 @@ +#include "Text.h" +////////////////////////////////////////////////////////////////////// +// Construction/Destruction +////////////////////////////////////////////////////////////////////// +CText::CText(){ + m_xpos = 0; + m_ypos = 0; + date_format = L"ddd, d. MMM yyyy"; + m_nAlignment = DT_LEFT; +} + +CText::~CText(){ +} + +void CText::Paint(HDC drawdc){ + HFONT hFontOld; + RECT rect; + SIZE size; + hFontOld = (HFONT)SelectObject(drawdc, m_hFont); + GetTextExtentPoint32(drawdc, date_format.c_str(), _tcslen(date_format.c_str()), &size); + rect.left = m_xpos; + rect.top = m_ypos; + rect.right = rect.left + size.cx; + rect.bottom = rect.top + size.cy; + if(m_nAlignment == DT_RIGHT){ + rect.left -= size.cx; + rect.right -= size.cx; + }else if(m_nAlignment == DT_CENTER){ + rect.left -= (size.cx / 2); + rect.right -= (size.cx / 2); + } + SetTextColor(drawdc, m_rgbFontColor); + if(m_selected){ + HBRUSH hBrush; + hBrush = CreateSolidBrush(GetSysColor(COLOR_HIGHLIGHT)); + FillRect(drawdc, &m_rect, hBrush); + DeleteObject(hBrush); + } + DrawText(drawdc, date_format.c_str(), -1, &rect, m_nAlignment); + m_rect = rect; + SelectObject(drawdc, hFontOld); +} diff --git a/pool/shard007/C++/0091619_app_command.cc b/pool/shard007/C++/0091619_app_command.cc new file mode 100644 index 0000000000000000000000000000000000000000..0e777e99318e2b56331c62bdbeb71701d73b7277 --- /dev/null +++ b/pool/shard007/C++/0091619_app_command.cc @@ -0,0 +1,99 @@ +// Copyright (c) 2011 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 "chrome/installer/util/app_command.h" + +#include <stddef.h> + +#include "base/cxx17_backports.h" +#include "base/logging.h" +#include "base/win/registry.h" +#include "chrome/installer/util/google_update_constants.h" +#include "chrome/installer/util/work_item_list.h" + +namespace installer { + +// static +// Associate bool member variables with registry entries. +const AppCommand::NamedBoolVar AppCommand::kNameBoolVars[] = { + {&AppCommand::sends_pings_, google_update::kRegSendsPingsField}, + {&AppCommand::is_web_accessible_, google_update::kRegWebAccessibleField}, + {&AppCommand::is_auto_run_on_os_upgrade_, + google_update::kRegAutoRunOnOSUpgradeField}, + {&AppCommand::is_run_as_user_, google_update::kRegRunAsUserField}, +}; + +AppCommand::AppCommand() + : sends_pings_(false), + is_web_accessible_(false), + is_auto_run_on_os_upgrade_(false), + is_run_as_user_(false) {} + +AppCommand::AppCommand(const std::wstring& command_line) + : command_line_(command_line), + sends_pings_(false), + is_web_accessible_(false), + is_auto_run_on_os_upgrade_(false), + is_run_as_user_(false) {} + +bool AppCommand::Initialize(const base::win::RegKey& key) { + if (!key.Valid()) { + LOG(DFATAL) << "Cannot initialize an AppCommand from an invalid key."; + return false; + } + + LONG result = ERROR_SUCCESS; + std::wstring cmd_line; + + result = key.ReadValue(google_update::kRegCommandLineField, &cmd_line); + if (result != ERROR_SUCCESS) { + LOG(WARNING) << "Error reading " << google_update::kRegCommandLineField + << " value from registry: " << result; + return false; + } + + command_line_.swap(cmd_line); + + for (size_t i = 0; i < base::size(kNameBoolVars); ++i) { + DWORD value = 0; // Set default to false. + // Note: ReadValueDW only modifies out param on success. + key.ReadValueDW(kNameBoolVars[i].name, &value); + this->*(kNameBoolVars[i].data) = (value != 0); + } + + return true; +} + +void AppCommand::AddWorkItems(HKEY predefined_root, + const std::wstring& command_path, + WorkItemList* item_list) const { + // Command_path is derived from GetRegCommandKey which always returns + // value from GetClientsKeyPath() which should be 32-bit hive. + item_list + ->AddCreateRegKeyWorkItem(predefined_root, command_path, KEY_WOW64_32KEY) + ->set_log_message("creating AppCommand registry key"); + item_list + ->AddSetRegValueWorkItem(predefined_root, command_path, KEY_WOW64_32KEY, + google_update::kRegCommandLineField, + command_line_, true) + ->set_log_message("setting AppCommand CommandLine registry value"); + + for (size_t i = 0; i < base::size(kNameBoolVars); ++i) { + const wchar_t* var_name = kNameBoolVars[i].name; + bool var_data = this->*(kNameBoolVars[i].data); + + // Adds a work item to set |var_name| to DWORD 1 if |var_data| is true; + // adds a work item to remove |var_name| otherwise. + if (var_data) { + item_list->AddSetRegValueWorkItem(predefined_root, command_path, + KEY_WOW64_32KEY, var_name, + static_cast<DWORD>(1), true); + } else { + item_list->AddDeleteRegValueWorkItem(predefined_root, command_path, + KEY_WOW64_32KEY, var_name); + } + } +} + +} // namespace installer diff --git a/pool/shard007/C++/0091622_GlDrawPrimitive.cpp b/pool/shard007/C++/0091622_GlDrawPrimitive.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6d646f1f7025bbe520bc605a38728139896a3982 --- /dev/null +++ b/pool/shard007/C++/0091622_GlDrawPrimitive.cpp @@ -0,0 +1,70 @@ +#include <common.h> +#pragma hdrstop + +#include <GlDrawPrimitive.h> + +namespace Fangame { + +////////////////////////////////////////////////////////////////////////// + +void CGlDrawPrimitive::setLayout( CPixelRect quadRect ) +{ + quad.SetBaseRect( getCommonRect() ); + setSizeParams( quadRect ); +} + +void CGlDrawPrimitive::setRawData( CPixelRect quadRect, const CStackArray<TVector2, 4>& textureData ) +{ + quad.SetRawData( getCommonRect(), textureData ); + setSizeParams( quadRect ); +} + +TAARect CGlDrawPrimitive::getCommonRect() const +{ + return TAARect{ 0.0f, 1.0f, 1.0f, 0.0f }; +} + +void CGlDrawPrimitive::setSizeParams( CPixelRect sizeRect ) +{ + quadSize = CPixelVector{ sizeRect.Width(), sizeRect.Height() }; + quadOffset = sizeRect.BottomLeft(); +} + +TMatrix3 CGlDrawPrimitive::getAlignedMatrix( const TMatrix3& modelToClip ) const +{ + const auto& pixelToClip = Coordinates::PixelToClip(); + const CClipVector pixelSize{ pixelToClip( 0, 0 ), pixelToClip( 1, 1 ) }; + const auto baseScale = GetScale( modelToClip ); + const auto scale = findImageScale( baseScale, pixelSize ); + const auto offset = findImageOffset( GetOffset( modelToClip ), baseScale, pixelSize ); + return CreateTransformation( offset, scale ); +} + +TVector2 CGlDrawPrimitive::findImageScale( TVector2 baseScale, CClipVector pixelSize ) const +{ + const auto totalX = baseScale.X() * quadSize.X(); + const auto totalY = baseScale.Y() * quadSize.Y(); + + const auto alignedX = RoundFloatTo( totalX, pixelSize.X() ); + const auto alignedY = RoundFloatTo( totalY, pixelSize.Y() ); + + return TVector2{ alignedX, alignedY }; +} + +TVector2 CGlDrawPrimitive::findImageOffset( TVector2 baseOffset, TVector2 baseScale, CClipVector pixelSize ) const +{ + // Rectangle offset must put the rectangle on the pixel grid. + const TVector2 scaledOffset( quadOffset.X() * baseScale.X(), quadOffset.Y() * baseScale.Y() ); + const auto baseX = RoundFloatTo( scaledOffset.X(), pixelSize.X() ); + const auto baseY = RoundFloatTo( scaledOffset.Y(), pixelSize.Y() ); + return TVector2{ baseX + baseOffset.X(), baseY + baseOffset.Y() }; +} + +void CGlDrawPrimitive::draw( CShaderProgram shader ) const +{ + quad.Draw( shader ); +} + +////////////////////////////////////////////////////////////////////////// + +} // namespace Fangame. diff --git a/pool/shard007/C++/0091628_OSCHierarchicalNamespace.cc b/pool/shard007/C++/0091628_OSCHierarchicalNamespace.cc new file mode 100644 index 0000000000000000000000000000000000000000..d24068208c048f37ff3fbf52d1e23e3738cdad50 --- /dev/null +++ b/pool/shard007/C++/0091628_OSCHierarchicalNamespace.cc @@ -0,0 +1,107 @@ +/* Open SoundControl kit in C++ */ +/* Copyright (C) 2002-2004 libOSC++ contributors. See AUTHORS */ +/* */ +/* This library is free software; you can redistribute it and/or */ +/* modify it under the terms of the GNU Lesser General Public */ +/* License as published by the Free Software Foundation; either */ +/* version 2.1 of the License, or (at your option) any later version. */ +/* */ +/* This library is distributed in the hope that it will be useful, */ +/* but WITHOUT ANY WARRANTY; without even the implied warranty of */ +/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */ +/* Lesser General Public License for more details. */ +/* */ +/* You should have received a copy of the GNU Lesser General Public */ +/* License along with this library; if not, write to the Free Software */ +/* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ +/* */ +/* For questions regarding this program contact */ +/* Daniel Holth <dholth@fastmail.fm> or visit */ +/* http://wiretap.stetson.edu/trac/ */ + +/** + * @file OSCHierarchicalNamespace.cc + * + * Hierarchical implementation of a namespace, including pattern matching. + * + * @bug Does not yet implement 'remove' + * @bug needs testing + * + * @author Daniel Holth + */ + +#include "OSCHierarchicalNamespace.h" + +OSCHierarchicalNamespace::OSCHierarchicalNamespace() +{ + this->myRoot = new OSCNamespaceItem(); +} + + +OSCHierarchicalNamespace::~OSCHierarchicalNamespace() +{ + delete this->getRoot(); +} + + +bool OSCHierarchicalNamespace::add(const std::string &address, + OSCCallable *thingamabob) +{ + OSCNamespaceItem *root; + + root = this->getRoot(); + return root->add(address, thingamabob); +} + + +bool OSCHierarchicalNamespace::remove(const std::string& address) +{ + return false; +} + + +OSCCallable* OSCHierarchicalNamespace::find(const std::string& address) +{ + return NULL; +} + + +// listing will be internal to the namespace +std::vector<std::string> OSCHierarchicalNamespace::list(const std::string& basename) +{ + std::vector<std::string> addresses; + OSCNamespaceItem *root; + root = this->getRoot(); + // root->traverse((void*)&addresses, &dispatchOSC) + return addresses; +} + +// this is confusing. +typedef std::pair <const std::string, Transmit*> Cook; + +void dispatchOSC(void *cookie, std::vector < std::string > &address, OSCNamespaceItem *item) +{ + OSCCallable *callback; + + if(item != NULL) + { + callback = item->getCallable(); + if(callback != NULL && cookie != NULL) + { + callback->call(((Cook*)cookie)->first, ((Cook*)cookie)->second); + } + } +} + + +bool OSCHierarchicalNamespace::dispatch(const std::string &address, + const std::string &data, + Transmit *const reply) +{ + OSCNamespaceItem *root; + Cook cookie(data, reply); + + root = this->getRoot(); + return root->traverse(address, &dispatchOSC, (void*)&cookie); +} + diff --git a/pool/shard007/C++/0091638_sendcoinsentry.cpp b/pool/shard007/C++/0091638_sendcoinsentry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e1add560d844c585ce406cac0aa1f5fb75f8caeb --- /dev/null +++ b/pool/shard007/C++/0091638_sendcoinsentry.cpp @@ -0,0 +1,172 @@ +#include "sendcoinsentry.h" +#include "ui_sendcoinsentry.h" +#include "guiutil.h" +#include "bitcoinunits.h" +#include "addressbookpage.h" +#include "walletmodel.h" +#include "optionsmodel.h" +#include "addresstablemodel.h" + +#include <QApplication> +#include <QClipboard> + +SendCoinsEntry::SendCoinsEntry(QWidget *parent) : + QFrame(parent), + ui(new Ui::SendCoinsEntry), + model(0) +{ + ui->setupUi(this); + +#ifdef Q_WS_MAC + ui->payToLayout->setSpacing(4); +#endif +#if QT_VERSION >= 0x040700 + /* Do not move this to the XML file, Qt before 4.7 will choke on it */ + ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); + ui->payTo->setPlaceholderText(tr("Enter a TradeCoin address (they start with an 'm')")); +#endif + setFocusPolicy(Qt::TabFocus); + setFocusProxy(ui->payTo); + + GUIUtil::setupAddressWidget(ui->payTo, this); +} + +SendCoinsEntry::~SendCoinsEntry() +{ + delete ui; +} + +void SendCoinsEntry::on_pasteButton_clicked() +{ + // Paste text from clipboard into recipient field + ui->payTo->setText(QApplication::clipboard()->text()); +} + +void SendCoinsEntry::on_addressBookButton_clicked() +{ + if(!model) + return; + AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); + dlg.setModel(model->getAddressTableModel()); + if(dlg.exec()) + { + ui->payTo->setText(dlg.getReturnValue()); + ui->payAmount->setFocus(); + } +} + +void SendCoinsEntry::on_payTo_textChanged(const QString &address) +{ + if(!model) + return; + // Fill in label from address book, if address has an associated label + QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); + if(!associatedLabel.isEmpty()) + ui->addAsLabel->setText(associatedLabel); +} + +void SendCoinsEntry::setModel(WalletModel *model) +{ + this->model = model; + + if(model && model->getOptionsModel()) + connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); + + clear(); +} + +void SendCoinsEntry::setRemoveEnabled(bool enabled) +{ + ui->deleteButton->setEnabled(enabled); +} + +void SendCoinsEntry::clear() +{ + ui->payTo->clear(); + ui->addAsLabel->clear(); + ui->payAmount->clear(); + ui->payTo->setFocus(); + // update the display unit, to not use the default ("BTC") + updateDisplayUnit(); +} + +void SendCoinsEntry::on_deleteButton_clicked() +{ + emit removeEntry(this); +} + +bool SendCoinsEntry::validate() +{ + // Check input validity + bool retval = true; + + if(!ui->payAmount->validate()) + { + retval = false; + } + else + { + if(ui->payAmount->value() <= 0) + { + // Cannot send 0 coins or less + ui->payAmount->setValid(false); + retval = false; + } + } + + if(!ui->payTo->hasAcceptableInput() || + (model && !model->validateAddress(ui->payTo->text()))) + { + ui->payTo->setValid(false); + retval = false; + } + + return retval; +} + +SendCoinsRecipient SendCoinsEntry::getValue() +{ + SendCoinsRecipient rv; + + rv.address = ui->payTo->text(); + rv.label = ui->addAsLabel->text(); + rv.amount = ui->payAmount->value(); + + return rv; +} + +QWidget *SendCoinsEntry::setupTabChain(QWidget *prev) +{ + QWidget::setTabOrder(prev, ui->payTo); + QWidget::setTabOrder(ui->payTo, ui->addressBookButton); + QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); + QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); + QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel); + return ui->payAmount->setupTabChain(ui->addAsLabel); +} + +void SendCoinsEntry::setValue(const SendCoinsRecipient &value) +{ + ui->payTo->setText(value.address); + ui->addAsLabel->setText(value.label); + ui->payAmount->setValue(value.amount); +} + +bool SendCoinsEntry::isClear() +{ + return ui->payTo->text().isEmpty(); +} + +void SendCoinsEntry::setFocus() +{ + ui->payTo->setFocus(); +} + +void SendCoinsEntry::updateDisplayUnit() +{ + if(model && model->getOptionsModel()) + { + // Update payAmount with the current unit + ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); + } +} diff --git a/pool/shard007/C++/0091640_DragImageWin.cpp b/pool/shard007/C++/0091640_DragImageWin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6399ea23ed4c47d8a73a3c00533206c40ebd0b81 --- /dev/null +++ b/pool/shard007/C++/0091640_DragImageWin.cpp @@ -0,0 +1,219 @@ +/* + * Copyright (C) 2007, 2008, 2013 Apple 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: + * 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. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 "config.h" +#include "DragImage.h" + +#include "Element.h" +#include "FloatRoundedRect.h" +#include "FontCascade.h" +#include "FontDescription.h" +#include "FontSelector.h" +#include "GraphicsContext.h" +#include "HWndDC.h" +#include "Image.h" +#include "URL.h" +#include "StringTruncator.h" +#include "TextIndicator.h" +#include "TextRun.h" +#include "WebCoreTextRenderer.h" +#include <wtf/RetainPtr.h> +#include <wtf/win/GDIObject.h> + +#include <windows.h> + +namespace WebCore { + +GDIObject<HBITMAP> allocImage(HDC, IntSize, PlatformGraphicsContext** targetRef); +void deallocContext(PlatformGraphicsContext* target); + +IntSize dragImageSize(DragImageRef image) +{ + if (!image) + return IntSize(); + BITMAP b; + GetObject(image, sizeof(BITMAP), &b); + return IntSize(b.bmWidth, b.bmHeight); +} + +void deleteDragImage(DragImageRef image) +{ + if (image) + ::DeleteObject(image); +} + +DragImageRef dissolveDragImageToFraction(DragImageRef image, float) +{ + //We don't do this on windows as the dragimage is blended by the OS + return image; +} + +DragImageRef createDragImageIconForCachedImageFilename(const String& filename) +{ + SHFILEINFO shfi = {0}; + String fname = filename; + if (FAILED(SHGetFileInfo(static_cast<LPCWSTR>(fname.charactersWithNullTermination().data()), FILE_ATTRIBUTE_NORMAL, + &shfi, sizeof(shfi), SHGFI_ICON | SHGFI_USEFILEATTRIBUTES))) + return 0; + + ICONINFO iconInfo; + if (!GetIconInfo(shfi.hIcon, &iconInfo)) { + DestroyIcon(shfi.hIcon); + return 0; + } + + DestroyIcon(shfi.hIcon); + DeleteObject(iconInfo.hbmMask); + + return iconInfo.hbmColor; +} + +const float DragLabelBorderX = 4; +// Keep border_y in synch with DragController::LinkDragBorderInset. +const float DragLabelBorderY = 2; +const float DragLabelRadius = 5; +const float LabelBorderYOffset = 2; + +const float MinDragLabelWidthBeforeClip = 120; +const float MaxDragLabelWidth = 200; +const float MaxDragLabelStringWidth = (MaxDragLabelWidth - 2 * DragLabelBorderX); + +const float DragLinkLabelFontsize = 11; +const float DragLinkUrlFontSize = 10; + +static FontCascade dragLabelFont(int size, bool bold, FontRenderingMode renderingMode) +{ + FontCascade result; + NONCLIENTMETRICS metrics; + metrics.cbSize = sizeof(metrics); + SystemParametersInfo(SPI_GETNONCLIENTMETRICS, metrics.cbSize, &metrics, 0); + + FontCascadeDescription description; + description.setWeight(bold ? boldWeightValue() : normalWeightValue()); + description.setOneFamily(metrics.lfSmCaptionFont.lfFaceName); + description.setSpecifiedSize((float)size); + description.setComputedSize((float)size); + description.setRenderingMode(renderingMode); + result = FontCascade(description, 0, 0); + result.update(0); + return result; +} + +DragImageRef createDragImageForLink(Element&, URL& url, const String& inLabel, TextIndicatorData&, FontRenderingMode fontRenderingMode, float) +{ + // This is more or less an exact match for the Mac OS X code. + + const FontCascade* labelFont; + const FontCascade* urlFont; + + if (fontRenderingMode == FontRenderingMode::Alternate) { + static const FontCascade alternateRenderingModeLabelFont = dragLabelFont(DragLinkLabelFontsize, true, FontRenderingMode::Alternate); + static const FontCascade alternateRenderingModeURLFont = dragLabelFont(DragLinkUrlFontSize, false, FontRenderingMode::Alternate); + labelFont = &alternateRenderingModeLabelFont; + urlFont = &alternateRenderingModeURLFont; + } else { + static const FontCascade normalRenderingModeLabelFont = dragLabelFont(DragLinkLabelFontsize, true, FontRenderingMode::Normal); + static const FontCascade normalRenderingModeURLFont = dragLabelFont(DragLinkUrlFontSize, false, FontRenderingMode::Normal); + labelFont = &normalRenderingModeLabelFont; + urlFont = &normalRenderingModeURLFont; + } + + bool drawURLString = true; + bool clipURLString = false; + bool clipLabelString = false; + + String urlString = url.string(); + String label = inLabel; + if (label.isEmpty()) { + drawURLString = false; + label = urlString; + } + + // First step in drawing the link drag image width. + TextRun labelRun(label); + TextRun urlRun(urlString); + IntSize labelSize(labelFont->width(labelRun), labelFont->fontMetrics().ascent() + labelFont->fontMetrics().descent()); + + if (labelSize.width() > MaxDragLabelStringWidth) { + labelSize.setWidth(MaxDragLabelStringWidth); + clipLabelString = true; + } + + IntSize urlStringSize; + IntSize imageSize(labelSize.width() + DragLabelBorderX * 2, labelSize.height() + DragLabelBorderY * 2); + + if (drawURLString) { + urlStringSize.setWidth(urlFont->width(urlRun)); + urlStringSize.setHeight(urlFont->fontMetrics().ascent() + urlFont->fontMetrics().descent()); + imageSize.setHeight(imageSize.height() + urlStringSize.height()); + if (urlStringSize.width() > MaxDragLabelStringWidth) { + imageSize.setWidth(MaxDragLabelWidth); + clipURLString = true; + } else + imageSize.setWidth(std::max(labelSize.width(), urlStringSize.width()) + DragLabelBorderX * 2); + } + + // We now know how big the image needs to be, so we create and + // fill the background + HWndDC dc(0); + auto workingDC = adoptGDIObject(::CreateCompatibleDC(dc)); + if (!workingDC) + return 0; + + PlatformGraphicsContext* contextRef; + auto image = allocImage(workingDC.get(), imageSize, &contextRef); + if (!image) + return 0; + + ::SelectObject(workingDC.get(), image.get()); + GraphicsContext context(contextRef); + // On Mac alpha is {0.7, 0.7, 0.7, 0.8}, however we can't control alpha + // for drag images on win, so we use 1 + static const Color backgroundColor(140, 140, 140); + static const IntSize radii(DragLabelRadius, DragLabelRadius); + IntRect rect(0, 0, imageSize.width(), imageSize.height()); + context.fillRoundedRect(FloatRoundedRect(rect, radii, radii, radii, radii), backgroundColor); + + // Draw the text + static const Color topColor(0, 0, 0, 255); // original alpha = 0.75 + static const Color bottomColor(255, 255, 255, 127); // original alpha = 0.5 + if (drawURLString) { + if (clipURLString) + urlString = StringTruncator::rightTruncate(urlString, imageSize.width() - (DragLabelBorderX * 2.0f), *urlFont); + IntPoint textPos(DragLabelBorderX, imageSize.height() - (LabelBorderYOffset + urlFont->fontMetrics().descent())); + WebCoreDrawDoubledTextAtPoint(context, urlString, textPos, *urlFont, topColor, bottomColor); + } + + if (clipLabelString) + label = StringTruncator::rightTruncate(label, imageSize.width() - (DragLabelBorderX * 2.0f), *labelFont); + + IntPoint textPos(DragLabelBorderX, DragLabelBorderY + labelFont->pixelSize()); + WebCoreDrawDoubledTextAtPoint(context, label, textPos, *labelFont, topColor, bottomColor); + + deallocContext(contextRef); + return image.leak(); +} + +} diff --git a/pool/shard007/C++/0091644_version_tests.cpp b/pool/shard007/C++/0091644_version_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7cd80d465a1ce8f263b7dfcffc65034164f5497a --- /dev/null +++ b/pool/shard007/C++/0091644_version_tests.cpp @@ -0,0 +1,143 @@ +/* + * Copyright 2013 Matthew Harvey + * + * 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 "version.hpp" +#include <UnitTest++/UnitTest++.h> +#include <iterator> +#include <sstream> + +using jewel::Version; +using std::ostringstream; +using std::wostringstream; +using std::begin; +using std::end; + +TEST(version_basic) +{ + Version v0(1, 0, 0); + CHECK_EQUAL(v0.major(), 1U); + CHECK_EQUAL(v0.minor(), 0U); + CHECK_EQUAL(v0.patch(), 0U); + + Version const v1(23, 8, 10); + CHECK_EQUAL(v1.major(), 23U); + CHECK_EQUAL(v1.minor(), 8U); + CHECK_EQUAL(v1.patch(), 10U); + + Version const v2(v1); + CHECK_EQUAL(v2.major(), v1.major()); + CHECK_EQUAL(v2.minor(), v1.minor()); + CHECK_EQUAL(v2.patch(), v1.patch()); + CHECK_EQUAL(v2.patch(), 10U); + + v0 = v2; + CHECK_EQUAL(v0.major(), v2.major()); + CHECK_EQUAL(v0.major(), 23U); + CHECK_EQUAL(v0.minor(), 8U); + CHECK_EQUAL(v0.patch(), v2.patch()); +} + +TEST(version_output) +{ + Version const v0(12, 0, 306); + ostringstream oss0; + oss0 << v0; + CHECK_EQUAL(oss0.str(), "12.0.306"); + + Version const v1(0, 69, 50); + ostringstream oss1; + oss1 << v1; + CHECK_EQUAL(oss1.str(), "0.69.50"); + + wostringstream woss1; + woss1 << v1; + CHECK(woss1.str() == L"0.69.50"); +} + +TEST(version_comparison) +{ + CHECK (Version(0, 0, 0) < Version(1, 1, 1)); + CHECK (Version(1, 0, 0) > Version(0, 14, 0)); + CHECK (Version(30, 12, 6) == Version(30, 12, 6)); + CHECK (Version(0, 12, 3) != Version(3, 12, 0)); + CHECK (Version(3, 2, 1) <= Version(3, 2, 1)); + CHECK (Version(18, 3, 6) >= Version(17, 6, 3)); + Version const versions[] = + { Version(0, 0, 0), + Version(0, 0, 1), + Version(0, 0, 2986), + Version(0, 1, 0), + Version(0, 1, 1), + Version(0, 1, 90), + Version(1, 0, 0), + Version(1, 9, 3), + Version(2, 0, 5), + Version(29768, 0, 0), + Version(297681, 0, 0), + Version(297681, 0, 3), + Version(297681, 2, 0) + }; + size_t const sz = end(versions) - begin(versions); + for (size_t i = 0; i != sz; ++i) + { + for (size_t j = 0; j != sz; ++j) + { + if (i == j) + { + CHECK_EQUAL(versions[i], versions[j]); + CHECK(versions[i] <= versions[j]); + CHECK(versions[j] <= versions[i]); + CHECK(versions[i] >= versions[j]); + CHECK(versions[j] >= versions[i]); + CHECK(!(versions[i] < versions[j])); + CHECK(!(versions[j] < versions[i])); + CHECK(!(versions[i] > versions[j])); + CHECK(!(versions[i] > versions[j])); + CHECK(!(versions[i] != versions[j])); + CHECK(!(versions[j] != versions[i])); + } + else if (i < j) + { + CHECK(versions[i] < versions[j]); + CHECK(versions[i] <= versions[j]); + CHECK(versions[i] != versions[j]); + CHECK(versions[j] > versions[i]); + CHECK(versions[j] >= versions[i]); + CHECK(!(versions[j] < versions[i])); + CHECK(!(versions[j] <= versions[i])); + CHECK(!(versions[j] == versions[i])); + CHECK(!(versions[i] == versions[j])); + CHECK(!(versions[i] > versions[j])); + CHECK(!(versions[i] >= versions[j])); + } + else if (i > j) + { + CHECK(versions[j] < versions[i]); + CHECK(versions[j] <= versions[i]); + CHECK(versions[j] != versions[i]); + CHECK(versions[i] > versions[j]); + CHECK(versions[i] >= versions[j]); + CHECK(!(versions[i] < versions[j])); + CHECK(!(versions[i] <= versions[j])); + CHECK(!(versions[i] == versions[j])); + CHECK(!(versions[j] == versions[i])); + CHECK(!(versions[j] > versions[i])); + CHECK(!(versions[j] >= versions[i])); + } + } + } +} + diff --git a/pool/shard007/C++/0091649_unordered_map_hash_func02.cpp b/pool/shard007/C++/0091649_unordered_map_hash_func02.cpp new file mode 100644 index 0000000000000000000000000000000000000000..97f29b7cdb3a1f694c57d083e854d37b95bd9db6 --- /dev/null +++ b/pool/shard007/C++/0091649_unordered_map_hash_func02.cpp @@ -0,0 +1,37 @@ +#include <iostream> +#include <functional> +#include <string> +#include <utility> +#include <unordered_map> + +using std::string; + +struct Key { + string first; + string second; + int third; + bool operator==(const Key& other) const { + return (first == other.first && second == other.second && third == other.third); + } +}; + +struct KeyHasher { + std::size_t operator()(const Key& k) const { + using std::hash; + return ( (hash<string>()(k.first)) + ^ ((hash<string>()(k.second) << 1) >> 1) + ^ (hash<int>()(k.third) << 1) ); + } +}; + +int main() +{ + std::unordered_map<Key, string, KeyHasher> mp = { + {{"John", "Doe", 12}, "first"}, + {{"Mary", "Sue", 11}, "second"} + }; + + Key John {"John", "Doe", 12}; + auto iter = mp.find(John); + std::cout << iter->second << std::endl; +} diff --git a/pool/shard007/C++/0091653_NytramBox2DRunner.cpp b/pool/shard007/C++/0091653_NytramBox2DRunner.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f02f833809a93a6d77788d5fc80dfb16188d4364 --- /dev/null +++ b/pool/shard007/C++/0091653_NytramBox2DRunner.cpp @@ -0,0 +1,76 @@ +// NytramBox2DRunner.cpp : Defines the entry point for the console application. +// + +#include "stdafx.h" +#include "NytramBox2D.h" + +#include <iostream> +using namespace std; + +void CollisionStart(unsigned int colliderA, unsigned int colliderB) +{ + cout << colliderA << " hit " << colliderB << endl; +} + +void CollisionStop(unsigned int colliderA, unsigned int colliderB) +{ + cout << colliderA << " stopped hitting " << colliderB << endl; +} + + +int _tmain(int argc, _TCHAR* argv[]) +{ + BodyDef bodyDef; + bodyDef.type = b2BodyType::b2_dynamicBody; + bodyDef.position.Set(0, 20); + bodyDef.fixedRotation = true; + + BodyDef bodyDef2; + bodyDef2.type = b2BodyType::b2_staticBody; + bodyDef2.position.Set(0, 0); + + BodyDef bodyDef3; + bodyDef3.type = b2BodyType::b2_staticBody; + bodyDef3.position.Set(0, 1); + + FixtureDef fixtureDef; + fixtureDef.userData = (void*) 1; + fixtureDef.restitution = 1; + FixtureDef fixtureDef2; + fixtureDef2.userData = (void*) 2; + FixtureDef fixtureDef3; + fixtureDef3.userData = (void*) 3; + fixtureDef3.isSensor = true; + + unsigned int worldId = World_Add(b2Vec2(0, -10)); + Collision_SetStartCallback(CollisionStart); + Collision_SetStopCallback(CollisionStop); + + unsigned int bodyId = World_AddBody(worldId, bodyDef); + unsigned int fixtureId = Body_AddBoxFixture(bodyId, fixtureDef, 2, 2); + unsigned int bodyId2 = World_AddBody(worldId, bodyDef2); + unsigned int fixtureId2 = Body_AddEdgeFixture(bodyId2, fixtureDef2, b2Vec2(-10, 0), b2Vec2(10, 0)); + unsigned int bodyId3 = World_AddBody(worldId, bodyDef3); + unsigned int fixtureId3 = Body_AddBoxFixture(bodyId3, fixtureDef3, 20, 2); + + const b2Vec2 v = Body_GetPosition(bodyId3); + cout << "X: " << v.x << " Y: " << v.y << endl; + + for (int i = 0; i < 2*60; i++) + { + World_Step(worldId, 1/60.0, 10, 10); + const b2Vec2 v = Body_GetPosition(bodyId); + cout << "X: " << v.x << " Y: " << v.y << endl; + } + system("PAUSE"); + for (int i = 0; i < 4*60; i++) + { + World_Step(worldId, 1/60.0, 10, 10); + const b2Vec2 v = Body_GetPosition(bodyId); + cout << "X: " << v.x << " Y: " << v.y << endl; + } + + system("PAUSE"); + return 0; +} + diff --git a/pool/shard007/C++/0091655_abstract_pipeline_node.cpp b/pool/shard007/C++/0091655_abstract_pipeline_node.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fe25d5ab6bf1533a7b9545ca593b9ac57a0724de --- /dev/null +++ b/pool/shard007/C++/0091655_abstract_pipeline_node.cpp @@ -0,0 +1,64 @@ +#include "pipeline/abstract_pipeline_head.hpp" +#include "pipeline/abstract_pipeline_node.hpp" + +using namespace std; +using namespace pipeline; + +AbstractPipelineNode :: AbstractPipelineNode () +: head_(nullptr), + output_preservation_mode_(OutputPreservationMode::kNone) +{ +} + +AbstractPipelineNode :: ~AbstractPipelineNode () +{ +} + +string AbstractPipelineNode :: ConnectOutput ( + shared_ptr<AbstractPipelineNode> output_node) +{ + if (output_node_) { + return "Pipeline node's output is already connected to another node"; + } + + output_node_ = output_node; + + return ""; +} + +void AbstractPipelineNode :: SubmitThreadWork (ThreadSquad::ThreadWorkUnit work) +{ + AbstractPipelineHead* typed_head = dynamic_cast<AbstractPipelineHead*>(head_); + + // The pipeline head was initially received as an AbstractPipelineHead, so + // the dynamic cast should always succeed + assert(typed_head); + + typed_head->SubmitThreadWorkToHead(work); +} + +AbstractPipelineNode::ReturnReason AbstractPipelineNode :: InterruptibleSleep ( + double seconds) +{ + AbstractPipelineHead* typed_head = dynamic_cast<AbstractPipelineHead*>(head_); + + // The pipeline head was initially received as an AbstractPipelineHead, so + // the dynamic cast should always succeed + assert(typed_head); + + return typed_head->InterruptibleSleep(seconds); +} + +void AbstractPipelineNode :: SetHead (AbstractPipelineHead* head) +{ + // This method is for internal use only, so the validity of <head> should + // be guaranteed + assert(head); + + head_ = head; +} + +void AbstractPipelineNode :: InvalidateHead () +{ + head_ = nullptr; +} diff --git a/pool/shard007/C++/0091656_output_stream_manager.cc b/pool/shard007/C++/0091656_output_stream_manager.cc new file mode 100644 index 0000000000000000000000000000000000000000..0784bdccc922dd8d8dff0bd0289b07afca48b64f --- /dev/null +++ b/pool/shard007/C++/0091656_output_stream_manager.cc @@ -0,0 +1,218 @@ +// Copyright 2019 The MediaPipe Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "mediapipe/framework/output_stream_manager.h" + +#include "absl/synchronization/mutex.h" +#include "mediapipe/framework/input_stream_handler.h" +#include "mediapipe/framework/port/status_builder.h" + +namespace mediapipe { + +absl::Status OutputStreamManager::Initialize(const std::string& name, + const PacketType* packet_type) { + output_stream_spec_.name = name; + output_stream_spec_.packet_type = packet_type; + output_stream_spec_.offset_enabled = false; + PrepareForRun(nullptr); + return absl::OkStatus(); +} + +void OutputStreamManager::PrepareForRun( + std::function<void(absl::Status)> error_callback) { + output_stream_spec_.error_callback = std::move(error_callback); + + output_stream_spec_.locked_intro_data = false; + output_stream_spec_.header = Packet(); + { + absl::MutexLock lock(&stream_mutex_); + next_timestamp_bound_ = Timestamp::PreStream(); + closed_ = false; + } +} + +void OutputStreamManager::Close() { + { + absl::MutexLock lock(&stream_mutex_); + if (closed_) { + return; + } + closed_ = true; + next_timestamp_bound_ = Timestamp::Done(); + } + + for (const auto& mirror : mirrors_) { + mirror.input_stream_handler->SetNextTimestampBound(mirror.id, + Timestamp::Done()); + } +} + +bool OutputStreamManager::IsClosed() const { + absl::MutexLock lock(&stream_mutex_); + return closed_; +} + +void OutputStreamManager::PropagateHeader() { + if (output_stream_spec_.locked_intro_data) { + output_stream_spec_.TriggerErrorCallback( + mediapipe::FailedPreconditionErrorBuilder(MEDIAPIPE_LOC) + << "PropagateHeader must be called in CalculatorNode::OpenNode(). " + "Stream: \"" + << output_stream_spec_.name << "\"."); + return; + } + for (auto& mirror : mirrors_) { + mirror.input_stream_handler->SetHeader(mirror.id, + output_stream_spec_.header); + } +} + +void OutputStreamManager::AddMirror(InputStreamHandler* input_stream_handler, + CollectionItemId id) { + CHECK(input_stream_handler); + mirrors_.emplace_back(input_stream_handler, id); +} + +void OutputStreamManager::SetMaxQueueSize(int max_queue_size) { + for (auto& mirror : mirrors_) { + mirror.input_stream_handler->SetMaxQueueSize(mirror.id, max_queue_size); + } +} + +Timestamp OutputStreamManager::NextTimestampBound() const { + absl::MutexLock lock(&stream_mutex_); + return next_timestamp_bound_; +} + +// TODO Consider moving the output bound computing logic to +// OutputStreamHandler. +Timestamp OutputStreamManager::ComputeOutputTimestampBound( + const OutputStreamShard& output_stream_shard, + Timestamp input_timestamp) const { + // This function is called for Calculator::Open() and Calculator::Process(). + // It is not called for Calculator::Close() because the output timestamp bound + // is always Timestamp::Done(). + if (input_timestamp != Timestamp::Unstarted() && + !input_timestamp.IsAllowedInStream()) { + output_stream_spec_.TriggerErrorCallback( + mediapipe::FailedPreconditionErrorBuilder(MEDIAPIPE_LOC) + << "Invalid input timestamp to compute the output timestamp bound. " + "Stream: \"" + << output_stream_spec_.name + << "\", Timestamp: " << input_timestamp.DebugString() << "."); + return Timestamp::Unset(); + } + // new_bound = max(AddOffset(completed_timestamp) + 1, + // MaxOutputTimestamp(completed_timestamp) + 1) + // Note that "MaxOutputTimestamp()" must consider both output packet + // timetstamp and SetNextTimestampBound values. + Timestamp input_bound; + if (output_stream_spec_.offset_enabled && + input_timestamp != Timestamp::Unstarted()) { + if (input_timestamp == Timestamp::PreStream()) { + // Timestamp::PreStream() is a special value that we shouldn't apply any + // offset. + input_bound = Timestamp::Min(); + } else if (input_timestamp == Timestamp::Max()) { + // If the offset is positive or zero, we set the input_bound to + // Timestamp::PostStream() since the calculator might process + // Timestamp::PostStream() in the next invocation. + if (output_stream_spec_.offset >= 0) { + input_bound = Timestamp::PostStream(); + } else { + input_bound = (input_timestamp + output_stream_spec_.offset) + .NextAllowedInStream(); + } + } else if (input_timestamp == Timestamp::PostStream()) { + // For Timestamp::PostStream(), it's expected that no futher timestamps + // will occur. + input_bound = Timestamp::OneOverPostStream(); + } else { + input_bound = + input_timestamp.NextAllowedInStream() + output_stream_spec_.offset; + } + } + Timestamp new_bound; + // The input_bound if it is greater than the shard bound. + if (input_bound > output_stream_shard.NextTimestampBound()) { + new_bound = std::max(new_bound, input_bound); + } + // The bound defined by SetNextTimestampBound. + new_bound = + std::max(new_bound, output_stream_shard.updated_next_timestamp_bound_); + // The bound defined by added packets. + if (!output_stream_shard.IsEmpty()) { + new_bound = std::max( + new_bound, + output_stream_shard.LastAddedPacketTimestamp().NextAllowedInStream()); + } + return new_bound; +} + +// TODO Consider moving the propagation logic to OutputStreamHandler. +void OutputStreamManager::PropagateUpdatesToMirrors( + Timestamp next_timestamp_bound, OutputStreamShard* output_stream_shard) { + CHECK(output_stream_shard); + { + if (next_timestamp_bound != Timestamp::Unset()) { + absl::MutexLock lock(&stream_mutex_); + next_timestamp_bound_ = next_timestamp_bound; + } + } + std::list<Packet>* packets_to_propagate = output_stream_shard->OutputQueue(); + VLOG(3) << "Output stream: " << Name() + << " queue size: " << packets_to_propagate->size(); + VLOG(3) << "Output stream: " << Name() + << " next timestamp: " << next_timestamp_bound; + bool add_packets = !packets_to_propagate->empty(); + bool set_bound = + (next_timestamp_bound != Timestamp::Unset()) && + (!add_packets || + packets_to_propagate->back().Timestamp().NextAllowedInStream() != + next_timestamp_bound); + int mirror_count = mirrors_.size(); + for (int idx = 0; idx < mirror_count; ++idx) { + const Mirror& mirror = mirrors_[idx]; + if (add_packets) { + // If the stream is the last element in mirrors_, moves packets from + // output_queue_. Otherwise, copies the packets. + if (idx == mirror_count - 1) { + mirror.input_stream_handler->MovePackets(mirror.id, + packets_to_propagate); + } else { + mirror.input_stream_handler->AddPackets(mirror.id, + *packets_to_propagate); + } + } + if (set_bound) { + mirror.input_stream_handler->SetNextTimestampBound(mirror.id, + next_timestamp_bound); + } + } + // Clear out the packets. + packets_to_propagate->clear(); +} + +void OutputStreamManager::ResetShard(OutputStreamShard* output_stream_shard) { + Timestamp next_timestamp_bound; + bool closed = false; + absl::MutexLock lock(&stream_mutex_); + { + next_timestamp_bound = next_timestamp_bound_; + closed = closed_; + } + output_stream_shard->Reset(next_timestamp_bound, closed); +} + +} // namespace mediapipe diff --git a/pool/shard007/C++/0091661_Job.cpp b/pool/shard007/C++/0091661_Job.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b739afd761b59a7cd42ffd473ce8e5fccd7ec682 --- /dev/null +++ b/pool/shard007/C++/0091661_Job.cpp @@ -0,0 +1,232 @@ +/* +* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ +#include <aws/elastictranscoder/model/Job.h> +#include <aws/core/utils/json/JsonSerializer.h> + +#include <utility> + +using namespace Aws::ElasticTranscoder::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +Job::Job() : + m_idHasBeenSet(false), + m_arnHasBeenSet(false), + m_pipelineIdHasBeenSet(false), + m_inputHasBeenSet(false), + m_outputHasBeenSet(false), + m_outputsHasBeenSet(false), + m_outputKeyPrefixHasBeenSet(false), + m_playlistsHasBeenSet(false), + m_statusHasBeenSet(false), + m_userMetadataHasBeenSet(false), + m_timingHasBeenSet(false) +{ +} + +Job::Job(const JsonValue& jsonValue) : + m_idHasBeenSet(false), + m_arnHasBeenSet(false), + m_pipelineIdHasBeenSet(false), + m_inputHasBeenSet(false), + m_outputHasBeenSet(false), + m_outputsHasBeenSet(false), + m_outputKeyPrefixHasBeenSet(false), + m_playlistsHasBeenSet(false), + m_statusHasBeenSet(false), + m_userMetadataHasBeenSet(false), + m_timingHasBeenSet(false) +{ + *this = jsonValue; +} + +Job& Job::operator =(const JsonValue& jsonValue) +{ + if(jsonValue.ValueExists("Id")) + { + m_id = jsonValue.GetString("Id"); + + m_idHasBeenSet = true; + } + + if(jsonValue.ValueExists("Arn")) + { + m_arn = jsonValue.GetString("Arn"); + + m_arnHasBeenSet = true; + } + + if(jsonValue.ValueExists("PipelineId")) + { + m_pipelineId = jsonValue.GetString("PipelineId"); + + m_pipelineIdHasBeenSet = true; + } + + if(jsonValue.ValueExists("Input")) + { + m_input = jsonValue.GetObject("Input"); + + m_inputHasBeenSet = true; + } + + if(jsonValue.ValueExists("Output")) + { + m_output = jsonValue.GetObject("Output"); + + m_outputHasBeenSet = true; + } + + if(jsonValue.ValueExists("Outputs")) + { + Array<JsonValue> outputsJsonList = jsonValue.GetArray("Outputs"); + for(unsigned outputsIndex = 0; outputsIndex < outputsJsonList.GetLength(); ++outputsIndex) + { + m_outputs.push_back(outputsJsonList[outputsIndex].AsObject()); + } + m_outputsHasBeenSet = true; + } + + if(jsonValue.ValueExists("OutputKeyPrefix")) + { + m_outputKeyPrefix = jsonValue.GetString("OutputKeyPrefix"); + + m_outputKeyPrefixHasBeenSet = true; + } + + if(jsonValue.ValueExists("Playlists")) + { + Array<JsonValue> playlistsJsonList = jsonValue.GetArray("Playlists"); + for(unsigned playlistsIndex = 0; playlistsIndex < playlistsJsonList.GetLength(); ++playlistsIndex) + { + m_playlists.push_back(playlistsJsonList[playlistsIndex].AsObject()); + } + m_playlistsHasBeenSet = true; + } + + if(jsonValue.ValueExists("Status")) + { + m_status = jsonValue.GetString("Status"); + + m_statusHasBeenSet = true; + } + + if(jsonValue.ValueExists("UserMetadata")) + { + Aws::Map<Aws::String, JsonValue> userMetadataJsonMap = jsonValue.GetObject("UserMetadata").GetAllObjects(); + for(auto& userMetadataItem : userMetadataJsonMap) + { + m_userMetadata[userMetadataItem.first] = userMetadataItem.second.AsString(); + } + m_userMetadataHasBeenSet = true; + } + + if(jsonValue.ValueExists("Timing")) + { + m_timing = jsonValue.GetObject("Timing"); + + m_timingHasBeenSet = true; + } + + return *this; +} + +JsonValue Job::Jsonize() const +{ + JsonValue payload; + + if(m_idHasBeenSet) + { + payload.WithString("Id", m_id); + + } + + if(m_arnHasBeenSet) + { + payload.WithString("Arn", m_arn); + + } + + if(m_pipelineIdHasBeenSet) + { + payload.WithString("PipelineId", m_pipelineId); + + } + + if(m_inputHasBeenSet) + { + payload.WithObject("Input", m_input.Jsonize()); + + } + + if(m_outputHasBeenSet) + { + payload.WithObject("Output", m_output.Jsonize()); + + } + + if(m_outputsHasBeenSet) + { + Array<JsonValue> outputsJsonList(m_outputs.size()); + for(unsigned outputsIndex = 0; outputsIndex < outputsJsonList.GetLength(); ++outputsIndex) + { + outputsJsonList[outputsIndex].AsObject(m_outputs[outputsIndex].Jsonize()); + } + payload.WithArray("Outputs", std::move(outputsJsonList)); + + } + + if(m_outputKeyPrefixHasBeenSet) + { + payload.WithString("OutputKeyPrefix", m_outputKeyPrefix); + + } + + if(m_playlistsHasBeenSet) + { + Array<JsonValue> playlistsJsonList(m_playlists.size()); + for(unsigned playlistsIndex = 0; playlistsIndex < playlistsJsonList.GetLength(); ++playlistsIndex) + { + playlistsJsonList[playlistsIndex].AsObject(m_playlists[playlistsIndex].Jsonize()); + } + payload.WithArray("Playlists", std::move(playlistsJsonList)); + + } + + if(m_statusHasBeenSet) + { + payload.WithString("Status", m_status); + + } + + if(m_userMetadataHasBeenSet) + { + JsonValue userMetadataJsonMap; + for(auto& userMetadataItem : m_userMetadata) + { + userMetadataJsonMap.WithString(userMetadataItem.first, userMetadataItem.second); + } + payload.WithObject("UserMetadata", std::move(userMetadataJsonMap)); + + } + + if(m_timingHasBeenSet) + { + payload.WithObject("Timing", m_timing.Jsonize()); + + } + + return std::move(payload); +} \ No newline at end of file diff --git a/pool/shard007/C++/0091670_web_encrypted_media_request.cc b/pool/shard007/C++/0091670_web_encrypted_media_request.cc new file mode 100644 index 0000000000000000000000000000000000000000..e0a066e3e09a00e4dd8090119abe72dece580b10 --- /dev/null +++ b/pool/shard007/C++/0091670_web_encrypted_media_request.cc @@ -0,0 +1,60 @@ +// 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 "third_party/blink/public/platform/web_encrypted_media_request.h" + +#include "third_party/blink/public/platform/web_media_key_system_configuration.h" +#include "third_party/blink/public/platform/web_security_origin.h" +#include "third_party/blink/public/platform/web_string.h" +#include "third_party/blink/public/platform/web_vector.h" +#include "third_party/blink/renderer/platform/encrypted_media_request.h" +#include "third_party/blink/renderer/platform/weborigin/security_origin.h" + +namespace blink { + +WebEncryptedMediaRequest::WebEncryptedMediaRequest( + const WebEncryptedMediaRequest& request) { + Assign(request); +} + +WebEncryptedMediaRequest::WebEncryptedMediaRequest( + EncryptedMediaRequest* request) + : private_(request) {} + +WebEncryptedMediaRequest::~WebEncryptedMediaRequest() { + Reset(); +} + +WebString WebEncryptedMediaRequest::KeySystem() const { + return private_->KeySystem(); +} + +const WebVector<WebMediaKeySystemConfiguration>& +WebEncryptedMediaRequest::SupportedConfigurations() const { + return private_->SupportedConfigurations(); +} + +WebSecurityOrigin WebEncryptedMediaRequest::GetSecurityOrigin() const { + return WebSecurityOrigin(private_->GetSecurityOrigin()); +} + +void WebEncryptedMediaRequest::RequestSucceeded( + std::unique_ptr<WebContentDecryptionModuleAccess> access) { + private_->RequestSucceeded(std::move(access)); +} + +void WebEncryptedMediaRequest::RequestNotSupported( + const WebString& error_message) { + private_->RequestNotSupported(error_message); +} + +void WebEncryptedMediaRequest::Assign(const WebEncryptedMediaRequest& other) { + private_ = other.private_; +} + +void WebEncryptedMediaRequest::Reset() { + private_.Reset(); +} + +} // namespace blink diff --git a/pool/shard007/C++/0091673_Extents.cpp b/pool/shard007/C++/0091673_Extents.cpp new file mode 100644 index 0000000000000000000000000000000000000000..848c1fb3fde13c7c09ee6c5b39bb2d362982381f --- /dev/null +++ b/pool/shard007/C++/0091673_Extents.cpp @@ -0,0 +1,136 @@ +//===--------------------------------------------------------------------------------*- C++ -*-===// +// _ +// | | +// __| | __ ___ ___ ___ +// / _` |/ _` \ \ /\ / / '_ | +// | (_| | (_| |\ V V /| | | | +// \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain +// +// +// This file is distributed under the MIT License (MIT). +// See LICENSE.txt for details. +// +//===------------------------------------------------------------------------------------------===// + +#include "dawn/Optimizer/Extents.h" +#include "dawn/Support/Assert.h" +#include "dawn/Support/StringUtil.h" +#include <iostream> + +namespace dawn { + +Extents::Extents() : extents_{} {} + +Extents::Extents(const Array3i& offset) { merge(offset); } + +Extents::Extents(int extent1Minus, int extent1Plus, int extent2Minus, int extent2Plus, + int extent3Minus, int extent3Plus) { + extents_[0].Minus = extent1Minus; + extents_[0].Plus = extent1Plus; + extents_[1].Minus = extent2Minus; + extents_[1].Plus = extent2Plus; + extents_[2].Minus = extent3Minus; + extents_[2].Plus = extent3Plus; +} + +void Extents::merge(const Extents& other) { + DAWN_ASSERT(extents_.size() == other.extents_.size()); + for(std::size_t i = 0; i < extents_.size(); ++i) + extents_[i].merge(other.extents_[i]); +} + +void Extents::expand(const Extents& other) { + DAWN_ASSERT(extents_.size() == other.extents_.size()); + + for(std::size_t i = 0; i < extents_.size(); ++i) + extents_[i].expand(other.extents_[i]); +} + +void Extents::merge(const Array3i& offset) { + DAWN_ASSERT(extents_.size() == offset.size()); + + for(std::size_t i = 0; i < extents_.size(); ++i) + extents_[i].merge(offset[i] >= 0 ? Extent{0, offset[i]} : Extent{offset[i], 0}); +} + +void Extents::add(const Extents& other) { + DAWN_ASSERT(extents_.size() == other.extents_.size()); + + for(std::size_t i = 0; i < extents_.size(); ++i) + extents_[i].add(other.extents_[i]); +} + +Extents Extents::add(const Extents& lhs, const Extents& rhs) { + Extents sum; + for(std::size_t i = 0; i < sum.extents_.size(); ++i) + sum.extents_[i] = Extent::add(lhs.extents_[i], rhs.extents_[i]); + return sum; +} + +void Extents::add(const Array3i& offset) { + DAWN_ASSERT(extents_.size() == offset.size()); + + for(std::size_t i = 0; i < extents_.size(); ++i) + extents_[i].add(offset[i]); +} + +bool Extents::empty() { return extents_.empty(); } + +bool Extents::isPointwise() const { + return isPointwiseInDim(0) && isPointwiseInDim(1) && isPointwiseInDim(2); +} + +bool Extents::isPointwiseInDim(int dim) const { + return (extents_[dim].Minus == 0 && extents_[dim].Plus == 0); +} + +bool Extents::isHorizontalPointwise() const { return isPointwiseInDim(0) && isPointwiseInDim(1); } +bool Extents::isVerticalPointwise() const { return isPointwiseInDim(2); } + +Extents::VerticalLoopOrderAccess +Extents::getVerticalLoopOrderAccesses(LoopOrderKind loopOrder) const { + VerticalLoopOrderAccess access{false, false}; + + if(isVerticalPointwise()) + return access; + + const Extent& verticalExtent = extents_[2]; + + switch(loopOrder) { + case LoopOrderKind::LK_Parallel: + // Any accesses in the vertical are against the loop-order + return VerticalLoopOrderAccess{true, true}; + + case LoopOrderKind::LK_Forward: { + // Accesses k+1 are against the loop order + if(verticalExtent.Plus > 0) + access.CounterLoopOrder = true; + if(verticalExtent.Minus < 0) + access.LoopOrder = true; + break; + } + case LoopOrderKind::LK_Backward: + // Accesses k-1 are against the loop order + if(verticalExtent.Minus < 0) + access.CounterLoopOrder = true; + if(verticalExtent.Plus > 0) + access.LoopOrder = true; + break; + } + + return access; +} + +bool Extents::operator==(const Extents& other) const { + return (extents_[0] == other[0] && extents_[1] == other[1] && extents_[2] == other[2]); +} + +bool Extents::operator!=(const Extents& other) const { return !(*this == other); } + +std::ostream& operator<<(std::ostream& os, const Extents& extent) { + return (os << RangeToString()(extent.getExtents(), [](const Extent& e) -> std::string { + return "(" + std::to_string(e.Minus) + ", " + std::to_string(e.Plus) + ")"; + })); +} + +} // namespace dawn diff --git a/pool/shard007/C++/0091677_elf.cpp b/pool/shard007/C++/0091677_elf.cpp new file mode 100644 index 0000000000000000000000000000000000000000..04bfe07d70e762229030cf073fdbdae9e2cef301 --- /dev/null +++ b/pool/shard007/C++/0091677_elf.cpp @@ -0,0 +1,127 @@ +/* ELF executable loader. + Copyright (C) 2015 Shaun Ren. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ + +#include "elf.h" +#include <paging.h> +#include <memory.h> +#include <lib/string.h> +#include <errno.h> +#include <algorithm> + + +using namespace paging; +using std::max; + +namespace elf +{ + +bool Elf32_Ehdr::valid() const +{ + if (memcmp(e_ident, ELFMAG, SELFMAG) || + e_ident[EI_CLASS] != ELFCLASS32 || + e_ident[EI_DATA] != ELFDATA2LSB || + e_machine != EM_386 || + e_ident[EI_VERSION] != EV_CURRENT || + e_ident[EI_OSABI] != ELFOSABI_NONE || + (e_type != ET_REL && e_type != ET_EXEC)) { + return false; + } + return true; +} + +const char* Elf32_Ehdr::strtab() const +{ + if (e_shstrndx == SHN_UNDEF) return nullptr; + return (const char*)this + (get_shdr() + e_shstrndx)->sh_offset; +} + +const char* Elf32_Ehdr::get_str(size_t offset) const +{ + auto strtab = this->strtab(); + return !strtab ? nullptr : strtab + offset; +} + +// dir must contain the current kernel stack and buf +// this function will load dir in the process +int load(const void* buf, page_dir* dir, Elf32_Addr& entry, void*& brk_start) +{ + if (unlikely(!buf || !dir)) + return -EFAULT; + + const Elf32_Ehdr* hdr = (const Elf32_Ehdr*) buf; + if (!hdr->valid()) + return -ENOEXEC; + + auto phdr = hdr->get_phdr(); + if (unlikely(!phdr)) + return -ENOEXEC; + + brk_start = (void*) 0; + + for (unsigned i=0; i < hdr->e_phnum; ++i, ++phdr) { + if (phdr->p_type == PT_PHDR) + continue; // ignore + if (phdr->p_type == PT_LOAD) { + const auto vaddr_start = phdr->p_vaddr & ~(PAGE_SIZE - 1); + const auto vaddr_end = memory::align_addr(phdr->p_vaddr + + phdr->p_memsz); + if (!dir->alloc_block((void*)vaddr_start, + vaddr_end - vaddr_start, + PAGE_PRESENT|PAGE_US|PAGE_RW)) + return -ENOMEM; + brk_start = (void*) max((uintptr_t)brk_start, vaddr_end); + } else + return -EINVAL; + } + + phdr = hdr->get_phdr(); + + paging::switch_page_dir(dir); + + // copy over the contents + for (unsigned i=0; i < hdr->e_phnum; ++i, ++phdr) { + if (phdr->p_type == PT_PHDR) + continue; // ignore + + if (unlikely(phdr->p_filesz & 3)) + memcpy((void*)phdr->p_vaddr, (char*)buf + phdr->p_offset, phdr->p_filesz); + else + memcpyd((void*)phdr->p_vaddr, (char*)buf + phdr->p_offset, phdr->p_filesz/4); + // clear extra memory to 0 + if (phdr->p_memsz > phdr->p_filesz) { + const auto sz = phdr->p_memsz - phdr->p_filesz; + if (unlikely(sz & 3)) + memset((char*)phdr->p_vaddr + phdr->p_filesz, 0, sz); + else + memsetd((char*)phdr->p_vaddr + phdr->p_filesz, 0, sz/4); + } + + if (phdr->p_align >= PAGE_SIZE && !(phdr->p_flags & PF_W)) { + // set pages as read-only if we are able to + const auto vaddr_start = phdr->p_vaddr & ~(PAGE_SIZE - 1); + const auto vaddr_end = memory::align_addr(phdr->p_vaddr + + phdr->p_memsz); + for (auto addr = vaddr_start; addr < vaddr_end; addr += PAGE_SIZE) + dir->get_page((void*)addr)->rw = false; + } + } + + entry = hdr->e_entry; + + return 0; +} + +} diff --git a/pool/shard007/C++/0091680_048.cpp b/pool/shard007/C++/0091680_048.cpp new file mode 100644 index 0000000000000000000000000000000000000000..db58ec35d4139e27c03647fe8ada7688344ee839 --- /dev/null +++ b/pool/shard007/C++/0091680_048.cpp @@ -0,0 +1,25 @@ +#include "euler.h" +#include "util/range.h" +#include <gmpxx.h> +using namespace util; +using namespace math; + +// The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. +// +// Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. + +std::string euler048() +{ + mpz_class num, tmp; + for(auto i : range<1, 1001>()) + { + mpz_ui_pow_ui(tmp.get_mpz_t(), i, i); + num += tmp; + } + + std::string result = num.get_str(); + result.erase(result.begin(), result.end()-10); + return result; +} + +static bool reg_ = euler::set("48", euler048); diff --git a/pool/shard007/C++/0091690_EfectRigidbody.cpp b/pool/shard007/C++/0091690_EfectRigidbody.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5de3d34bbc6b13ba3bd7ad7f14588f4eeb9801e1 --- /dev/null +++ b/pool/shard007/C++/0091690_EfectRigidbody.cpp @@ -0,0 +1,32 @@ +#include <Re\Game\Efect\Physics\EfectRigidbody.h> +#include <Re\Game\GameActor.h> + +namespace Efect +{ + Rigidbody::Rigidbody() + { + ///static + def.type = b2_staticBody; + } + + Rigidbody::Rigidbody(float32 linearDamping, float32 angularDamping, bool fixedRotation, bool bullet, bool allowSleep, b2BodyType type) + { + def.type = type; + + def.angularDamping = angularDamping; + def.linearDamping = linearDamping; + def.allowSleep = allowSleep; + def.fixedRotation = fixedRotation; + def.bullet = bullet; + } + + void Rigidbody::onInit() + { + def.position.x = getOwner()->getPosition().x * toB2Position; + def.position.y = getOwner()->getPosition().y * toB2Position; + def.angle = getOwner()->getRotation().asRadian(); + + getOwner()->createRigidbody(def); + readyToRemove = true; + } +} \ No newline at end of file diff --git a/pool/shard007/C++/0091702_IViewToolSkin.cpp b/pool/shard007/C++/0091702_IViewToolSkin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dc22528e8a612a68f76c61ac82754b4e0c14ceb5 --- /dev/null +++ b/pool/shard007/C++/0091702_IViewToolSkin.cpp @@ -0,0 +1,135 @@ +/* + Copyright (c) 2013 yvt + + This file is part of OpenSpades. + + OpenSpades is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + OpenSpades is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with OpenSpades. If not, see <http://www.gnu.org/licenses/>. + + */ + +#include "ScriptManager.h" +#include "IViewToolSkin.h" +#include <Core/Debug.h> + +namespace spades{ + namespace client { + ScriptIViewToolSkin::ScriptIViewToolSkin(asIScriptObject *obj): + obj(obj){} + + void ScriptIViewToolSkin::SetEyeMatrix(Matrix4 m) { + SPADES_MARK_FUNCTION_DEBUG(); + static ScriptFunction func("IViewToolSkin", + "void set_EyeMatrix(Matrix4)"); + ScriptContextHandle ctx = func.Prepare(); + int r; + r = ctx->SetObject((void *)obj); + ScriptManager::CheckError(r); + r = ctx->SetArgObject(0, &m); + ScriptManager::CheckError(r); + ctx.ExecuteChecked(); + } + + void ScriptIViewToolSkin::SetSwing(spades::Vector3 v) { + SPADES_MARK_FUNCTION_DEBUG(); + static ScriptFunction func("IViewToolSkin", + "void set_Swing(Vector3)"); + ScriptContextHandle ctx = func.Prepare(); + int r; + r = ctx->SetObject((void *)obj); + ScriptManager::CheckError(r); + r = ctx->SetArgObject(0, &v); + ScriptManager::CheckError(r); + ctx.ExecuteChecked(); + } + + Vector3 ScriptIViewToolSkin::GetLeftHandPosition() { + SPADES_MARK_FUNCTION_DEBUG(); + static ScriptFunction func("IViewToolSkin", + "Vector3 get_LeftHandPosition()"); + ScriptContextHandle ctx = func.Prepare(); + int r; + r = ctx->SetObject((void *)obj); + ScriptManager::CheckError(r); + ctx.ExecuteChecked(); + return *reinterpret_cast<Vector3 *>(ctx->GetReturnObject()); + } + + Vector3 ScriptIViewToolSkin::GetRightHandPosition() { + SPADES_MARK_FUNCTION_DEBUG(); + static ScriptFunction func("IViewToolSkin", + "Vector3 get_RightHandPosition()"); + ScriptContextHandle ctx = func.Prepare(); + int r; + r = ctx->SetObject((void *)obj); + ScriptManager::CheckError(r); + ctx.ExecuteChecked(); + return *reinterpret_cast<Vector3 *>(ctx->GetReturnObject()); + } + + void ScriptIViewToolSkin::Draw2D() { + SPADES_MARK_FUNCTION_DEBUG(); + static ScriptFunction func("IViewToolSkin", + "void Draw2D()"); + ScriptContextHandle ctx = func.Prepare(); + int r; + r = ctx->SetObject((void *)obj); + ScriptManager::CheckError(r); + ctx.ExecuteChecked(); + } + + class IViewToolSkinRegistrar: public ScriptObjectRegistrar { + public: + IViewToolSkinRegistrar(): + ScriptObjectRegistrar("IViewToolSkin"){ + + } + virtual void Register(ScriptManager *manager, Phase phase) { + asIScriptEngine *eng = manager->GetEngine(); + int r; + eng->SetDefaultNamespace("spades"); + switch(phase){ + case PhaseObjectType: + r = eng->RegisterInterface("IViewToolSkin"); + manager->CheckError(r); + + + break; + case PhaseObjectMember: + r = eng->RegisterInterfaceMethod("IViewToolSkin", + "void set_EyeMatrix(Matrix4)"); + manager->CheckError(r); + r = eng->RegisterInterfaceMethod("IViewToolSkin", + "void set_Swing(Vector3)"); + manager->CheckError(r); + r = eng->RegisterInterfaceMethod("IViewToolSkin", + "Vector3 get_LeftHandPosition()"); + manager->CheckError(r); + r = eng->RegisterInterfaceMethod("IViewToolSkin", + "Vector3 get_RightHandPosition()"); + manager->CheckError(r); + r = eng->RegisterInterfaceMethod("IViewToolSkin", + "void Draw2D()"); + manager->CheckError(r); + break; + default: + + break; + } + } + }; + + static IViewToolSkinRegistrar registrar; + } +} + diff --git a/pool/shard007/C++/0091707_assign_value_op.cc b/pool/shard007/C++/0091707_assign_value_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..2351c0d80cfcc86175fb8569b2790b6b7260df44 --- /dev/null +++ b/pool/shard007/C++/0091707_assign_value_op.cc @@ -0,0 +1,99 @@ +// Copyright (c) 2018 PaddlePaddle 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 "paddle/fluid/operators/assign_value_op.h" + +#include <string> + +namespace paddle { +namespace framework { +class InferShapeContext; +class OpDesc; +template <typename T> +class EmptyGradOpMaker; +} // namespace framework +namespace imperative { +class OpBase; +} // namespace imperative +} // namespace paddle + +namespace paddle { +namespace operators { + +class AssignValueOp : public framework::OperatorWithKernel { + public: + AssignValueOp(const std::string &type, + const framework::VariableNameMap &inputs, + const framework::VariableNameMap &outputs, + const framework::AttributeMap &attrs) + : OperatorWithKernel(type, inputs, outputs, attrs) {} + + void InferShape(framework::InferShapeContext *ctx) const override { + PADDLE_ENFORCE_EQ( + ctx->HasOutput("Out"), true, + platform::errors::NotFound("Output(Out) of assign_op is not found.")); + auto shape = ctx->Attrs().Get<std::vector<int>>("shape"); + ctx->SetOutputDim("Out", phi::make_ddim(shape)); + } + + protected: + framework::OpKernelType GetExpectedKernelType( + const framework::ExecutionContext &ctx) const override { + return framework::OpKernelType( + framework::proto::VarType::Type(ctx.Attr<int>("dtype")), + ctx.GetPlace()); + } +}; + +class AssignValueOpMaker : public framework::OpProtoAndCheckerMaker { + public: + void Make() override { + AddOutput("Out", "(Tensor) Output tensor of assign_value operator."); + AddAttr<std::vector<int>>("shape", + "(vector<int>) " + "Shape of values."); + AddAttr<int>("dtype", "data type of values") + .InEnum({framework::proto::VarType::BOOL, + framework::proto::VarType::INT32, + framework::proto::VarType::FP32, + framework::proto::VarType::INT64}); + AddAttr<std::vector<int>>("bool_values", "store the bool values") + .SetDefault({}); + AddAttr<std::vector<float>>("fp32_values", "store the float32 values") + .SetDefault({}); + AddAttr<std::vector<int>>("int32_values", "store the int32 values") + .SetDefault({}); + AddAttr<std::vector<int64_t>>("int64_values", "store the int64 values") + .SetDefault({}); + AddComment(R"DOC( +AssignValue operator + +$$Out = values$$ +)DOC"); + } +}; + +} // namespace operators +} // namespace paddle + +namespace ops = paddle::operators; + +REGISTER_OPERATOR( + assign_value, ops::AssignValueOp, ops::AssignValueOpMaker, + paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>, + paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>); +REGISTER_OP_CPU_KERNEL(assign_value, ops::AssignValueKernel<bool>, + ops::AssignValueKernel<int>, + ops::AssignValueKernel<float>, + ops::AssignValueKernel<int64_t>); diff --git a/pool/shard007/C++/0091709_bitcoin.cpp b/pool/shard007/C++/0091709_bitcoin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9886c62ecee98bafb5f4d6654ec4cf933bcc0490 --- /dev/null +++ b/pool/shard007/C++/0091709_bitcoin.cpp @@ -0,0 +1,310 @@ +/* + * W.J. van der Laan 2011-2012 + */ + +#include <QApplication> + +#include "bitcoingui.h" +#include "clientmodel.h" +#include "walletmodel.h" +#include "optionsmodel.h" +#include "guiutil.h" +#include "guiconstants.h" +#include "init.h" +#include "util.h" +#include "ui_interface.h" +#include "paymentserver.h" +#include "splashscreen.h" + +#include <QMessageBox> +#if QT_VERSION < 0x050000 +#include <QTextCodec> +#endif +#include <QLocale> +#include <QTimer> +#include <QTranslator> +#include <QLibraryInfo> + +#ifdef Q_OS_MAC +#include "macdockiconhandler.h" +#endif + +#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) +#define _BITCOIN_QT_PLUGINS_INCLUDED +#define __INSURE__ +#include <QtPlugin> +Q_IMPORT_PLUGIN(qcncodecs) +Q_IMPORT_PLUGIN(qjpcodecs) +Q_IMPORT_PLUGIN(qtwcodecs) +Q_IMPORT_PLUGIN(qkrcodecs) +Q_IMPORT_PLUGIN(qtaccessiblewidgets) +#endif + +// Declare meta types used for QMetaObject::invokeMethod +Q_DECLARE_METATYPE(bool*) + +// Need a global reference for the notifications to find the GUI +static BitcoinGUI *guiref; +static SplashScreen *splashref; + +static bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) +{ + // Message from network thread + if(guiref) + { + bool modal = (style & CClientUIInterface::MODAL); + bool ret = false; + // In case of modal message, use blocking connection to wait for user to click a button + QMetaObject::invokeMethod(guiref, "message", + modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, + Q_ARG(QString, QString::fromStdString(caption)), + Q_ARG(QString, QString::fromStdString(message)), + Q_ARG(unsigned int, style), + Q_ARG(bool*, &ret)); + return ret; + } + else + { + printf("%s: %s\n", caption.c_str(), message.c_str()); + fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); + return false; + } +} + +static bool ThreadSafeAskFee(int64 nFeeRequired) +{ + if(!guiref) + return false; + if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon) + return true; + + bool payFee = false; + + QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), + Q_ARG(qint64, nFeeRequired), + Q_ARG(bool*, &payFee)); + + return payFee; +} + +static void InitMessage(const std::string &message) +{ + if(splashref) + { + splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55)); + qApp->processEvents(); + } + printf("init message: %s\n", message.c_str()); +} + +/* + Translate string to current locale using Qt. + */ +static std::string Translate(const char* psz) +{ + return QCoreApplication::translate("bitcoin-core", psz).toStdString(); +} + +/* Handle runaway exceptions. Shows a message box with the problem and quits the program. + */ +static void handleRunawayException(std::exception *e) +{ + PrintExceptionContinue(e, "Runaway exception"); + QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. sportcoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); + exit(1); +} + +#ifndef BITCOIN_QT_TEST +int main(int argc, char *argv[]) +{ + // Command-line options take precedence: + ParseParameters(argc, argv); + +#if QT_VERSION < 0x050000 + // Internal string conversion is all UTF-8 + QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); + QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); +#endif + + Q_INIT_RESOURCE(bitcoin); + QApplication app(argc, argv); + + // Register meta types used for QMetaObject::invokeMethod + qRegisterMetaType< bool* >(); + + // Do this early as we don't want to bother initializing if we are just calling IPC + // ... but do it after creating app, so QCoreApplication::arguments is initialized: + if (PaymentServer::ipcSendCommandLine()) + exit(0); + PaymentServer* paymentServer = new PaymentServer(&app); + + // Install global event filter that makes sure that long tooltips can be word-wrapped + app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); + + // ... then bitcoin.conf: + if (!boost::filesystem::is_directory(GetDataDir(false))) + { + // This message can not be translated, as translation is not initialized yet + // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) + QMessageBox::critical(0, "sportcoin", + QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); + return 1; + } + ReadConfigFile(mapArgs, mapMultiArgs); + + // Application identification (must be set before OptionsModel is initialized, + // as it is used to locate QSettings) + QApplication::setOrganizationName("sportcoin"); + QApplication::setOrganizationDomain("sportcoin.io"); + if(GetBoolArg("-testnet")) // Separate UI settings for testnet + QApplication::setApplicationName("sportcoin-Qt-testnet"); + else + QApplication::setApplicationName("sportcoin-Qt"); + + // ... then GUI settings: + OptionsModel optionsModel; + + // Get desired locale (e.g. "de_DE") from command line or use system locale + QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); + QString lang = lang_territory; + // Convert to "de" only by truncating "_DE" + lang.truncate(lang_territory.lastIndexOf('_')); + + QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; + // Load language files for configured locale: + // - First load the translator for the base language, without territory + // - Then load the more specific locale translator + + // Load e.g. qt_de.qm + if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) + app.installTranslator(&qtTranslatorBase); + + // Load e.g. qt_de_DE.qm + if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) + app.installTranslator(&qtTranslator); + + // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) + if (translatorBase.load(lang, ":/translations/")) + app.installTranslator(&translatorBase); + + // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) + if (translator.load(lang_territory, ":/translations/")) + app.installTranslator(&translator); + + // Subscribe to global signals from core + uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); + uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); + uiInterface.InitMessage.connect(InitMessage); + uiInterface.Translate.connect(Translate); + + // Show help message immediately after parsing command-line options (for "-lang") and setting locale, + // but before showing splash screen. + if (mapArgs.count("-?") || mapArgs.count("--help")) + { + GUIUtil::HelpMessageBox help; + help.showOrPrint(); + return 1; + } + +#ifdef Q_OS_MAC + // on mac, also change the icon now because it would look strange to have a testnet splash (green) and a std app icon (orange) + if(GetBoolArg("-testnet")) { + MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet")); + } +#endif + + SplashScreen splash(QPixmap(), 0); + if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) + { + splash.show(); + splash.setAutoFillBackground(true); + splashref = &splash; + } + + app.processEvents(); + app.setQuitOnLastWindowClosed(false); + + try + { +#ifndef Q_OS_MAC + // Regenerate startup link, to fix links to old versions + // OSX: makes no sense on mac and might also scan/mount external (and sleeping) volumes (can take up some secs) + if (GUIUtil::GetStartOnSystemStartup()) + GUIUtil::SetStartOnSystemStartup(true); +#endif + + boost::thread_group threadGroup; + + BitcoinGUI window; + guiref = &window; + + QTimer* pollShutdownTimer = new QTimer(guiref); + QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown())); + pollShutdownTimer->start(200); + + if(AppInit2(threadGroup)) + { + { + // Put this in a block, so that the Model objects are cleaned up before + // calling Shutdown(). + + optionsModel.Upgrade(); // Must be done after AppInit2 + + if (splashref) + splash.finish(&window); + + ClientModel clientModel(&optionsModel); + WalletModel *walletModel = 0; + if(pwalletMain) + walletModel = new WalletModel(pwalletMain, &optionsModel); + + window.setClientModel(&clientModel); + if(walletModel) + { + window.addWallet("~Default", walletModel); + window.setCurrentWallet("~Default"); + } + + // If -min option passed, start window minimized. + if(GetBoolArg("-min")) + { + window.showMinimized(); + } + else + { + window.show(); + } + + // Now that initialization/startup is done, process any command-line + // bitcoin: URIs + QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString))); + QTimer::singleShot(100, paymentServer, SLOT(uiReady())); + + app.exec(); + + window.hide(); + window.setClientModel(0); + window.removeAllWallets(); + guiref = 0; + delete walletModel; + } + // Shutdown the core and its threads, but don't exit Bitcoin-Qt here + threadGroup.interrupt_all(); + threadGroup.join_all(); + Shutdown(); + } + else + { + threadGroup.interrupt_all(); + threadGroup.join_all(); + Shutdown(); + return 1; + } + } catch (std::exception& e) { + handleRunawayException(&e); + } catch (...) { + handleRunawayException(NULL); + } + return 0; +} +#endif // BITCOIN_QT_TEST diff --git a/pool/shard007/C++/0091715_file_operation.cpp b/pool/shard007/C++/0091715_file_operation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3493c18cec82e91aad75f453dd0ed03e71467943 --- /dev/null +++ b/pool/shard007/C++/0091715_file_operation.cpp @@ -0,0 +1,34 @@ +#include <iostream> +#include <cstdlib> +#include <ctime> + +int main(int argc, char **argv) { + int secret, guess; + srand(time(NULL)); + secret = rand() % 10 + 1; + std::cin >> guess; + + FILE *file = fopen("myfile.txt", "w"); + FILE *f2 = fopen("myfile2.txt", "w"); + + fclose(fopen("myfile3.txt", "w")); + + if (guess < secret) { + fclose(file); + return 1; + } + + if (fopen("test1","r")); + + std::cout << "blabla" << std::endl; + + fclose(f2); + fclose(file); + + FILE *a = 1 + fopen("test2", "r"); + fclose(a); + + fopen("blabla", "w"); + + return 0; +} diff --git a/pool/shard007/C++/0091718_network.cc b/pool/shard007/C++/0091718_network.cc new file mode 100644 index 0000000000000000000000000000000000000000..b1be01cde62cb5d98458c3adb6df3c021bacece5 --- /dev/null +++ b/pool/shard007/C++/0091718_network.cc @@ -0,0 +1,241 @@ +/* + * Copyright (C) 2004-2022 by the Widelands Development Team + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see <https://www.gnu.org/licenses/>. + * + */ + +#include "network/network.h" + +#include <SDL_timer.h> + +#include "base/log.h" + +namespace { + +bool do_resolve(const asio::ip::tcp& protocol, + NetAddress* addr, + const std::string& hostname, + uint16_t port) { + assert(addr != nullptr); + try { + asio::io_service io_service; + asio::ip::tcp::resolver resolver(io_service); + asio::ip::tcp::resolver::query query(protocol, hostname, as_string(port)); + asio::ip::tcp::resolver::iterator iter = resolver.resolve(query); + if (iter == asio::ip::tcp::resolver::iterator()) { + // Resolution failed + log_err("Could not resolve network name '%s:%u' to %s-address\n", hostname.c_str(), port, + ((protocol == asio::ip::tcp::v4()) ? "IPv4" : "IPv6")); + return false; + } + addr->ip = iter->endpoint().address(); + addr->port = port; + verb_log_info("Resolved network name '%s:%u' to %s", hostname.c_str(), port, + addr->ip.to_string().c_str()); + return true; + } catch (const std::system_error& ec) { + // Resolution failed + log_err("Could not resolve network name '%s:%u' to %s-address: %s\n", hostname.c_str(), port, + ((protocol == asio::ip::tcp::v4()) ? "IPv4" : "IPv6"), ec.what()); + return false; + } +} +} // namespace + +bool NetAddress::resolve_to_v4(NetAddress* addr, const std::string& hostname, uint16_t port) { + return do_resolve(asio::ip::tcp::v4(), addr, hostname, port); +} + +bool NetAddress::resolve_to_v6(NetAddress* addr, const std::string& hostname, uint16_t port) { + return do_resolve(asio::ip::tcp::v6(), addr, hostname, port); +} + +bool NetAddress::parse_ip(NetAddress* addr, const std::string& ip, uint16_t port) { + std::error_code ec; + asio::ip::address new_addr = asio::ip::address::from_string(ip, ec); + if (ec) { + return false; + } + addr->ip = new_addr; + addr->port = port; + return true; +} + +bool NetAddress::is_ipv6() const { + return ip.is_v6(); +} + +bool NetAddress::is_valid() const { + return port != 0 && !ip.is_unspecified(); +} + +CmdNetCheckSync::CmdNetCheckSync(const Time& dt, SyncReportCallback cb) + : Command(dt), callback_(std::move(cb)) { +} + +void CmdNetCheckSync::execute(Widelands::Game& /* game */) { + callback_(); +} + +NetworkTime::NetworkTime() { + reset(Time(0)); +} + +void NetworkTime::reset(const Time& ntime) { + networktime_ = time_ = ntime; + lastframe_ = SDL_GetTicks(); + latency_ = 0; +} + +void NetworkTime::fastforward() { + time_ = networktime_; + lastframe_ = SDL_GetTicks(); +} + +void NetworkTime::think(uint32_t const speed) { + uint32_t const curtime = SDL_GetTicks(); + int32_t delta = curtime - lastframe_; + lastframe_ = curtime; + + // in case weird things are happening with the system time + // (e.g. debugger, extremely slow simulation, ...) + if (delta < 0) { + delta = 0; + } else if (delta > 1000) { + delta = 1000; + } + + delta = (delta * speed) / 1000; + + int32_t const behind = networktime_.get() - time_.get(); + + // Play catch up + uint32_t speedup = 0; + if (latency_ > static_cast<uint32_t>(10 * delta)) { + // just try to kill as much of the latency as possible if we are that + // far behind + speedup = latency_ / 3; + } else if (latency_ > static_cast<uint32_t>(delta)) { + speedup = delta / 8; // speed up by 12.5% + } + if (static_cast<int32_t>(delta + speedup) > behind) { + speedup = behind - delta; + } + + delta += speedup; + latency_ -= speedup; + + if (delta > behind) { + delta = behind; + } + + time_.increment(Duration(delta)); +} + +const Time& NetworkTime::time() const { + return time_; +} + +const Time& NetworkTime::networktime() const { + return networktime_; +} + +void NetworkTime::receive(const Time& ntime) { + if (ntime < networktime_) { + throw wexception("NetworkTime: Time appears to be running backwards."); + } + + uint32_t const behind = networktime_.get() - time_.get(); + + latency_ = behind < latency_ ? behind : ((latency_ * 7) + behind) / 8; + +#if 0 + log + ("NetworkTime: New networktime %i (local time %i), behind %i, latency " + "%u\n", + ntime, time_, networktime_ - time_, latency_); +#endif + + networktime_ = ntime; +} + +/*** class SendPacket ***/ + +void SendPacket::data(const void* const packet_data, const size_t size) { + if (buffer.empty()) { + buffer.push_back(0); // this will finally be the length of the packet + buffer.push_back(0); + // Attention! These bytes are also used by the network relay protocol. + // So if they are removed the protocol has to be updated + } + + for (size_t idx = 0; idx < size; ++idx) { + buffer.push_back(static_cast<const uint8_t*>(packet_data)[idx]); + } +} + +void SendPacket::reset() { + buffer.clear(); +} + +size_t SendPacket::get_size() const { + return buffer.size(); +} + +uint8_t* SendPacket::get_data() const { + + uint32_t const length = buffer.size(); + + assert(length >= 2); + assert(length < 0x10000); + + // update packet length + buffer[0] = length >> 8; + buffer[1] = length & 0xFF; + + return &(buffer[0]); +} + +/*** class RecvPacket ***/ +size_t RecvPacket::data(void* const packet_data, size_t const bufsize) { + if (index_ + bufsize > buffer.size()) { + throw wexception("Packet too short"); + } + + for (size_t read = 0; read < bufsize; ++read) { + static_cast<uint8_t*>(packet_data)[read] = buffer[index_++]; + } + + return bufsize; +} + +bool RecvPacket::end_of_file() const { + return index_ < buffer.size(); +} + +DisconnectException::DisconnectException(const char* fmt, ...) { + char buffer[kNetworkBufferSize]; + { + va_list va; + va_start(va, fmt); + vsnprintf(buffer, sizeof(buffer), fmt, va); + va_end(va); + } + what_ = buffer; +} + +char const* DisconnectException::what() const noexcept { + return what_.c_str(); +} diff --git a/pool/shard007/C++/0091722_Wither.cpp b/pool/shard007/C++/0091722_Wither.cpp new file mode 100644 index 0000000000000000000000000000000000000000..19399953ebf8ef98f33ce4a10e226ac0058c8c7f --- /dev/null +++ b/pool/shard007/C++/0091722_Wither.cpp @@ -0,0 +1,141 @@ + +#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules + +#include "Wither.h" + +#include "../World.h" +#include "../Entities/Player.h" + + + + + +cWither::cWither(void) : + super("Wither", mtWither, "mob.wither.hurt", "mob.wither.death", 0.9, 4.0), + m_WitherInvulnerableTicks(220) +{ + SetMaxHealth(300); +} + + + + + +bool cWither::IsArmored(void) const +{ + return GetHealth() <= (GetMaxHealth() / 2); +} + + + + + +bool cWither::Initialize(cWorld & a_World) +{ + // Set health before BroadcastSpawnEntity() + SetHealth(GetMaxHealth() / 3); + + return super::Initialize(a_World); +} + + + + + +bool cWither::DoTakeDamage(TakeDamageInfo & a_TDI) +{ + if (a_TDI.DamageType == dtDrowning) + { + return false; + } + + if (m_WitherInvulnerableTicks > 0) + { + return false; + } + + if (IsArmored() && (a_TDI.DamageType == dtRangedAttack)) + { + return false; + } + + return super::DoTakeDamage(a_TDI); +} + + + + + +void cWither::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk) +{ + super::Tick(a_Dt, a_Chunk); + if (!IsTicking()) + { + // The base class tick destroyed us + return; + } + + if (m_WitherInvulnerableTicks > 0) + { + unsigned int NewTicks = m_WitherInvulnerableTicks - 1; + + if (NewTicks == 0) + { + m_World->DoExplosionAt(7.0, GetPosX(), GetPosY(), GetPosZ(), false, esWitherBirth, this); + } + + m_WitherInvulnerableTicks = NewTicks; + + if ((NewTicks % 10) == 0) + { + Heal(10); + } + } + + m_World->BroadcastEntityMetadata(*this); +} + + + + + +void cWither::GetDrops(cItems & a_Drops, cEntity * a_Killer) +{ + AddRandomDropItem(a_Drops, 1, 1, E_ITEM_NETHER_STAR); +} + + + + + +void cWither::KilledBy(TakeDamageInfo & a_TDI) +{ + super::KilledBy(a_TDI); + + class cPlayerCallback : public cPlayerListCallback + { + Vector3f m_Pos; + + virtual bool Item(cPlayer * a_Player) + { + // TODO 2014-05-21 xdot: Vanilla minecraft uses an AABB check instead of a radius one + double Dist = (a_Player->GetPosition() - m_Pos).Length(); + if (Dist < 50.0) + { + // If player is close, award achievement + a_Player->AwardAchievement(achKillWither); + } + return false; + } + + public: + cPlayerCallback(const Vector3f & a_Pos) : m_Pos(a_Pos) {} + + } PlayerCallback(GetPosition()); + + m_World->ForEachPlayer(PlayerCallback); +} + + + + diff --git a/pool/shard007/C++/0091723_SILOpenedArchetypesTracker.cpp b/pool/shard007/C++/0091723_SILOpenedArchetypesTracker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e3e8b7f5f3da4523628231df7f06fc247c753de5 --- /dev/null +++ b/pool/shard007/C++/0091723_SILOpenedArchetypesTracker.cpp @@ -0,0 +1,226 @@ +//===--- SILOpenedArchetypesTracker.cpp - Track opened archetypes ---------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#include "swift/SIL/SILBuilder.h" +#include "swift/SIL/SILOpenedArchetypesTracker.h" + +using namespace swift; + +void SILOpenedArchetypesTracker::addOpenedArchetypeDef(CanArchetypeType archetype, + SingleValueInstruction *Def) { + auto OldDef = getOpenedArchetypeDef(archetype); + if (OldDef) { + if (auto *OldI = dyn_cast<GlobalAddrInst>(OldDef)) { + // It is a forward definition created during deserialization. + // Replace it with the real definition now. + OldDef->replaceAllUsesWith(Def); + // Remove the placeholder instruction. + OldI->eraseFromParent(); + OldDef = nullptr; + } + } + assert((!OldDef || OldDef == Def) && + "There can be only one definition of an opened archetype"); + OpenedArchetypeDefs[archetype] = Def; +} + +/// Check if there are any unresolved forward definitions of opened +/// archetypes. +bool SILOpenedArchetypesTracker::hasUnresolvedOpenedArchetypeDefinitions() { + for (auto &KV : getOpenedArchetypeDefs()) { + assert(KV.getFirst()->is<ArchetypeType>() && "The type should be an archetype"); + if (!KV.getSecond() || isa<GlobalAddrInst>(KV.getSecond())) + return true; + } + return false; +} + +bool SILOpenedArchetypesTracker::registerUsedOpenedArchetypes(CanType Ty) { + bool Registered = false; + // Nothing else to be done if the type does not contain an opened archetype. + if (!Ty || !Ty->hasOpenedExistential()) + return Registered; + + // Find all opened existentials used by this type and check if their + // definitions are known. + Ty.visit([&](CanType ty) { + if (!ty->isOpenedExistential()) + return; + + auto archetypeTy = cast<ArchetypeType>(ty); + // Nothing to do if a definition was seen already. + if (getOpenedArchetypeDef(archetypeTy)) + return; + + auto *CurF = const_cast<SILFunction *>(this->getFunction()); + auto &SILMod = CurF->getModule(); + // Create a placeholder representing a forward definition. + // Add the placeholder at the beginning of the entry block. + SingleValueInstruction *Placeholder; + if (!CurF->getEntryBlock()->empty()) { + SILBuilder B(CurF->getEntryBlock()->begin()); + Placeholder = + B.createGlobalAddr(ArtificialUnreachableLocation(), + SILMod.Types.getLoweredType(archetypeTy)); + } else { + SILBuilder B(CurF->getEntryBlock()); + Placeholder = + B.createGlobalAddr(ArtificialUnreachableLocation(), + SILMod.Types.getLoweredType(archetypeTy)); + } + // Make it available to SILBuilder, so that instructions using this + // archetype can be constructed. + addOpenedArchetypeDef(archetypeTy, Placeholder); + }); + return Registered; +} + +// Register archetypes opened by a given instruction. +// Can be used to incrementally populate the mapping, e.g. +// if it is done when performing a scan of all instructions +// inside a function. +bool SILOpenedArchetypesTracker::registerOpenedArchetypes( + const SILInstruction *I) { + assert((!I->getParent() || I->getFunction() == getFunction()) && + "Instruction does not belong to a proper SILFunction"); + auto Archetype = getOpenedArchetypeOf(I); + if (!Archetype) + return false; + auto SVI = + const_cast<SingleValueInstruction*>(cast<SingleValueInstruction>(I)); + addOpenedArchetypeDef(Archetype, SVI); + return true; +} + +// Register opened archetypes whose definitions are referenced by +// the typedef operands of this instruction. +bool SILOpenedArchetypesTracker::registerUsedOpenedArchetypes( + const SILInstruction *I) { + assert((!I->getParent() || I->getFunction() == getFunction()) && + "Instruction does not belong to a proper SILFunction"); + bool Registered = false; + for (auto &Op : I->getTypeDependentOperands()) { + auto OpenedArchetypeDef = Op.get(); + if (auto *DefInst = dyn_cast<SingleValueInstruction>(OpenedArchetypeDef)) { + addOpenedArchetypeDef(getOpenedArchetypeOf(DefInst), DefInst); + Registered = true; + } + } + return Registered; +} + +// Unregister archetypes opened by a given instruction. +// Should be only called when this instruction is to be removed. +void SILOpenedArchetypesTracker::unregisterOpenedArchetypes( + const SILInstruction *I) { + assert(I->getFunction() == getFunction() && + "Instruction does not belong to a proper SILFunction"); + auto archetype = getOpenedArchetypeOf(I); + // Remove the archetype definition if it was registered before. + // It may happen that this archetype was not registered in the + // SILOpenedArchetypesTracker, because the tracker was created + // without scanning the whole function and thus may not aware + // of all opened archetypes of the function. + if (archetype) { + auto def = getOpenedArchetypeDef(archetype); + if (def == I) { + OpenedArchetypeDefs.erase(archetype); + } + } +} + +void SILOpenedArchetypesTracker::handleDeleteNotification( + swift::SILNode *node) { + if (auto I = dyn_cast<SILInstruction>(node)) + if (I->getFunction() == getFunction()) + unregisterOpenedArchetypes(I); +} + +/// Find an opened archetype defined by an instruction. +/// \returns The found archetype or empty type otherwise. +CanArchetypeType swift::getOpenedArchetypeOf(const SILInstruction *I) { + if (isa<OpenExistentialAddrInst>(I) || isa<OpenExistentialRefInst>(I) || + isa<OpenExistentialBoxInst>(I) || isa<OpenExistentialBoxValueInst>(I) || + isa<OpenExistentialMetatypeInst>(I) || isa<OpenExistentialValueInst>(I)) { + auto SVI = cast<SingleValueInstruction>(I); + auto Ty = getOpenedArchetypeOf(SVI->getType().getSwiftRValueType()); + assert(Ty && Ty->isOpenedExistential() && + "Type should be an opened archetype"); + return Ty; + } + + return CanArchetypeType(); +} + + +/// Find an opened archetype represented by this type. +/// It is assumed by this method that the type contains +/// at most one opened archetype. +/// Typically, it would be called from a type visitor. +/// It checks only the type itself, but does not try to +/// recursively check any children of this type, because +/// this is the task of the type visitor invoking it. +/// \returns The found archetype or empty type otherwise. +CanArchetypeType swift::getOpenedArchetypeOf(CanType Ty) { + if (!Ty) + return CanArchetypeType(); + while (auto MetaTy = dyn_cast<AnyMetatypeType>(Ty)) + Ty = MetaTy.getInstanceType(); + if (Ty->isOpenedExistential()) + return cast<ArchetypeType>(Ty); + return CanArchetypeType(); +} + +SILValue SILOpenedArchetypesState::getOpenedArchetypeDef( + CanArchetypeType archetypeTy) const { + if (!archetypeTy) + return SILValue(); + // First perform a quick check. + for (auto &Op : OpenedArchetypeOperands) { + auto Def = Op.get(); + if (auto SVI = dyn_cast<SingleValueInstruction>(Def)) + if (getOpenedArchetypeOf(SVI) == archetypeTy) + return Def; + } + // Then use a regular lookup. + if (OpenedArchetypesTracker) + return OpenedArchetypesTracker->getOpenedArchetypeDef(archetypeTy); + return SILValue(); +} + +void SILOpenedArchetypesTracker::dump() const { + llvm::dbgs() << "SILOpenedArchetypesTracker {\n"; + llvm::dbgs() << "Tracks open archetypes for function: " + << getFunction()->getName() << "\n"; + llvm::dbgs() << "Open archetype operands and their definitions:\n"; + for (auto &KV : OpenedArchetypeDefs) { + auto Archetype = KV.first; + auto Def = KV.second; + llvm::dbgs() << "open archetype:\n"; + Type(Archetype)->dump(); + llvm::dbgs() << "defined at: " << *Def << "\n"; + } + llvm::dbgs() << "}\n"; +} + +void SILOpenedArchetypesState::dump() const { + ArrayRef<Operand> OpenedArchetypeOperands; + // A non-modifiable mapping provided by the tracker. + llvm::dbgs() << "SILOpenedArchetypesState {\n"; + llvm::dbgs() << "Open archetype operands:\n"; + for (auto &Op : OpenedArchetypeOperands) { + Op.get()->dump(); + } + if (OpenedArchetypesTracker) + OpenedArchetypesTracker->dump(); + llvm::dbgs() << "}\n"; +} diff --git a/pool/shard007/C++/0091731_invert_bubble_view.cc b/pool/shard007/C++/0091731_invert_bubble_view.cc new file mode 100644 index 0000000000000000000000000000000000000000..c19272276bd1888b72c58e30eb7951d6d1d5908c --- /dev/null +++ b/pool/shard007/C++/0091731_invert_bubble_view.cc @@ -0,0 +1,177 @@ +// Copyright (c) 2012 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 "chrome/browser/ui/views/accessibility/invert_bubble_view.h" + +#include "base/macros.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_dialogs.h" +#include "chrome/browser/ui/views/chrome_layout_provider.h" +#include "chrome/browser/ui/views/chrome_typography.h" +#include "chrome/browser/ui/views/frame/app_menu_button.h" +#include "chrome/browser/ui/views/frame/browser_view.h" +#include "chrome/browser/ui/views/frame/toolbar_button_provider.h" +#include "chrome/common/pref_names.h" +#include "chrome/grit/generated_resources.h" +#include "components/prefs/pref_service.h" +#include "components/strings/grit/components_strings.h" +#include "components/vector_icons/vector_icons.h" +#include "content/public/browser/page_navigator.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/base/resource/resource_bundle.h" +#include "ui/base/window_open_disposition.h" +#include "ui/gfx/color_utils.h" +#include "ui/native_theme/native_theme.h" +#include "ui/views/bubble/bubble_dialog_delegate_view.h" +#include "ui/views/controls/button/image_button.h" +#include "ui/views/controls/button/image_button_factory.h" +#include "ui/views/controls/button/menu_button.h" +#include "ui/views/controls/label.h" +#include "ui/views/controls/link.h" +#include "ui/views/layout/box_layout.h" +#include "ui/views/widget/widget.h" + +namespace { + +constexpr char kHighContrastExtensionUrl[] = + "https://chrome.google.com/webstore/detail/" + "djcfdncoelnlbldjfhinnjlhdjlikmph"; +constexpr char kDarkThemeSearchUrl[] = + "https://chrome.google.com/webstore/category/collection/dark_themes"; +constexpr char kLearnMoreUrl[] = + "https://groups.google.com/a/googleproductforums.com/d/topic/chrome/" + "Xrco2HsXS-8/discussion"; + +// Tag value used to uniquely identify the "learn more" (?) button. +constexpr int kLearnMoreButton = 100; + +std::unique_ptr<views::View> CreateExtraView(views::ButtonListener* listener) { + auto learn_more = views::CreateVectorImageButtonWithNativeTheme( + listener, vector_icons::kHelpOutlineIcon); + learn_more->SetTooltipText(l10n_util::GetStringUTF16(IDS_LEARN_MORE)); + learn_more->set_tag(kLearnMoreButton); + return learn_more; +} + +class InvertBubbleView : public views::BubbleDialogDelegateView, + public views::ButtonListener { + public: + InvertBubbleView(Browser* browser, views::View* anchor_view); + ~InvertBubbleView() override; + + private: + // Overridden from views::BubbleDialogDelegateView: + void Init() override; + + // Overridden from views::WidgetDelegate: + base::string16 GetWindowTitle() const override; + bool ShouldShowCloseButton() const override; + + // Overridden from views::ButtonListener: + void ButtonPressed(views::Button* sender, const ui::Event& event) override; + + void OpenLink(const std::string& url, views::Link* source, int event_flags); + + Browser* browser_; + + DISALLOW_COPY_AND_ASSIGN(InvertBubbleView); +}; + +InvertBubbleView::InvertBubbleView(Browser* browser, views::View* anchor_view) + : views::BubbleDialogDelegateView(anchor_view, + views::BubbleBorder::TOP_RIGHT), + browser_(browser) { + SetButtons(ui::DIALOG_BUTTON_OK); + SetButtonLabel(ui::DIALOG_BUTTON_OK, l10n_util::GetStringUTF16(IDS_DONE)); + SetExtraView(::CreateExtraView(this)); + set_margins(gfx::Insets()); + chrome::RecordDialogCreation(chrome::DialogIdentifier::INVERT); +} + +InvertBubbleView::~InvertBubbleView() { +} + +void InvertBubbleView::Init() { + const ChromeLayoutProvider* provider = ChromeLayoutProvider::Get(); + SetBorder(views::CreateEmptyBorder( + provider->GetInsetsMetric(views::INSETS_DIALOG))); + + views::BoxLayout* layout = + SetLayoutManager(std::make_unique<views::BoxLayout>( + views::BoxLayout::Orientation::kVertical)); + layout->set_cross_axis_alignment( + views::BoxLayout::CrossAxisAlignment::kStart); + + AddChildView(std::make_unique<views::Label>( + l10n_util::GetStringUTF16(IDS_HIGH_CONTRAST_HEADER), + CONTEXT_BODY_TEXT_LARGE)); + + auto* high_contrast = AddChildView(std::make_unique<views::Link>( + l10n_util::GetStringUTF16(IDS_HIGH_CONTRAST_EXT), + CONTEXT_BODY_TEXT_LARGE)); + high_contrast->set_callback(base::BindRepeating(&InvertBubbleView::OpenLink, + base::Unretained(this), + kHighContrastExtensionUrl)); + + auto* dark_theme = AddChildView(std::make_unique<views::Link>( + l10n_util::GetStringUTF16(IDS_DARK_THEME), CONTEXT_BODY_TEXT_LARGE)); + dark_theme->set_callback(base::BindRepeating(&InvertBubbleView::OpenLink, + base::Unretained(this), + kDarkThemeSearchUrl)); + + // Switching to high-contrast mode has a nasty habit of causing Chrome + // top-level windows to lose focus, so closing the bubble on deactivate + // makes it disappear before the user has even seen it. This forces the + // user to close it explicitly, which should be okay because it affects + // a small minority of users, and only once. + set_close_on_deactivate(false); +} + +base::string16 InvertBubbleView::GetWindowTitle() const { + return l10n_util::GetStringUTF16(IDS_HIGH_CONTRAST_TITLE); +} + +bool InvertBubbleView::ShouldShowCloseButton() const { + return true; +} + +void InvertBubbleView::ButtonPressed(views::Button* sender, + const ui::Event& event) { + if (sender->tag() == kLearnMoreButton) + OpenLink(kLearnMoreUrl, nullptr, event.flags()); +} + +void InvertBubbleView::OpenLink(const std::string& url, + views::Link* source, + int event_flags) { + WindowOpenDisposition disposition = ui::DispositionFromEventFlags( + event_flags, WindowOpenDisposition::NEW_FOREGROUND_TAB); + content::OpenURLParams params(GURL(url), content::Referrer(), disposition, + ui::PAGE_TRANSITION_LINK, false); + browser_->OpenURL(params); +} + +} // namespace + +void MaybeShowInvertBubbleView(BrowserView* browser_view) { + Browser* browser = browser_view->browser(); + if (browser->profile()->IsIncognitoProfile()) + return; + PrefService* pref_service = browser->profile()->GetPrefs(); + views::View* anchor = + browser_view->toolbar_button_provider()->GetAppMenuButton(); + if (anchor && anchor->GetWidget() && + anchor->GetNativeTheme()->GetHighContrastColorScheme() == + ui::NativeTheme::HighContrastColorScheme::kDark && + !pref_service->GetBoolean(prefs::kInvertNotificationShown)) { + pref_service->SetBoolean(prefs::kInvertNotificationShown, true); + ShowInvertBubbleView(browser, anchor); + } +} + +void ShowInvertBubbleView(Browser* browser, views::View* anchor) { + InvertBubbleView* delegate = new InvertBubbleView(browser, anchor); + views::BubbleDialogDelegateView::CreateBubble(delegate)->Show(); +} diff --git a/pool/shard007/C++/0091746_etudiantaffectation.cpp b/pool/shard007/C++/0091746_etudiantaffectation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..61996167b10c74741207eebddd42d7a1d9d8350e --- /dev/null +++ b/pool/shard007/C++/0091746_etudiantaffectation.cpp @@ -0,0 +1,105 @@ +#include "etudiantaffectation.h" +#include "domainconstants.h" +#include "etudiant.h" +#include "idatamanager.h" +////////////////////////////////// +namespace info { + ////////////////////////////////////////////// + std::vector<std::shared_ptr<EtudiantAffectation> > + EtudiantAffectation::get_all_affectations(IDataManager &oMan, + const std::string &semid /*= std::string()*/, + const std::string &groupeid /*= std::string()*/, + int skip /*= 0*/, int limit /*= 0*/) { + std::vector<std::shared_ptr<EtudiantAffectation> > oRet; + std::string start = DomainConstants::ETUDIANTAFFECTATION_PREFIX + + semid + groupeid; + std::string end = start + std::string("zzzzzz"); + Value vr = oMan.read_docs_range(start, end, skip, limit); + if (vr.is_array()) { + Array *pAr = vr.as_array(); + if (pAr != nullptr) { + size_t n = pAr->size(); + for (size_t i = 0; i < n; ++i) { + PValue ov = (*pAr)[i]; + Value *pv = ov.get(); + if (pv != nullptr) { + std::shared_ptr<EtudiantAffectation> d = std::make_shared<EtudiantAffectation>(*pv); + oRet.push_back(d); + } + }// i + }// pAr + }// array + return oRet; + }//get_all_affectations + /////////////////////////////////////////////// + EtudiantAffectation::EtudiantAffectation() + { + this->type(DomainConstants::ETUDIANTAFFECTATION_TYPE); + this->modified(false); + } + + EtudiantAffectation::EtudiantAffectation(const Etudiant &oEtud, + const Semestre &oSem, const Groupe &oGroupe) :Affectation(oEtud, oSem, oGroupe) { + this->type(DomainConstants::ETUDIANTAFFECTATION_TYPE); + this->etudiant(oEtud); + this->modified(false); + } + EtudiantAffectation::EtudiantAffectation(const Value &oMap) : Affectation(oMap) { + this->type(DomainConstants::ETUDIANTAFFECTATION_TYPE); + this->modified(false); + } + EtudiantAffectation::EtudiantAffectation(const EtudiantAffectation &other) : Affectation(other) { + + } + EtudiantAffectation & EtudiantAffectation::operator=(const EtudiantAffectation &other) { + if (this != &other) { + Affectation::operator=(other); + } + return *this; + } + EtudiantAffectation::~EtudiantAffectation() + { + } + std::string EtudiantAffectation::etudiantid(void) const { + return this->get_string(DomainConstants::ETUDIANTID); + } + void EtudiantAffectation::etudiantid(const std::string &s) { + this->set_string(DomainConstants::ETUDIANTID, s); + } + void EtudiantAffectation::etudiant(const Etudiant &oEtud) { + this->etudiantid(oEtud.id()); + this->personid(oEtud.personid()); + } + std::shared_ptr<Etudiant> EtudiantAffectation::get_etudiant(IDataManager &oMan) { + std::shared_ptr<Etudiant> oRet; + std::string id = this->etudiantid(); + if (id.empty()) { + Value v = oMan.read_doc(id); + if (v.is_object()) { + Object *pObj = v.as_object(); + if (pObj != nullptr) { + std::string sx = pObj->get_string(DomainConstants::ID); + if (sx == id) { + oRet = std::make_shared<Etudiant>(v); + } + }// pObj + } + } + return oRet; + } + std::string EtudiantAffectation::store_prefix(void) const { + return DomainConstants::ETUDIANTAFFECTATION_PREFIX; + } + std::string EtudiantAffectation::start_key(void) const { + return this->store_prefix() + this->semestreid() + + this->groupeid(); + } + std::string EtudiantAffectation::create_id(void) const { + return this->start_key() + this->etudiantid(); + } + bool EtudiantAffectation::is_storeable(void) const { + std::string s = this->etudiantid(); + return (!s.empty()) && Affectation::is_storeable(); + } + /////////////////////////////////////// +}// namespace geninfo diff --git a/pool/shard007/C++/0091752_function_descriptor.cc b/pool/shard007/C++/0091752_function_descriptor.cc new file mode 100644 index 0000000000000000000000000000000000000000..ea25028cbd79f6ade6eff87c986c79e585d328d6 --- /dev/null +++ b/pool/shard007/C++/0091752_function_descriptor.cc @@ -0,0 +1,104 @@ +// Copyright 2017 The Ray Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "ray/common/function_descriptor.h" + +namespace ray { +FunctionDescriptor FunctionDescriptorBuilder::Empty() { + static ray::FunctionDescriptor empty = + ray::FunctionDescriptor(new EmptyFunctionDescriptor()); + return empty; +} + +FunctionDescriptor FunctionDescriptorBuilder::BuildJava(const std::string &class_name, + const std::string &function_name, + const std::string &signature) { + rpc::FunctionDescriptor descriptor; + auto typed_descriptor = descriptor.mutable_java_function_descriptor(); + typed_descriptor->set_class_name(class_name); + typed_descriptor->set_function_name(function_name); + typed_descriptor->set_signature(signature); + return ray::FunctionDescriptor(new JavaFunctionDescriptor(std::move(descriptor))); +} + +FunctionDescriptor FunctionDescriptorBuilder::BuildPython( + const std::string &module_name, const std::string &class_name, + const std::string &function_name, const std::string &function_hash) { + rpc::FunctionDescriptor descriptor; + auto typed_descriptor = descriptor.mutable_python_function_descriptor(); + typed_descriptor->set_module_name(module_name); + typed_descriptor->set_class_name(class_name); + typed_descriptor->set_function_name(function_name); + typed_descriptor->set_function_hash(function_hash); + return ray::FunctionDescriptor(new PythonFunctionDescriptor(std::move(descriptor))); +} + +FunctionDescriptor FunctionDescriptorBuilder::BuildCpp(const std::string &function_name) { + rpc::FunctionDescriptor descriptor; + auto typed_descriptor = descriptor.mutable_cpp_function_descriptor(); + typed_descriptor->set_function_name(function_name); + return ray::FunctionDescriptor(new CppFunctionDescriptor(std::move(descriptor))); +} + +FunctionDescriptor FunctionDescriptorBuilder::FromProto(rpc::FunctionDescriptor message) { + switch (message.function_descriptor_case()) { + case ray::FunctionDescriptorType::kJavaFunctionDescriptor: + return ray::FunctionDescriptor(new ray::JavaFunctionDescriptor(std::move(message))); + case ray::FunctionDescriptorType::kPythonFunctionDescriptor: + return ray::FunctionDescriptor(new ray::PythonFunctionDescriptor(std::move(message))); + case ray::FunctionDescriptorType::kCppFunctionDescriptor: + return ray::FunctionDescriptor(new ray::CppFunctionDescriptor(std::move(message))); + default: + break; + } + // When TaskSpecification() constructed without function_descriptor set, + // we should return a valid ray::FunctionDescriptor instance. + return FunctionDescriptorBuilder::Empty(); +} + +FunctionDescriptor FunctionDescriptorBuilder::FromVector( + rpc::Language language, const std::vector<std::string> &function_descriptor_list) { + if (language == rpc::Language::JAVA) { + RAY_CHECK(function_descriptor_list.size() == 3); + return FunctionDescriptorBuilder::BuildJava( + function_descriptor_list[0], // class name + function_descriptor_list[1], // function name + function_descriptor_list[2] // signature + ); + } else if (language == rpc::Language::PYTHON) { + RAY_CHECK(function_descriptor_list.size() == 4); + return FunctionDescriptorBuilder::BuildPython( + function_descriptor_list[0], // module name + function_descriptor_list[1], // class name + function_descriptor_list[2], // function name + function_descriptor_list[3] // function hash + ); + } else if (language == rpc::Language::CPP) { + RAY_CHECK(function_descriptor_list.size() == 1); + return FunctionDescriptorBuilder::BuildCpp( + function_descriptor_list[0] // function name + ); + } else { + RAY_LOG(FATAL) << "Unspported language " << language; + return FunctionDescriptorBuilder::Empty(); + } +} + +FunctionDescriptor FunctionDescriptorBuilder::Deserialize( + const std::string &serialized_binary) { + rpc::FunctionDescriptor descriptor; + descriptor.ParseFromString(serialized_binary); + return FunctionDescriptorBuilder::FromProto(std::move(descriptor)); +} +} // namespace ray diff --git a/pool/shard007/C++/0091757_result_read.cc b/pool/shard007/C++/0091757_result_read.cc new file mode 100644 index 0000000000000000000000000000000000000000..351be041ab125c553821df6d1bfa060fbf749a95 --- /dev/null +++ b/pool/shard007/C++/0091757_result_read.cc @@ -0,0 +1,54 @@ +// Copyright 2020 The Pigweed Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may not +// use this file except in compliance with the License. You may obtain a copy of +// the License at +// +// https://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 <cstring> +#include <span> + +#include "pw_bytes/array.h" +#include "pw_log/log.h" +#include "pw_preprocessor/compiler.h" +#include "pw_result/result.h" + +namespace { + +// clang-format off +constexpr auto kArray = pw::bytes::Array< + 0x0a, 0x14, 0x00, 0x00, 0x00, 0x00, 0x32, 0x00, + 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x96, 0x00, + 0x00, 0x00, 0xc8, 0x00, 0x00, 0x00, 0x12, 0x08, + 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01>(); +// clang-format on + +PW_NO_INLINE pw::Result<std::span<const std::byte>> Read(size_t offset, + size_t size) { + if (offset + size >= std::size(kArray)) { + return pw::Status::OutOfRange(); + } + + return std::span<const std::byte>(std::data(kArray) + offset, size); +} + +} // namespace + +size_t volatile* unoptimizable; + +int main() { + pw::Result result = Read(*unoptimizable, *unoptimizable); + if (!result.ok()) { + return 1; + } + + PW_LOG_INFO("Read %u bytes", static_cast<unsigned>(result.value().size())); + return 0; +} diff --git a/pool/shard007/C++/0091761_block_based_filter_block.cc b/pool/shard007/C++/0091761_block_based_filter_block.cc new file mode 100644 index 0000000000000000000000000000000000000000..e65ee280d91d17cfb961d3abbfc50c09286ce5e4 --- /dev/null +++ b/pool/shard007/C++/0091761_block_based_filter_block.cc @@ -0,0 +1,250 @@ +// Copyright (c) 2011-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. +// +// Copyright (c) 2012 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "table/block_based_filter_block.h" +#include <algorithm> + +#include "db/dbformat.h" +#include "rocksdb/filter_policy.h" +#include "util/coding.h" +#include "util/perf_context_imp.h" +#include "util/string_util.h" + +namespace rocksdb { + +namespace { + +void AppendItem(std::string* props, const std::string& key, + const std::string& value) { + char cspace = ' '; + std::string value_str(""); + size_t i = 0; + const size_t dataLength = 64; + const size_t tabLength = 2; + const size_t offLength = 16; + + value_str.append(&value[i], std::min(size_t(dataLength), value.size())); + i += dataLength; + while (i < value.size()) { + value_str.append("\n"); + value_str.append(offLength, cspace); + value_str.append(&value[i], std::min(size_t(dataLength), value.size() - i)); + i += dataLength; + } + + std::string result(""); + if (key.size() < (offLength - tabLength)) + result.append(size_t((offLength - tabLength)) - key.size(), cspace); + result.append(key); + + props->append(result + ": " + value_str + "\n"); +} + +template <class TKey> +void AppendItem(std::string* props, const TKey& key, const std::string& value) { + std::string key_str = rocksdb::ToString(key); + AppendItem(props, key_str, value); +} +} // namespace + + +// See doc/table_format.txt for an explanation of the filter block format. + +// Generate new filter every 2KB of data +static const size_t kFilterBaseLg = 11; +static const size_t kFilterBase = 1 << kFilterBaseLg; + +BlockBasedFilterBlockBuilder::BlockBasedFilterBlockBuilder( + const SliceTransform* prefix_extractor, + const BlockBasedTableOptions& table_opt) + : policy_(table_opt.filter_policy.get()), + prefix_extractor_(prefix_extractor), + whole_key_filtering_(table_opt.whole_key_filtering), + prev_prefix_start_(0), + prev_prefix_size_(0) { + assert(policy_); +} + +void BlockBasedFilterBlockBuilder::StartBlock(uint64_t block_offset) { + uint64_t filter_index = (block_offset / kFilterBase); + assert(filter_index >= filter_offsets_.size()); + while (filter_index > filter_offsets_.size()) { + GenerateFilter(); + } +} + +void BlockBasedFilterBlockBuilder::Add(const Slice& key) { + if (prefix_extractor_ && prefix_extractor_->InDomain(key)) { + AddPrefix(key); + } + + if (whole_key_filtering_) { + AddKey(key); + } +} + +// Add key to filter if needed +inline void BlockBasedFilterBlockBuilder::AddKey(const Slice& key) { + start_.push_back(entries_.size()); + entries_.append(key.data(), key.size()); +} + +// Add prefix to filter if needed +inline void BlockBasedFilterBlockBuilder::AddPrefix(const Slice& key) { + // get slice for most recently added entry + Slice prev; + if (prev_prefix_size_ > 0) { + prev = Slice(entries_.data() + prev_prefix_start_, prev_prefix_size_); + } + + Slice prefix = prefix_extractor_->Transform(key); + // insert prefix only when it's different from the previous prefix. + if (prev.size() == 0 || prefix != prev) { + start_.push_back(entries_.size()); + prev_prefix_start_ = entries_.size(); + prev_prefix_size_ = prefix.size(); + entries_.append(prefix.data(), prefix.size()); + } +} + +Slice BlockBasedFilterBlockBuilder::Finish() { + if (!start_.empty()) { + GenerateFilter(); + } + + // Append array of per-filter offsets + const uint32_t array_offset = static_cast<uint32_t>(result_.size()); + for (size_t i = 0; i < filter_offsets_.size(); i++) { + PutFixed32(&result_, filter_offsets_[i]); + } + + PutFixed32(&result_, array_offset); + result_.push_back(kFilterBaseLg); // Save encoding parameter in result + return Slice(result_); +} + +void BlockBasedFilterBlockBuilder::GenerateFilter() { + const size_t num_entries = start_.size(); + if (num_entries == 0) { + // Fast path if there are no keys for this filter + filter_offsets_.push_back(static_cast<uint32_t>(result_.size())); + return; + } + + // Make list of keys from flattened key structure + start_.push_back(entries_.size()); // Simplify length computation + tmp_entries_.resize(num_entries); + for (size_t i = 0; i < num_entries; i++) { + const char* base = entries_.data() + start_[i]; + size_t length = start_[i + 1] - start_[i]; + tmp_entries_[i] = Slice(base, length); + } + + // Generate filter for current set of keys and append to result_. + filter_offsets_.push_back(static_cast<uint32_t>(result_.size())); + policy_->CreateFilter(&tmp_entries_[0], static_cast<int>(num_entries), + &result_); + + tmp_entries_.clear(); + entries_.clear(); + start_.clear(); + prev_prefix_start_ = 0; + prev_prefix_size_ = 0; +} + +BlockBasedFilterBlockReader::BlockBasedFilterBlockReader( + const SliceTransform* prefix_extractor, + const BlockBasedTableOptions& table_opt, bool whole_key_filtering, + BlockContents&& contents) + : policy_(table_opt.filter_policy.get()), + prefix_extractor_(prefix_extractor), + whole_key_filtering_(whole_key_filtering), + data_(nullptr), + offset_(nullptr), + num_(0), + base_lg_(0), + contents_(std::move(contents)) { + assert(policy_); + size_t n = contents_.data.size(); + if (n < 5) return; // 1 byte for base_lg_ and 4 for start of offset array + base_lg_ = contents_.data[n - 1]; + uint32_t last_word = DecodeFixed32(contents_.data.data() + n - 5); + if (last_word > n - 5) return; + data_ = contents_.data.data(); + offset_ = data_ + last_word; + num_ = (n - 5 - last_word) / 4; +} + +bool BlockBasedFilterBlockReader::KeyMayMatch(const Slice& key, + uint64_t block_offset) { + assert(block_offset != kNotValid); + if (!whole_key_filtering_) { + return true; + } + return MayMatch(key, block_offset); +} + +bool BlockBasedFilterBlockReader::PrefixMayMatch(const Slice& prefix, + uint64_t block_offset) { + assert(block_offset != kNotValid); + if (!prefix_extractor_) { + return true; + } + return MayMatch(prefix, block_offset); +} + +bool BlockBasedFilterBlockReader::MayMatch(const Slice& entry, + uint64_t block_offset) { + uint64_t index = block_offset >> base_lg_; + if (index < num_) { + uint32_t start = DecodeFixed32(offset_ + index * 4); + uint32_t limit = DecodeFixed32(offset_ + index * 4 + 4); + if (start <= limit && limit <= (uint32_t)(offset_ - data_)) { + Slice filter = Slice(data_ + start, limit - start); + bool const may_match = policy_->KeyMayMatch(entry, filter); + if (may_match) { + PERF_COUNTER_ADD(bloom_sst_hit_count, 1); + return true; + } else { + PERF_COUNTER_ADD(bloom_sst_miss_count, 1); + return false; + } + } else if (start == limit) { + // Empty filters do not match any entries + return false; + } + } + return true; // Errors are treated as potential matches +} + +size_t BlockBasedFilterBlockReader::ApproximateMemoryUsage() const { + return num_ * 4 + 5 + (offset_ - data_); +} + +std::string BlockBasedFilterBlockReader::ToString() const { + std::string result, filter_meta; + result.reserve(1024); + + std::string s_bo("Block offset"), s_hd("Hex dump"), s_fb("# filter blocks"); + AppendItem(&result, s_fb, rocksdb::ToString(num_)); + AppendItem(&result, s_bo, s_hd); + + for (size_t index = 0; index < num_; index++) { + uint32_t start = DecodeFixed32(offset_ + index * 4); + uint32_t limit = DecodeFixed32(offset_ + index * 4 + 4); + + if (start != limit) { + result.append(" filter block # " + rocksdb::ToString(index + 1) + "\n"); + Slice filter = Slice(data_ + start, limit - start); + AppendItem(&result, start, filter.ToString(true)); + } + } + return result; +} +} // namespace rocksdb diff --git a/pool/shard007/C++/0091765_hat_action_renderer.cpp b/pool/shard007/C++/0091765_hat_action_renderer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..05371744b393ac21bfe44ec47f25bba3ca0ed4fe --- /dev/null +++ b/pool/shard007/C++/0091765_hat_action_renderer.cpp @@ -0,0 +1,78 @@ +#include "render/hat_action_renderer.h" +#include "platform/auto_id.h" +#include "core/i_inventory_component.h" +#include "core/player_controller_component.h" +namespace render { + + +glm::vec4 const ColorRepo::mDefaultColor = glm::vec4( 1, 1, 1, 1 ); + + +ColorRepo::ColorRepo() + : Repository<glm::vec4>( mDefaultColor ) +{ + int32_t i = 0; + mElements.insert( i, new glm::vec4( 0.8, 0.0, 0.0, 1 ) ); + ++i; + mElements.insert( i, new glm::vec4( 0.0, 0.8, 0.8, 1 ) ); + ++i; + mElements.insert( i, new glm::vec4( 0.9, 0.9, 0.0, 1 ) ); + ++i; + mElements.insert( i, new glm::vec4( 0.0, 0.7, 0.0, 1 ) ); + ++i; + mElements.insert( i, new glm::vec4( 0.8, 0.0, 0.8, 1 ) ); + ++i; + mElements.insert( i, new glm::vec4( 0.3, 0.3, 0.3, 1 ) ); + ++i; + mElements.insert( i, new glm::vec4( 0.95, 0.95, 0.95, 1 ) ); + ++i; + mElements.insert( i, new glm::vec4( 1.0, 0.6, 0.0, 1 ) ); + ++i; + mElements.insert( i, new glm::vec4( 0.5, 0.8, 0.5, 1 ) ); + ++i; + mElements.insert( i, new glm::vec4( 0.6, 0.0, 1.0, 1 ) ); + ++i; + mElements.insert( i, new glm::vec4( 0.2, 0.4, 0.8, 1 ) ); + ++i; +} + +HatActionRenderer::HatActionRenderer( int32_t Id ) + : ActionRenderer( Id ) +{ + mHatId = AutoId( "body_color" ); +} + +void HatActionRenderer::Init( const Actor& actor ) +{ + Opt<Weapon> weapon = actor.Get<IInventoryComponent>()->GetSelectedWeapon(); + if ( !weapon.IsValid() ) + { + return; + } + SpriteCollection const& Sprites = mRenderableRepo( actor.GetId() ); + Sprite const& Spr = Sprites( mHatId ); + if( Spr.IsValid() ) + { + mSecsToEnd = Spr.GetSecsToEnd(); + } +} + +void HatActionRenderer::FillRenderableSprites( const Actor& actor, IRenderableComponent const& renderableC, RenderableSprites_t& renderableSprites ) +{ + SpriteCollection const& Sprites = mRenderableRepo( actor.GetId() ); + Sprite const& Spr = Sprites( mHatId ); + if( Spr.IsValid() ) + { + SpritePhase const& Phase = Spr( ( int32_t )GetState() ); + Opt<PlayerControllerComponent> playerCC = actor.Get<IControllerComponent>(); + glm::vec4 col = (playerCC.IsValid() ? ColorRepo::Get()(playerCC->mControllerId) : glm::vec4( 1, 1, 1, 1 ))*GetColor( actor ); + col.a = GetCloakColor( actor ).a; + col = col * GetColor( actor ); + renderableSprites.push_back( + RenderableSprite( &actor, &renderableC, mHatId, &Spr, &Phase, col ) ); + } +} + + + +} // namespace render diff --git a/pool/shard007/C++/0091767_lru-cache-test.cc b/pool/shard007/C++/0091767_lru-cache-test.cc new file mode 100644 index 0000000000000000000000000000000000000000..a10d6aebd5967c11452c062204f82b5b0eb41ac5 --- /dev/null +++ b/pool/shard007/C++/0091767_lru-cache-test.cc @@ -0,0 +1,155 @@ +// Copyright 2015 Cloudera Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "lru-cache.h" + +#include <boost/thread.hpp> +#include <glog/logging.h> +#include <gtest/gtest.h> + +#include "common/init.h" +#include "common/logging.h" +#include "util/test-info.h" + +#include "common/names.h" + +using boost::thread; +using boost::thread_group; + +using namespace impala; + +TEST(FifoMultimap, Basic) { + FifoMultimap<int, int> c(3); + int result; + ASSERT_EQ(3, c.capacity()); + c.Put(0, 1); + c.Put(0, 2); + ASSERT_EQ(2, c.size()); + ASSERT_FALSE(c.Pop(99, &result)); + c.Pop(0, &result); + c.Pop(0, &result); + ASSERT_FALSE(c.Pop(0, &result)); +} + +TEST(FifoMultimap, Invalid) { + FifoMultimap<int, int> c(0); + int result; + ASSERT_EQ(0, c.capacity()); + c.Put(0, 1); + ASSERT_EQ(0, c.size()); + ASSERT_FALSE(c.Pop(99, &result)); +} + +TEST(FifoMultimap, Evict) { + FifoMultimap<int, int> c(3); + int result; + c.Put(0, 1); + c.Put(1, 2); + c.Put(2, 3); + ASSERT_EQ(3, c.size()); + c.Put(3, 4); + ASSERT_EQ(3, c.size()); + ASSERT_FALSE(c.Pop(0, &result)); + ASSERT_TRUE(c.Pop(1, &result)); + ASSERT_EQ(2, result); + ASSERT_FALSE(c.Pop(1, &result)); + ASSERT_EQ(2, c.size()); +} + +TEST(FifoMultimap, Large) { + FifoMultimap<int, int> c(1000); + int result; + for (int i = 0; i < 1000; ++i) { + c.Put(i, i); + } + ASSERT_EQ(1000, c.size()); + for (int i = 0; i < 2000; ++i) { + int key = rand(); + c.Pop(key % 1000, &result); + ASSERT_EQ(999, c.size()); + c.Put(key % 1000, i); + ASSERT_EQ(1000, c.size()); + } +} + +static int del_sum = 0; +void TestDeleter(int* v) { del_sum += *v; } + +TEST(FifoMultimap, Deleter) { + FifoMultimap<int, int> c(10, TestDeleter); + for (int i = 1; i <= 1000; ++i) { + c.Put(i, i); + } + int n = 1000 - c.capacity(); + // All values from 1 to n have been evicted, so the sum of all values must match del_sum + ASSERT_EQ((n * (n + 1)) / 2, del_sum); +} + +static int del_count = 0; +void TestCountDeleter(int* v) { ++del_count; } + +void ParallelPut(const int start, const int end, FifoMultimap<int, int>* shelf) { + int val; + for (int i = start; i < end; ++i) { + if (i % 3 == 0) { + if (shelf->Pop(i, &val)) { + shelf->Put(i, i); + } + } + shelf->Put(i, i); + } +} + +TEST(FifoMultimap, ParallelEviction) { + del_sum = 0; + FifoMultimap<int, int> c(10, TestCountDeleter); + + thread_group group; + size_t count = 100000; + size_t thread_count = 10; + size_t part = count / thread_count; + for (int i = 0; i < thread_count; ++i) { + group.add_thread(new thread(ParallelPut, 0, part, &c)); + } + group.join_all(); + ASSERT_EQ(10, c.size()); + ASSERT_EQ(count - c.capacity(), del_count); +} + +TEST(FifoMultimap, PopShouldPopMostRecent) { + FifoMultimap<int, int> c(3); + int result; + c.Put(1, 1); + c.Put(1, 2); + c.Put(1, 3); + ASSERT_TRUE(c.Pop(1, &result)); + ASSERT_EQ(3, result); + c.Put(1, 3); + c.Put(1, 4); + ASSERT_EQ(3, c.size()); + ASSERT_TRUE(c.Pop(1, &result)); + ASSERT_EQ(4, result); + ASSERT_EQ(2, c.size()); + ASSERT_TRUE(c.Pop(1, &result)); + ASSERT_EQ(3, result); + ASSERT_EQ(1, c.size()); + ASSERT_TRUE(c.Pop(1, &result)); + ASSERT_EQ(2, result); + ASSERT_EQ(0, c.size()); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/pool/shard007/C++/0091769_TestProfile.cpp b/pool/shard007/C++/0091769_TestProfile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..beb13fb7fdf08ce983ee8989437bf95d5af8a9d6 --- /dev/null +++ b/pool/shard007/C++/0091769_TestProfile.cpp @@ -0,0 +1,148 @@ +/* Copyright_License { + + XCSoar Glide Computer - http://www.xcsoar.org/ + Copyright (C) 2000-2014 The XCSoar Project + A detailed list of copyright holders can be found in the file "AUTHORS". + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +} +*/ + +#include "Profile/Profile.hpp" +#include "IO/FileLineReader.hpp" +#include "TestUtil.hpp" + +static void +TestMap() +{ + Profile::Clear(); + + { + int value; + ok1(!Profile::Exists("key1")); + ok1(!Profile::Get("key1", value)); + Profile::Set("key1", 4); + ok1(Profile::Exists("key1")); + ok1(Profile::Get("key1", value)); + ok1(value == 4); + } + + { + short value; + ok1(!Profile::Get("key2", value)); + Profile::Set("key2", 123); + ok1(Profile::Get("key2", value)); + ok1(value == 123); + } + + { + unsigned value; + ok1(!Profile::Get("key3", value)); + Profile::Set("key3", -42); + ok1(Profile::Get("key3", value)); + ok1(value == -42u); + } + + { + bool value; + ok1(!Profile::Get("key4", value)); + Profile::Set("key4", true); + ok1(Profile::Get("key4", value)); + ok1(value); + Profile::Set("key4", false); + ok1(Profile::Get("key4", value)); + ok1(!value); + } + + { + fixed value; + ok1(!Profile::Get("key5", value)); + Profile::Set("key5", fixed(1.337)); + ok1(Profile::Get("key5", value)); + ok1(equals(value, 1.337)); + } +} + +static void +TestWriter() +{ + Profile::Clear(); + Profile::Set("key1", 4); + Profile::Set("key2", "value2"); + + Profile::SaveFile(_T("output/TestProfileWriter.prf")); + + FileLineReader reader(_T("output/TestProfileWriter.prf")); + if (reader.error()) { + skip(3, 0, "read error"); + return; + } + + unsigned count = 0; + bool found1 = false, found2 = false; + + TCHAR *line; + while ((line = reader.ReadLine()) != NULL) { + if (_tcscmp(line, _T("key1=\"4\"")) == 0) + found1 = true; + if (_tcscmp(line, _T("key2=\"value2\"")) == 0) + found2 = true; + + count++; + } + + ok1(count == 2); + ok1(found1); + ok1(found2); +} + +static void +TestReader() +{ + Profile::Clear(); + Profile::LoadFile(_T("test/data/TestProfileReader.prf")); + + { + int value; + ok1(Profile::Exists("key1")); + ok1(Profile::Get("key1", value)); + ok1(value == 1); + } + + { + StaticString<32> value; + ok1(Profile::Exists("key2")); + ok1(Profile::Get("key2", value)); + ok1(value == _T("value")); + } + + { + int value; + ok1(Profile::Exists("key3")); + ok1(Profile::Get("key3", value)); + ok1(value == 5); + } +} + +int main(int argc, char **argv) +{ + plan_tests(31); + + TestMap(); + TestWriter(); + TestReader(); + + return exit_status(); +} diff --git a/pool/shard007/C++/0091770_qglcolormap.cpp b/pool/shard007/C++/0091770_qglcolormap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f480f35f8ad6150ba67ad2e6449f7e68f62018e --- /dev/null +++ b/pool/shard007/C++/0091770_qglcolormap.cpp @@ -0,0 +1,297 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the QtOpenGL module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \class QGLColormap + \brief The QGLColormap class is used for installing custom colormaps into + a QGLWidget. + + \module OpenGL + \ingroup painting-3D + \ingroup shared + + QGLColormap provides a platform independent way of specifying and + installing indexed colormaps for a QGLWidget. QGLColormap is + especially useful when using the OpenGL color-index mode. + + Under X11 you must use an X server that supports either a \c + PseudoColor or \c DirectColor visual class. If your X server + currently only provides a \c GrayScale, \c TrueColor, \c + StaticColor or \c StaticGray visual, you will not be able to + allocate colorcells for writing. If this is the case, try setting + your X server to 8 bit mode. It should then provide you with at + least a \c PseudoColor visual. Note that you may experience + colormap flashing if your X server is running in 8 bit mode. + + The size() of the colormap is always set to 256 + colors. Note that under Windows you can also install colormaps + in child widgets. + + This class uses \l{implicit sharing} as a memory and speed + optimization. + + Example of use: + \snippet doc/src/snippets/code/src_opengl_qglcolormap.cpp 0 + + \sa QGLWidget::setColormap(), QGLWidget::colormap() +*/ + +/*! + \fn Qt::HANDLE QGLColormap::handle() + + \internal + + Returns the handle for this color map. +*/ + +/*! + \fn void QGLColormap::setHandle(Qt::HANDLE handle) + + \internal + + Sets the handle for this color map to \a handle. +*/ + +#include "qglcolormap.h" + +QT_BEGIN_NAMESPACE + +QGLColormap::QGLColormapData QGLColormap::shared_null = { Q_BASIC_ATOMIC_INITIALIZER(1), 0, 0 }; + +/*! + Construct a QGLColormap. +*/ +QGLColormap::QGLColormap() + : d(&shared_null) +{ + d->ref.ref(); +} + + +/*! + Construct a shallow copy of \a map. +*/ +QGLColormap::QGLColormap(const QGLColormap &map) + : d(map.d) +{ + d->ref.ref(); +} + +/*! + Dereferences the QGLColormap and deletes it if this was the last + reference to it. +*/ +QGLColormap::~QGLColormap() +{ + if (!d->ref.deref()) + cleanup(d); +} + +void QGLColormap::cleanup(QGLColormap::QGLColormapData *x) +{ + delete x->cells; + x->cells = 0; + delete x; +} + +/*! + Assign a shallow copy of \a map to this QGLColormap. +*/ +QGLColormap & QGLColormap::operator=(const QGLColormap &map) +{ + map.d->ref.ref(); + if (!d->ref.deref()) + cleanup(d); + d = map.d; + return *this; +} + +/*! + \fn void QGLColormap::detach() + \internal + + Detaches this QGLColormap from the shared block. +*/ + +void QGLColormap::detach_helper() +{ + QGLColormapData *x = new QGLColormapData; + x->ref = 1; + x->cmapHandle = 0; + x->cells = 0; + if (d->cells) { + x->cells = new QVector<QRgb>(256); + *x->cells = *d->cells; + } + if (!d->ref.deref()) + cleanup(d); + d = x; +} + +/*! + Set cell at index \a idx in the colormap to color \a color. +*/ +void QGLColormap::setEntry(int idx, QRgb color) +{ + detach(); + if (!d->cells) + d->cells = new QVector<QRgb>(256); + d->cells->replace(idx, color); +} + +/*! + Set an array of cells in this colormap. \a count is the number of + colors that should be set, \a colors is the array of colors, and + \a base is the starting index. The first element in \a colors + is set at \a base in the colormap. +*/ +void QGLColormap::setEntries(int count, const QRgb *colors, int base) +{ + detach(); + if (!d->cells) + d->cells = new QVector<QRgb>(256); + + Q_ASSERT_X(colors && base >= 0 && (base + count) <= d->cells->size(), "QGLColormap::setEntries", + "preconditions not met"); + for (int i = 0; i < count; ++i) + setEntry(base + i, colors[i]); +} + +/*! + Returns the QRgb value in the colorcell with index \a idx. +*/ +QRgb QGLColormap::entryRgb(int idx) const +{ + if (d == &shared_null || !d->cells) + return 0; + else + return d->cells->at(idx); +} + +/*! + \overload + + Set the cell with index \a idx in the colormap to color \a color. +*/ +void QGLColormap::setEntry(int idx, const QColor &color) +{ + setEntry(idx, color.rgb()); +} + +/*! + Returns the QRgb value in the colorcell with index \a idx. +*/ +QColor QGLColormap::entryColor(int idx) const +{ + if (d == &shared_null || !d->cells) + return QColor(); + else + return QColor(d->cells->at(idx)); +} + +/*! + Returns true if the colormap is empty or it is not in use + by a QGLWidget; otherwise returns false. + + A colormap with no color values set is considered to be empty. + For historical reasons, a colormap that has color values set + but which is not in use by a QGLWidget is also considered empty. + + Compare size() with zero to determine if the colormap is empty + regardless of whether it is in use by a QGLWidget or not. + + \sa size() +*/ +bool QGLColormap::isEmpty() const +{ + return d == &shared_null || d->cells == 0 || d->cells->size() == 0 || d->cmapHandle == 0; +} + + +/*! + Returns the number of colorcells in the colormap. +*/ +int QGLColormap::size() const +{ + return d->cells ? d->cells->size() : 0; +} + +/*! + Returns the index of the color \a color. If \a color is not in the + map, -1 is returned. +*/ +int QGLColormap::find(QRgb color) const +{ + if (d->cells) + return d->cells->indexOf(color); + return -1; +} + +/*! + Returns the index of the color that is the closest match to color + \a color. +*/ +int QGLColormap::findNearest(QRgb color) const +{ + int idx = find(color); + if (idx >= 0) + return idx; + int mapSize = size(); + int mindist = 200000; + int r = qRed(color); + int g = qGreen(color); + int b = qBlue(color); + int rx, gx, bx, dist; + for (int i = 0; i < mapSize; ++i) { + QRgb ci = d->cells->at(i); + rx = r - qRed(ci); + gx = g - qGreen(ci); + bx = b - qBlue(ci); + dist = rx * rx + gx * gx + bx * bx; // calculate distance + if (dist < mindist) { // minimal? + mindist = dist; + idx = i; + } + } + return idx; +} + +QT_END_NAMESPACE diff --git a/pool/shard007/C++/0091774_FramedReader.cpp b/pool/shard007/C++/0091774_FramedReader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..02edba6943ed28a534302664b79f8cfbabfb8c6e --- /dev/null +++ b/pool/shard007/C++/0091774_FramedReader.cpp @@ -0,0 +1,217 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "rsocket/framing/FramedReader.h" + +#include <folly/io/Cursor.h> + +#include "rsocket/framing/FrameSerializer_v1_0.h" +#include "rsocket/internal/Common.h" + +namespace rsocket { + +using namespace yarpl::flowable; + +namespace { + +constexpr size_t kFrameLengthFieldLengthV1_0 = 3; + +/// Get the byte size of the frame length field in an RSocket frame. +size_t frameSizeFieldLength(ProtocolVersion version) { + DCHECK_NE(version, ProtocolVersion::Unknown); + return kFrameLengthFieldLengthV1_0; +} + +/// Get the minimum size for a valid RSocket frame (including its frame length +/// field). +size_t minimalFrameLength(ProtocolVersion version) { + DCHECK_NE(version, ProtocolVersion::Unknown); + return FrameSerializerV1_0::kFrameHeaderSize; +} + +/// Compute the length of the entire frame (including its frame length field), +/// if given only its frame length field. +size_t frameSizeWithLengthField(ProtocolVersion version, size_t frameSize) { + return version < FrameSerializerV1_0::Version + ? frameSize + : frameSize + frameSizeFieldLength(version); +} + +/// Compute the length of the frame (excluding its frame length field), if given +/// only its frame length field. +size_t frameSizeWithoutLengthField(ProtocolVersion version, size_t frameSize) { + DCHECK_NE(version, ProtocolVersion::Unknown); + return version < FrameSerializerV1_0::Version + ? frameSize - frameSizeFieldLength(version) + : frameSize; +} +} // namespace + +size_t FramedReader::readFrameLength() const { + const auto fieldLength = frameSizeFieldLength(*version_); + DCHECK_GT(fieldLength, 0); + + folly::io::Cursor cur{payloadQueue_.front()}; + size_t frameLength = 0; + + // Reading of arbitrary-sized big-endian integer. + for (size_t i = 0; i < fieldLength; ++i) { + frameLength <<= 8; + frameLength |= cur.read<uint8_t>(); + } + + return frameLength; +} + +void FramedReader::onSubscribe(std::shared_ptr<Subscription> subscription) { + subscription_ = std::move(subscription); + subscription_->request(std::numeric_limits<int64_t>::max()); +} + +void FramedReader::onNext(std::unique_ptr<folly::IOBuf> payload) { + VLOG(4) << "incoming bytes length=" << payload->length() << '\n' + << hexDump(payload->clone()->moveToFbString()); + payloadQueue_.append(std::move(payload)); + parseFrames(); +} + +void FramedReader::parseFrames() { + if (dispatchingFrames_) { + return; + } + + // Delivering onNext can trigger termination and destroy this instance. + auto const self = shared_from_this(); + + dispatchingFrames_ = true; + + while (allowance_.canConsume(1) && inner_) { + if (!ensureOrAutodetectProtocolVersion()) { + // At this point we dont have enough bytes on the wire or we errored out. + break; + } + + auto const frameSizeFieldLen = frameSizeFieldLength(*version_); + if (payloadQueue_.chainLength() < frameSizeFieldLen) { + // We don't even have the next frame size value. + break; + } + + auto const nextFrameSize = readFrameLength(); + if (nextFrameSize < minimalFrameLength(*version_)) { + error("Invalid frame - Frame size smaller than minimum"); + break; + } + + if (payloadQueue_.chainLength() < + frameSizeWithLengthField(*version_, nextFrameSize)) { + // Need to accumulate more data. + break; + } + + payloadQueue_.trimStart(frameSizeFieldLen); + const auto payloadSize = + frameSizeWithoutLengthField(*version_, nextFrameSize); + + DCHECK_GT(payloadSize, 0) + << "folly::IOBufQueue::split(0) returns a nullptr, can't have that"; + auto nextFrame = payloadQueue_.split(payloadSize); + + CHECK(allowance_.tryConsume(1)); + + VLOG(4) << "parsed frame length=" << nextFrame->length() << '\n' + << hexDump(nextFrame->clone()->moveToFbString()); + inner_->onNext(std::move(nextFrame)); + } + + dispatchingFrames_ = false; +} + +void FramedReader::onComplete() { + payloadQueue_.move(); + auto subscription = std::move(subscription_); + if (auto subscriber = std::move(inner_)) { + // After this call the instance can be destroyed! + subscriber->onComplete(); + } +} + +void FramedReader::onError(folly::exception_wrapper ex) { + payloadQueue_.move(); + auto subscription = std::move(subscription_); + if (auto subscriber = std::move(inner_)) { + // After this call the instance can be destroyed! + subscriber->onError(std::move(ex)); + } +} + +void FramedReader::request(int64_t n) { + allowance_.add(n); + parseFrames(); +} + +void FramedReader::cancel() { + allowance_.consumeAll(); + inner_ = nullptr; +} + +void FramedReader::setInput( + std::shared_ptr<DuplexConnection::Subscriber> inner) { + CHECK(!inner_) + << "Must cancel original input to FramedReader before setting a new one"; + inner_ = std::move(inner); + inner_->onSubscribe(shared_from_this()); +} + +bool FramedReader::ensureOrAutodetectProtocolVersion() { + if (*version_ != ProtocolVersion::Unknown) { + return true; + } + + const auto minBytesNeeded = + FrameSerializerV1_0::kMinBytesNeededForAutodetection; + DCHECK_GT(minBytesNeeded, 0); + if (payloadQueue_.chainLength() < minBytesNeeded) { + return false; + } + + DCHECK_GT(minBytesNeeded, kFrameLengthFieldLengthV1_0); + + auto const& firstFrame = *payloadQueue_.front(); + + const auto detectedV1 = FrameSerializerV1_0::detectProtocolVersion( + firstFrame, kFrameLengthFieldLengthV1_0); + if (detectedV1 != ProtocolVersion::Unknown) { + *version_ = FrameSerializerV1_0::Version; + return true; + } + + error("Could not detect protocol version from framing"); + return false; +} + +void FramedReader::error(std::string errorMsg) { + VLOG(1) << "error: " << errorMsg; + + payloadQueue_.move(); + if (auto subscription = std::move(subscription_)) { + subscription->cancel(); + } + if (auto subscriber = std::move(inner_)) { + // After this call the instance can be destroyed! + subscriber->onError(std::runtime_error{std::move(errorMsg)}); + } +} + +} // namespace rsocket diff --git a/pool/shard007/C++/0091779_decoder.cpp b/pool/shard007/C++/0091779_decoder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..60c2b1ea4100534f93936aadcb29a04c7322374f --- /dev/null +++ b/pool/shard007/C++/0091779_decoder.cpp @@ -0,0 +1,139 @@ +// +// decoder.cpp +// console +// +// Created by huanghaifeng on 14-10-1. +// Copyright (c) 2014 wonghoifung. All rights reserved. +// + +#include "decoder.h" + +int decoder::read_int() +{ + int val(-1); + codec::read_b((char*)&val, sizeof(int)); + return endian_op(val); +} + +int decoder::read_int_and_repack() +{ + int val(-1); + codec::read_del_b((char*)&val, sizeof(int)); + return endian_op(val); +} + +unsigned int decoder::read_uint() +{ + unsigned int val(0); + codec::read_b((char*)&val, sizeof(unsigned int)); + return endian_op(val); +} + +int64_t decoder::read_int64() +{ + int64_t val(0); + codec::read_b((char*)&val, sizeof(int64_t)); + return endian_op(val); +} + +uint64_t decoder::read_uint64() +{ + uint64_t val(0); + codec::read_b((char*)&val, sizeof(uint64_t)); + return endian_op(val); +} + +long decoder::read_long() +{ + long val(0); + codec::read_b((char*)&val, sizeof(long)); + return endian_op(val); +} + +unsigned long decoder::read_ulong() +{ + unsigned long val(0); + codec::read_b((char*)&val, sizeof(unsigned long)); + return endian_op(val); +} + +short decoder::read_short() +{ + short val(-1); + codec::read_b((char*)&val, sizeof(short)); + return endian_op(val); +} + +unsigned short decoder::read_ushort() +{ + unsigned short val(0); + codec::read_b((char*)&val, sizeof(unsigned short)); + return endian_op(val); +} + +char decoder::read_char() +{ + char val(0); + codec::read_b((char*)&val, sizeof(char)); + return endian_op(val); +} + +unsigned char decoder::read_uchar() +{ + unsigned char val(0); + codec::read_b((char*)&val, sizeof(unsigned char)); + return endian_op(val); +} + +char* decoder::read_cstring() +{ + int len = read_int(); + if(len <= 0 || len >= c_buffer_size) + return NULL; + return codec::read_bytes_b(len); +} + +int decoder::read_binary(char* outbuf, int maxlen) +{ + int len = read_int(); + if(len <= 0) + return -1; + if (len > maxlen) + { + codec::read_undo_b(sizeof(int)); + return -1; + } + if (codec::read_b(outbuf, len)) + return len; + return 0; +} + +uint32_t decoder::read_body(char* outbuf, uint32_t maxlen) +{ + uint32_t bodylen = codec::length(); + if (bodylen > maxlen) + { + return 0; + } + if (codec::read_b(outbuf, bodylen)) + { + return bodylen; + } + return 0; +} + +bool decoder::copy(const void* inbuf, int len) +{ + return codec::copy_b(inbuf, len); +} + +void decoder::begin(uint16_t cmd) +{ + codec::begin_b(cmd); +} + +void decoder::end() +{ + codec::end_b(); +} + diff --git a/pool/shard007/C++/0091785_criticalsection.cc b/pool/shard007/C++/0091785_criticalsection.cc new file mode 100644 index 0000000000000000000000000000000000000000..344f67666e1c890afee0b9d82442ba80e698b82e --- /dev/null +++ b/pool/shard007/C++/0091785_criticalsection.cc @@ -0,0 +1,81 @@ +// Copyright 2009 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +#include "common/criticalsection.h" + +#ifdef WIN32 + +CriticalSection::CriticalSection() { + InitializeCriticalSection(&criticalsection_); +} + +CriticalSection::~CriticalSection() { + DeleteCriticalSection(&criticalsection_); +} + +bool CriticalSection::Enter(bool wait) { + if (wait) { + // Should always succeed. + EnterCriticalSection(&criticalsection_); + return true; + } else { + return TryEnterCriticalSection(&criticalsection_) != 0; + } +} + +void CriticalSection::Leave() { + LeaveCriticalSection(&criticalsection_); +} + +#elif defined(__linux__) || defined(__unix__) + +CriticalSection::CriticalSection() { + pthread_mutex_init(&mutex_, NULL); +} + +CriticalSection::~CriticalSection() { + pthread_mutex_destroy(&mutex_); +} + +bool CriticalSection::Enter(bool wait) { + if (wait) { + return pthread_mutex_lock(&mutex_) == 0; + } else { + return pthread_mutex_trylock(&mutex_) == 0; + } +} + +void CriticalSection::Leave() { + pthread_mutex_unlock(&mutex_); +} + +#endif + + +AutoLeave::AutoLeave(CriticalSection *cs) { + critical_section_ = cs; + left_ = false; +} + +void AutoLeave::LeaveAhead() { + if (!left_) { + critical_section_->Leave(); + left_ = true; + } +} + +AutoLeave::~AutoLeave() { + LeaveAhead(); +} diff --git a/pool/shard007/C++/0091786_xxWindow.cc b/pool/shard007/C++/0091786_xxWindow.cc new file mode 100644 index 0000000000000000000000000000000000000000..2062960aa966167ffd20271b19abf71ad4481876 --- /dev/null +++ b/pool/shard007/C++/0091786_xxWindow.cc @@ -0,0 +1,281 @@ +// $Id: xxWindow.cc 5749 2014-10-11 19:42:10Z flaterco $ + +/* xxWindow An XTide window. + + Copyright (C) 1998 David Flater. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "xtide.hh" + + +static void xxWindowCloseHandler (Widget w unusedParameter, + XtPointer client_data, + XEvent *event, + Boolean *continue_dispatch unusedParameter) { + xxWindow *f ((xxWindow *)client_data); + if (f->noClose) + return; + if (event->type == ClientMessage) { + XClientMessageEvent *ev ((XClientMessageEvent *) event); + // Window manager close. + if (ev->message_type == xxX::protocolAtom && + ev->data.l[0] == (int)(xxX::killAtom)) + delete f->dismiss(); + } +} + + +xxWindow::xxWindow (int &argc, char **argv): + noClose(false), + _containerType(noContainer), + _grabKind(XtGrabNone), + _iconWindow(0), + _isRealized(false) { + + popup = xxX::wrap (xxX::connect (argc, argv)); + // Can't set colors until after the settings have been processed! + // See xxRoot::xxRoot. + XtAddEventHandler (popup->widget(), NoEventMask, True, + xxWindowCloseHandler, (XtPointer)this); + setIcon(); +} + + +xxWindow::xxWindow (const xxWidget &parent, + ContainerType containerType, + XtGrabKind grabKind): + noClose(false), + _containerType(containerType), + _grabKind(grabKind), + _iconWindow(0), + _isRealized(false) { + + xxroot->dup (this); + { + // I have to specify this stuff explicitly under Openwin. + // Probably has to do with using non-default colormap. + Arg args[5] = { + {XtNdepth, (XtArgVal)xxX::colordepth}, + {XtNvisual, (XtArgVal)xxX::visual}, + {XtNcolormap, (XtArgVal)xxX::colormap}, + {XtNborderColor, (XtArgVal)0}, + {XtNbackground, (XtArgVal)0} + }; + popup = xxX::wrap (XtCreatePopupShell ("XTide", + topLevelShellWidgetClass, + parent.widget(), + args, + 5)); + }{ + Arg args[2] = { + {XtNbackground, (XtArgVal)xxX::pixels[Colors::background]}, + {XtNforeground, (XtArgVal)xxX::pixels[Colors::foreground]} + }; + XtSetValues (popup->widget(), args, 2); + switch (_containerType) { + case noContainer: + break; + case boxContainer: + container = xxX::wrap (xxX::createXtWidget ("", + boxWidgetClass, + popup->widget(), + args, + 2)); + break; + case formContainer: + container = xxX::wrap (xxX::createXtWidget ("", + formWidgetClass, + popup->widget(), + args, + 2)); + break; + default: + assert (false); + } + } + XtAddEventHandler (popup->widget(), NoEventMask, True, + xxWindowCloseHandler, (XtPointer)this); + setIcon(); +} + + +xxWindow * const xxWindow::dismiss() { + return this; +} + + +// This should never be called for xxRoot since it dies only on exit(). +xxWindow::~xxWindow() { + unrealize(); + xxroot->release (this); + if (_iconWindow) + XDestroyWindow (xxX::display, _iconWindow); +} + + +void xxWindow::move (const Dstr &geometry) { + int xoff, yoff; + if (sscanf (geometry.aschar(), "%d%d", &xoff, &yoff) == 2) { + bool negx ((xoff < 0 || (xoff == 0 && geometry[0] == '-'))); + bool negy ((yoff < 0 || (yoff == 0 && geometry.strrchr('-') > 0))); + if (negx || negy) { + Dimension width, height; + Arg args[2] = { + {XtNwidth, (XtArgVal)(&width)}, + {XtNheight, (XtArgVal)(&height)} + }; + XtGetValues (popup->widget(), args, 2); + if (negx) + xoff += (int)(DisplayWidth(xxX::display,xxX::screenNum)) - width; + if (negy) + yoff += (int)(DisplayHeight(xxX::display,xxX::screenNum)) - height; + } + XMoveWindow (xxX::display, XtWindow(popup->widget()), xoff, yoff); + } +} + + +void xxWindow::globalRedraw() { + Arg args[2] = { + {XtNbackground, (XtArgVal)xxX::pixels[Colors::background]}, + {XtNforeground, (XtArgVal)xxX::pixels[Colors::foreground]} + }; + assert (popup.get()); + XtSetValues (popup->widget(), args, 2); + if (container.get()) + XtSetValues (container->widget(), args, 2); +} + + +void xxWindow::fixSize() { + assert (_isRealized); + Dimension width, height; + Arg args[2] = { + {XtNwidth, (XtArgVal)&width}, + {XtNheight, (XtArgVal)&height} + }; + Widget popupWidget (popup->widget()); + XtGetValues (popupWidget, args, 2); + XSizeHints sizeHint; + sizeHint.min_width = sizeHint.max_width = width; + sizeHint.min_height = sizeHint.max_height = height; + sizeHint.flags = PMinSize | PMaxSize; + XSetWMNormalHints (xxX::display, XtWindow(popupWidget), &sizeHint); +} + + +void xxWindow::setMinSize (Dimension width, Dimension height) { + assert (_isRealized); + XSizeHints sizeHint; + sizeHint.min_width = width; + sizeHint.min_height = height; + sizeHint.flags = PMinSize; + XSetWMNormalHints (xxX::display, XtWindow(popup->widget()), &sizeHint); +} + + +void xxWindow::widthNoSmaller() { + assert (_isRealized); + Dimension width; + Arg args[1] = { + {XtNwidth, (XtArgVal)&width} + }; + Widget popupWidget (popup->widget()); + XtGetValues (popupWidget, args, 1); + XSizeHints sizeHint; + sizeHint.min_width = width; + sizeHint.min_height = 0; + sizeHint.flags = PMinSize; + XSetWMNormalHints (xxX::display, XtWindow(popupWidget), &sizeHint); +} + + +void xxWindow::realize() { + if (!_isRealized) { + Widget popupWidget (popup->widget()); + XtPopup (popupWidget, _grabKind); + XSetWMProtocols (xxX::display, XtWindow(popupWidget), &xxX::killAtom, 1); + _isRealized = true; + setTitle_NET_WM(); + } +} + + +void xxWindow::unrealize() { + if (_isRealized) { + XtPopdown (popup->widget()); + _isRealized = false; + } +} + + +void xxWindow::setIcon() { + XSetWindowAttributes xswa; + xswa.background_pixmap = xxX::iconPixmap; + _iconWindow = XCreateWindow (xxX::display, + xxX::rootWindow, + 0, + 0, + xxX::iconSize, + xxX::iconSize, + 0, + xxX::iconColordepth, + InputOutput, + xxX::iconVisual, + CWBackPixmap, + &xswa); + Arg args[1] = { + {XtNiconWindow, (XtArgVal)_iconWindow} + }; + XtSetValues (popup->widget(), args, 1); +} + + +void xxWindow::setTitle (const Dstr &title) { + _title = "XTide: "; + _title += title; + + Arg args[2] = { + {XtNtitle, (XtArgVal)_title.aschar()}, + {XtNiconName, (XtArgVal)_title.aschar()} + }; + XtSetValues (popup->widget(), args, 2); + + setTitle_NET_WM(); +} + + +// In cases where a non-default locale is in use, the expected +// encoding of XtNtitle is ambiguous. The Window Manager +// Specification added _NET_WM_NAME to get around this. It's always +// in UTF-8. However, not all window managers support it. + +void xxWindow::setTitle_NET_WM () { + if (_isRealized && !_title.isNull()) { + Dstr temp (_title); + temp.utf8(); + XChangeProperty (xxX::display, + XtWindow(popup->widget()), + XInternAtom(xxX::display, "_NET_WM_NAME", False), + XInternAtom(xxX::display, "UTF8_STRING", False), + 8, + PropModeReplace, + (unsigned char *)temp.aschar(), + temp.length()); + } +} + +// Cleanup2006 Done diff --git a/pool/shard007/C++/0091787_ctkVTKErrorLogMessageHandler.cpp b/pool/shard007/C++/0091787_ctkVTKErrorLogMessageHandler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0175f746fe287c5ab83c018ba2190989a0cb7a3f --- /dev/null +++ b/pool/shard007/C++/0091787_ctkVTKErrorLogMessageHandler.cpp @@ -0,0 +1,200 @@ +/*========================================================================= + + Library: CTK + + Copyright (c) Kitware Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0.txt + + 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. + +=========================================================================*/ + +// Qt includes +#include <QThread> + +// CTK includes +#include "ctkVTKErrorLogMessageHandler.h" +#include "ctkUtils.h" + +// VTK includes +#include <vtkObjectFactory.h> +#include <vtkOutputWindow.h> + +namespace { + +// -------------------------------------------------------------------------- +// ctkVTKOutputWindow + +// -------------------------------------------------------------------------- +class ctkVTKOutputWindow : public vtkOutputWindow +{ +public: + static ctkVTKOutputWindow *New(); + vtkTypeMacro(ctkVTKOutputWindow,vtkOutputWindow); + void PrintSelf(ostream& os, vtkIndent indent); + + ctkVTKOutputWindow():MessageHandler(0){} + ~ctkVTKOutputWindow(){} + + virtual void DisplayText(const char*); + virtual void DisplayErrorText(const char*); + virtual void DisplayWarningText(const char*); + virtual void DisplayGenericWarningText(const char*); + + virtual void DisplayDebugText(const char*); + + ctkErrorLogAbstractMessageHandler * MessageHandler; +}; + +// -------------------------------------------------------------------------- +// ctkVTKOutputWindow methods + +// -------------------------------------------------------------------------- +vtkStandardNewMacro(ctkVTKOutputWindow); + +//---------------------------------------------------------------------------- +void ctkVTKOutputWindow::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os,indent); +} + +//---------------------------------------------------------------------------- +void ctkVTKOutputWindow::DisplayText(const char* text) +{ + Q_ASSERT(this->MessageHandler); + this->MessageHandler->handleMessage( + ctk::qtHandleToString(QThread::currentThreadId()), + ctkErrorLogLevel::Info, + this->MessageHandler->handlerPrettyName(), text); +} + +//---------------------------------------------------------------------------- +void ctkVTKOutputWindow::DisplayErrorText(const char* text) +{ + Q_ASSERT(this->MessageHandler); + this->MessageHandler->handleMessage( + ctk::qtHandleToString(QThread::currentThreadId()), + ctkErrorLogLevel::Error, + this->MessageHandler->handlerPrettyName(), text); +} + +//---------------------------------------------------------------------------- +void ctkVTKOutputWindow::DisplayWarningText(const char* text) +{ + Q_ASSERT(this->MessageHandler); + this->MessageHandler->handleMessage( + ctk::qtHandleToString(QThread::currentThreadId()), + ctkErrorLogLevel::Warning, + this->MessageHandler->handlerPrettyName(), text); +} + +//---------------------------------------------------------------------------- +void ctkVTKOutputWindow::DisplayGenericWarningText(const char* text) +{ + this->DisplayWarningText(text); +} + +//---------------------------------------------------------------------------- +void ctkVTKOutputWindow::DisplayDebugText(const char* text) +{ + Q_ASSERT(this->MessageHandler); + this->MessageHandler->handleMessage( + ctk::qtHandleToString(QThread::currentThreadId()), + ctkErrorLogLevel::Debug, + this->MessageHandler->handlerPrettyName(), text); +} + +} // End of anonymous namespace + +// -------------------------------------------------------------------------- +// ctkVTKErrorLogMessageHandlerPrivate + +// -------------------------------------------------------------------------- +class ctkVTKErrorLogMessageHandlerPrivate +{ + Q_DECLARE_PUBLIC(ctkVTKErrorLogMessageHandler); +protected: + ctkVTKErrorLogMessageHandler* const q_ptr; +public: + ctkVTKErrorLogMessageHandlerPrivate(ctkVTKErrorLogMessageHandler& object); + ~ctkVTKErrorLogMessageHandlerPrivate(); + + vtkOutputWindow * SavedVTKOutputWindow; + ctkVTKOutputWindow * CTKVTKOutputWindow; + +}; + +// -------------------------------------------------------------------------- +// ctkVTKErrorLogMessageHandlerPrivate methods + +// -------------------------------------------------------------------------- +ctkVTKErrorLogMessageHandlerPrivate:: +ctkVTKErrorLogMessageHandlerPrivate(ctkVTKErrorLogMessageHandler& object) : q_ptr(&object) +{ + Q_Q(ctkVTKErrorLogMessageHandler); + this->SavedVTKOutputWindow = 0; + this->CTKVTKOutputWindow = ctkVTKOutputWindow::New(); + this->CTKVTKOutputWindow->MessageHandler = q; +} + +// -------------------------------------------------------------------------- +ctkVTKErrorLogMessageHandlerPrivate::~ctkVTKErrorLogMessageHandlerPrivate() +{ + if (this->SavedVTKOutputWindow) + { + this->SavedVTKOutputWindow->Delete(); + } + this->CTKVTKOutputWindow->Delete(); +} + +// -------------------------------------------------------------------------- +// ctkVTKErrorLogMessageHandler methods + +// -------------------------------------------------------------------------- +QString ctkVTKErrorLogMessageHandler::HandlerName = QLatin1String("VTK"); + +//---------------------------------------------------------------------------- +ctkVTKErrorLogMessageHandler::ctkVTKErrorLogMessageHandler() : + Superclass(), d_ptr(new ctkVTKErrorLogMessageHandlerPrivate(*this)) +{ +} + +//---------------------------------------------------------------------------- +ctkVTKErrorLogMessageHandler::~ctkVTKErrorLogMessageHandler() +{ +} + +//---------------------------------------------------------------------------- +QString ctkVTKErrorLogMessageHandler::handlerName()const +{ + return ctkVTKErrorLogMessageHandler::HandlerName; +} + +//---------------------------------------------------------------------------- +void ctkVTKErrorLogMessageHandler::setEnabledInternal(bool value) +{ + Q_D(ctkVTKErrorLogMessageHandler); + if (value) + { + d->SavedVTKOutputWindow = vtkOutputWindow::GetInstance(); + d->SavedVTKOutputWindow->Register(0); + vtkOutputWindow::SetInstance(d->CTKVTKOutputWindow); + } + else + { + Q_ASSERT(d->SavedVTKOutputWindow); + vtkOutputWindow::SetInstance(d->SavedVTKOutputWindow); + d->SavedVTKOutputWindow->Delete(); + d->SavedVTKOutputWindow = 0; + } +} + diff --git a/pool/shard007/C++/0091789_KoSimpleOdsSheet.cpp b/pool/shard007/C++/0091789_KoSimpleOdsSheet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7603d5cdbdf40c1c6183c858db54813436dc7f5e --- /dev/null +++ b/pool/shard007/C++/0091789_KoSimpleOdsSheet.cpp @@ -0,0 +1,64 @@ +/* + KoReport Library + Copyright (C) 2010 by Adam Pigg (adam@piggz.co.uk) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "KoSimpleOdsSheet.h" +#include <KoXmlWriter.h> +#include <kdebug.h> + +KoSimpleOdsSheet::KoSimpleOdsSheet() +{ + +} + +KoSimpleOdsSheet::~KoSimpleOdsSheet() +{ + +} + +void KoSimpleOdsSheet::addCell(long row, long col, KoSimpleOdsCell *cell) +{ + m_model.setItem(row, col, cell); +} + +void KoSimpleOdsSheet::setName(const QString& name) +{ + m_name = name; +} + +void KoSimpleOdsSheet::saveSheet(KoXmlWriter *writer) +{ + writer->startElement("table:table"); + writer->addAttribute("table:name", (m_name.isEmpty() ? "Sheet" : m_name )); + //Add table:style-name ? + + for (long r = 0; r < m_model.rowCount(); ++r) { + writer->startElement("table:table-row"); + for (long c = 0; c < m_model.columnCount(); ++c) { + KoSimpleOdsCell *cell = dynamic_cast<KoSimpleOdsCell*>(m_model.item(r,c)); + if (cell) { + cell->writeCellData(writer); + } else { + KoSimpleOdsCell::writeCellData(writer, QString()); + } + } + writer->endElement(); + } + writer->endElement(); +} diff --git a/pool/shard007/C++/0091791_cutielist_tests.cpp b/pool/shard007/C++/0091791_cutielist_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4d5f14a7bc7a6119a0b9cdc4bb61bbdc8b42f86a --- /dev/null +++ b/pool/shard007/C++/0091791_cutielist_tests.cpp @@ -0,0 +1,72 @@ +#include "contest.h" + +extern "C" +{ +#include "cutie.h" +} + +CONTEST_SUITE(cutie_suite_test) +CONTEST_CASE(test_parser) +{ + std::vector<std::string> programs; + programs.push_back("(define a 10)"); + programs.push_back("(set! a 10)"); + programs.push_back("(1 ' set! 10) 10)"); + programs.push_back("(define a \"test\")"); + programs.push_back("(define a \"\")"); + programs.push_back("(define a \"test \\\" test\")"); + + for (std::string ps : programs) { + const char *p = ps.c_str(); + Error err; + Atom sexpr; + err = read_expr((const char*)p, (const char**)&p, &sexpr); + CONTEST_TRUE(!ERROR_RAISED(err)); + } +} + +CONTEST_CASE(test_parser_input) +{ + std::vector<std::string> programs; + programs.push_back(")£$(1 ' set! 10) 10)"); + + for (std::string ps : programs) { + const char *p = ps.c_str(); + Atom sexpr; + Error err = read_expr((const char*)p, (const char**)&p, &sexpr); + CONTEST_TRUE(ERROR_RAISED(err)); + } +} + +namespace { +Error builtin_square(Atom args, Atom *result) +{ + if (nilp(args)) + return ERROR(Error::Error_Args, "Requires one arguments."); + + Atom a = car(args); + if (a.type != AtomType::ATOM_INTEGER) + return ERROR(Error::Error_Args, "Argument must be integer"); + + *result = make_integer(a.value.integer * a.value.integer); + return ERROR_OK(); +} +} + +CONTEST_CASE(make_new_builtin) +{ + Atom env = setup_env(); + env_set(env, make_symbol("TEST-FUNC"), make_builtin(builtin_square)); + + Atom sexpr, result; + + const char *p = "(test-func 12)"; + Error err = read_expr(p, &p, &sexpr); + CONTEST_TRUE(!ERROR_RAISED(err)); + + err = eval_expr(sexpr, env, &result); + CONTEST_TRUE(!ERROR_RAISED(err)); + CONTEST_EQUAL(result.value.integer, (long)144); +} + +CONTEST_SUITE_END diff --git a/pool/shard007/C++/0091797_digit_dp.cpp b/pool/shard007/C++/0091797_digit_dp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8dd8a21f312f632ea896c8d799a878b4d26e8006 --- /dev/null +++ b/pool/shard007/C++/0091797_digit_dp.cpp @@ -0,0 +1,101 @@ +/* Part of Cosmos by OpenGenus Foundation + * By: Sibasish Ghosh (https://github.com/sibasish14) + */ + +/* How many numbers x are there in the range a to b? + * where the digit d occurs exactly k times in x? + */ + +#include <iostream> +#include <vector> +#include <string.h> + +using namespace std; + +long d = 3; +long k = 5; + +long dp[25][25][2]; +/* dp[pos][count][f] = Number of valid numbers <= b from this state + * pos = current position from left side (zero based) + * count = number of times we have placed the digit d so far + * f = the number we are building has already become smaller than b? [0 = no, 1 = yes] + */ + +long digit_dp(string num, long pos, long count, long f) +{ + if (count > k) + return 0; + + if (pos == num.size()) + { + if (count == k) + return 1; + return 0; + } + + if (dp[pos][count][f] != -1) + return dp[pos][count][f]; + + long result = 0; + long limit; + + if (f == 0) + /* Digits we placed so far matches with the prefix of b + * So if we place any digit > num[pos] in the current position, then + * the number will become greater than b + */ + limit = num[pos] - '0'; + else + /* The number has already become smaller than b. + * We can place any digit now. + */ + limit = 9; + + // Try to place all the valid digits such that the number doesn't exceed b + for (long dgt = 0; dgt <= limit; dgt++) + { + long fNext = f; + long countNext = count; + + // The number is getting smaller at this position + if (f == 0 && dgt < limit) + fNext = 1; + + if (dgt == d) + countNext++; + + if (countNext <= k) + result += digit_dp(num, pos + 1, countNext, fNext); + } + + return dp[pos][count][f] = result; +} + +long solve(string num) +{ + memset(dp, -1, sizeof(dp)); + long result = digit_dp(num, 0, 0, 0); + return result; +} + +bool check(string num) +{ + long count = 0; + for (long i = 0; i < num.size(); i++) + if (num[i] - '0' == d) + count++; + + if (count == k) + return true; + else + return false; +} + +int main() +{ + string a = "100", b = "100000000"; + long ans = solve(b) - solve(a) + check(a); + cout << ans << "\n"; + return 0; +} diff --git a/pool/shard007/C++/0091806_vtk_abstract_grid_builder.cc b/pool/shard007/C++/0091806_vtk_abstract_grid_builder.cc new file mode 100644 index 0000000000000000000000000000000000000000..8c2c3cf72ca8d10dfd221a9076adddd114cf4afd --- /dev/null +++ b/pool/shard007/C++/0091806_vtk_abstract_grid_builder.cc @@ -0,0 +1,409 @@ + +// +// Copyright (c) 2014 Limit Point Systems, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// Implementation for class vtk_abstract_grid_builder + +#include "SheafSystem/vtk_abstract_grid_builder.h" +#include "SheafSystem/assert_contract.h" +#include "SheafSystem/base_space_member.h" +#include "SheafSystem/eval_iterator.h" +#include "SheafSystem/namespace_poset.h" + +#include "vtkUnstructuredGrid.h" +#include "vtkUnstructuredGridWriter.h" +#include "vtkDoubleArray.h" +#include "vtkFieldData.h" +#include "vtkIdTypeArray.h" +#include "vtkIntArray.h" +#include "vtkPoints.h" +#include "vtkCellArray.h" +#include "vtkPointData.h" +#include "vtkCellData.h" + +//#unfine DIAGNOSTIC_OUTPUT +// #define DIAGNOSTIC_OUTPUT + +// Workaround for MS Visual C++ +using namespace tool; +using namespace std; + +// ============================================================================ +// ANY FACET +// ============================================================================ + +/// +bool +tool::vtk_abstract_grid_builder:: +is_ancestor_of(const any* other) const +{ + + // Preconditions: + + require(other != 0); + + // Body: + + // True if other conforms to this + + bool result = dynamic_cast<const vtk_abstract_grid_builder*>(other) != 0; + + // Postconditions: + + return result; +} + + + +/// +tool::vtk_abstract_grid_builder* +tool::vtk_abstract_grid_builder:: +clone() const +{ + vtk_abstract_grid_builder* result = 0; // Just to silence compiler warnings. + + // Preconditions: + + // Body: + + is_abstract(); + + // Postconditions: + + // Exit: + + return result; +} + + +/// +tool::vtk_abstract_grid_builder& +tool::vtk_abstract_grid_builder:: +operator=(const vtk_abstract_grid_builder& xother) +{ + + // Preconditions: + + + // Body: + + is_abstract(); + + // Postconditions: + + ensure(invariant()); + + // Exit + + return *this; +} + +/// +bool +tool::vtk_abstract_grid_builder:: +invariant() const +{ + bool result = true; + + if(invariant_check()) + { + // Prevent recursive calls to invariant + + disable_invariant_check(); + + // Must satisfy base class invariant + + invariance(any::invariant()); + + // Invariances for this class: + + // Finished, turn invariant checking back on. + + enable_invariant_check(); + } + + // Exit + + return result; +} + + + +// ============================================================================ +// VTK_DATA_SET_BUILDER FACET +// ============================================================================ + +/// +tool::vtk_abstract_grid_builder:: +~vtk_abstract_grid_builder() +{ + + // Preconditions: + + + // Body: + + // Nothing to do. + + // Postconditions: + + // Exit: + + return; +} + +/// +void +tool::vtk_abstract_grid_builder:: +set_name_space(namespace_poset& xns) +{ + // Preconditions: + + // Body: + + is_abstract(); + + // Postconditions: + + // Exit: + + return; +} + +/// +vtkUnstructuredGrid* +tool::vtk_abstract_grid_builder:: +build(const sec_vd& xcoords, const sec_vd& xproperty) +{ + vtkUnstructuredGrid* result; + + // Preconditions: + + require(xcoords.state_is_read_accessible()); + require(xcoords.schema().base_space().schema().conforms_to(base_space_member::standard_schema_path())); + require(xcoords.schema().df() <= 3); + require(xproperty.state_is_read_accessible()); + require(xproperty.schema().base_space().is_same_state(&xcoords.schema().base_space())); + require(xproperty.schema().evaluation().is_same_state(&xcoords.schema().evaluation())); + + // Body: + + result = vtkUnstructuredGrid::New(); + + build_pa(xcoords, xproperty, *result); + + // Postconditions: + + + // Exit: + + return result; +} + +/// +vtkUnstructuredGrid* +tool::vtk_abstract_grid_builder:: +build(const sec_vd& xcoords, const sec_vd& xproperty1, const sec_vd& xproperty2) +{ + vtkUnstructuredGrid* result; + + // Preconditions: + + require(xcoords.state_is_read_accessible()); + require(xcoords.schema().base_space().schema().conforms_to(base_space_member::standard_schema_path())); + require(xcoords.schema().df() <= 3); + require(xproperty1.state_is_read_accessible()); + require(xproperty1.schema().base_space().is_same_state(&xcoords.schema().base_space())); + require(xproperty1.schema().evaluation().is_same_state(&xcoords.schema().evaluation())); + require(xproperty2.state_is_read_accessible()); + require(xproperty2.schema().base_space().is_same_state(&xcoords.schema().base_space())); + require(xproperty2.schema().evaluation().is_same_state(&xcoords.schema().evaluation())); + + // Body: + + result = vtkUnstructuredGrid::New(); + + build_pa(xcoords, xproperty1, xproperty2, *result); + + // Postconditions: + + + // Exit: + + return result; +} + +/// +vtkUnstructuredGrid* +tool::vtk_abstract_grid_builder:: +build(const sec_vd& xcoords) +{ + vtkUnstructuredGrid* result; + + // Preconditions: + + require(xcoords.state_is_read_accessible()); + require(xcoords.schema().base_space().schema().conforms_to(base_space_member::standard_schema_path())); + require(xcoords.schema().df() <= 3); + + // Body: + + result = vtkUnstructuredGrid::New(); + + build_pa(xcoords, *result); + + // Postconditions: + + + // Exit: + + return result; +} + +/// +void +tool::vtk_abstract_grid_builder:: +build_pa(const sec_vd& xcoords, const sec_vd& xproperty, vtkUnstructuredGrid& xresult) +{ + // Preconditions: + + // Body: + + is_abstract(); + + // Postconditions: + + + // Exit: + + return; +} + +/// +void +tool::vtk_abstract_grid_builder:: +build_pa(const sec_vd& xcoords, const sec_vd& xproperty1, + const sec_vd& xproperty2, vtkUnstructuredGrid& xresult) +{ + // Preconditions: + + // Body: + + is_abstract(); + + // Postconditions: + + + // Exit: + + return; +} + +/// +void +tool::vtk_abstract_grid_builder:: +build_pa(const sec_vd& xcoords, vtkUnstructuredGrid& xresult) +{ + // Preconditions: + + // Body: + + is_abstract(); + + // Postconditions: + + + // Exit: + + return; +} + +bool +tool::vtk_abstract_grid_builder:: +use_point_top_ids() const +{ + return _use_point_top_ids; +} + +void +tool::vtk_abstract_grid_builder:: +put_use_point_top_ids(bool xvalue) +{ + _use_point_top_ids = xvalue; + + ensure(use_point_top_ids() == xvalue); + + return; +} + +bool +tool::vtk_abstract_grid_builder:: +use_cell_top_ids() const +{ + return _use_cell_top_ids; +} + +void +tool::vtk_abstract_grid_builder:: +put_use_cell_top_ids(bool xvalue) +{ + _use_cell_top_ids = xvalue; + + ensure(use_cell_top_ids() == xvalue); + + return; +} + +vtkIdTypeArray* +tool::vtk_abstract_grid_builder:: +vtk_pt_label_ids() const +{ + return _vtk_pt_label_ids; +} + +vtkIdTypeArray* +tool::vtk_abstract_grid_builder:: +vtk_cell_label_ids() const +{ + return _vtk_cell_label_ids; +} + +tool::vtk_abstract_grid_builder:: +vtk_abstract_grid_builder() +{ + // Preconditions: + + + // Body: + + _vtk_pt_label_ids = 0; + _vtk_cell_label_ids = 0; + + _use_point_top_ids = true; + _use_cell_top_ids = true; + + // Postconditions: + + + // Exit: + + return; +} + +// ============================================================================ +// NON-MEMBER FUNCTIONS +// ============================================================================ + diff --git a/pool/shard007/C++/0091808_kws_rate_filter.cc b/pool/shard007/C++/0091808_kws_rate_filter.cc new file mode 100644 index 0000000000000000000000000000000000000000..cbb9e55cae35f505f7e8ae9eaf95686b118124b5 --- /dev/null +++ b/pool/shard007/C++/0091808_kws_rate_filter.cc @@ -0,0 +1,148 @@ +//-------------------------------------------------------------------------- +// Copyright (C) 2014-2015 Cisco and/or its affiliates. All rights reserved. +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License Version 2 as published +// by the Free Software Foundation. You may not use, modify or distribute +// this program under any other version of the GNU General Public License. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +//-------------------------------------------------------------------------- +// kws_rate_filter.cc author Josh Rosenbaum <jrosenba@cisco.com> + +#include <sstream> +#include <vector> + +#include "conversion_state.h" +#include "helpers/converter.h" +#include "helpers/s2l_util.h" + +namespace keywords +{ +namespace +{ +class RateFilter : public ConversionState +{ +public: + RateFilter(Converter& c) : ConversionState(c) { } + virtual ~RateFilter() { } + virtual bool convert(std::istringstream& data); + +private: + void fix_separators(std::istringstream& stream); +}; +} // namespace + +void RateFilter::fix_separators(std::istringstream& stream) +{ + const std::streamoff pos = stream.tellg(); + std::size_t curr = pos; + std::string s = stream.str(); + int cnt = 0; + + while ( (curr = s.find_first_of("[],", curr)) != std::string::npos ) + { + switch (s[curr]) + { + case '[': + cnt++; + break; + case ']': + cnt--; + break; + case ',': + if (cnt == 0) + s[curr] = ';'; + break; + } + ++curr; + } + + stream.str(s); + stream.clear(); + stream.seekg(pos); +} + +bool RateFilter::convert(std::istringstream& data_stream) +{ + bool retval = true; + std::string args; + + table_api.open_table("rate_filter"); + fix_separators(data_stream); + + while (std::getline(data_stream, args, ';')) + { + std::string keyword; + std::istringstream arg_stream(args); + bool tmpval = true; + + arg_stream >> keyword; + + if (keyword.empty()) + continue; + + else if (!keyword.compare("track")) + tmpval = parse_string_option("track", arg_stream); + + else if (!keyword.compare("count")) + tmpval = parse_int_option("count", arg_stream, false); + + else if (!keyword.compare("seconds")) + tmpval = parse_int_option("seconds", arg_stream, false); + + else if (!keyword.compare("timeout")) + tmpval = parse_int_option("timeout", arg_stream, false); + + else if (!keyword.compare("new_action")) + tmpval = parse_string_option("new_action", arg_stream); + + else if (!keyword.compare("apply_to")) + { + std::getline(arg_stream, keyword); + util::trim(keyword); + table_api.add_option("apply_to", keyword); + } + else if (!keyword.compare("gen_id")) + { + table_api.add_diff_option_comment("gen_id", "gid"); + tmpval = parse_int_option("gid", arg_stream, false); + } + else if (!keyword.compare("sig_id")) + { + table_api.add_diff_option_comment("sig_id", "sid"); + tmpval = parse_int_option("sid", arg_stream, false); + } + else + tmpval = false; + + if (retval) + retval = tmpval; + } + + return retval; +} + +/************************** + ******* A P I *********** + **************************/ + +static ConversionState* ctor(Converter& c) +{ return new RateFilter(c); } + +static const ConvertMap keyword_rate_filter = +{ + "rate_filter", + ctor, +}; + +const ConvertMap* rate_filter_map = &keyword_rate_filter; +} // namespace keywords + diff --git a/pool/shard007/C++/0091809_Theme.cpp b/pool/shard007/C++/0091809_Theme.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fc5194ee24c5b01bb54d07f02d77ca2bbe50b847 --- /dev/null +++ b/pool/shard007/C++/0091809_Theme.cpp @@ -0,0 +1,117 @@ +#include "Common.hpp" + +#include "resource/Geometry.hpp" +#include "resource/Texture.hpp" + +#include "resource/Entity.hpp" +#include "resource/Font.hpp" +#include "resource/Keyframe.hpp" + +#include "input/Mouse.hpp" + +#include "widget/Widget.hpp" +#include "widget/Frame.hpp" +#include "widget/Div.hpp" + +#include "widget/Button.hpp" +#include "widget/Canvas.hpp" +#include "widget/Caption.hpp" +#include "widget/CheckBox.hpp" +#include "widget/TextBox.hpp" +#include "widget/Icon.hpp" +#include "widget/KeyBox.hpp" +#include "widget/LogBox.hpp" +#include "widget/ScrollBar.hpp" +#include "widget/TabBox.hpp" +#include "widget/Pulldown.hpp" +#include "widget/Slider.hpp" +#include "widget/Thumb.hpp" +#include "widget/Wiring.hpp" + +#include "widget/Window.hpp" +#include "widget/Cursor.hpp" + +#include "Theme.hpp" + +using namespace reprize; +using namespace std; +using namespace inf; +using namespace res; + +Theme::Theme(const Str& name_, const Material* bg_, const Font* fn_, + const Font* mi_fn_, const res::Sound* pressed_snd_, + const res::Sound* released_snd_, const res::Sound* dragging_snd_) + : Node(name_), fallback(NULL), bg(bg_), fn(fn_), mi_fn(mi_fn_), + pressed_snd(pressed_snd_), released_snd(released_snd_), + dragging_snd(dragging_snd_) +{ + /* TODO */ + fallback = new Widget("Fallback", bg, fn, Vec3(4, 4)); + if (bg && fn) { /* TODO */ } + else { /* TODO */ } + Add(fallback); + + Add(new Button("Button", bg, fn, Vec3(4, 4))); + Add(new Canvas("Canvas", bg, fn, Vec3(4, 4))); + Add(new CheckBox("CheckBox", bg, fn, Vec3(4, 4))); + Add(new Cursor("Cursor", bg, fn, Vec3())); + Add(new Div("Div", NULL, fn_, Vec3())); + Add(new TextBox("TextBox", bg, fn, Vec3(4, 4))); + Add(new KeyBox("KeyBox", bg, fn, Vec3(4, 4))); + Add(new LogBox("LogBox", bg, fn, Vec3(4, 4))); + Add(new Frame("Frame", bg, fn, Vec3(6, 6))); + Add(new ScrollBar("ScrollBar", bg, fn, Vec3(6, 6))); + Add(new Slider("Slider", bg, mi_fn_, Vec3(4, 4))); + TabBox* tabbox = new TabBox("TabBox", bg, fn, Vec3(4, 4)); + Add(tabbox); + Thumb* thumb = new Thumb("Thumb", bg, fn, Vec3(4, 4)); + Add(thumb); + tabbox->set_tab(thumb); + Add(new Pulldown("Pulldown", bg, fn, Vec3(4, 4))); + Add(new Caption("Caption")); + Add(new Window("Window", bg, fn, Vec3(4, 4))); + + if (pressed_snd != NULL) + { RE_DBG("press snd: %s", pressed_snd->get_name().c_str()); } + if (released_snd != NULL) + { RE_DBG("release snd: %s", released_snd->get_name().c_str()); } + if (dragging_snd != NULL) + { RE_DBG("drag snd: %s", dragging_snd->get_name().c_str()); } +} + +Theme::Theme(const Theme& src_) + : Node(src_.name), fallback(NULL), bg(src_.bg), fn(src_.fn), + mi_fn(src_.mi_fn), + pressed_snd(src_.pressed_snd), released_snd(src_.released_snd), + dragging_snd(src_.dragging_snd) +{ + /* TODO */ + fallback = new Widget("Fallback", bg, fn, Vec3(4, 4)); + if (bg && fn) { /* TODO */ } + else { /* TODO */ } + Add(fallback); +} + +Theme::~Theme(void) +{ +} + +Theme* Theme::Clone(const bool with_child_) +{ + return new Theme(*this); +} + +const Sound* Theme::get_pressed_snd(void) +{ + return pressed_snd; +} + +const Sound* Theme::get_released_snd(void) +{ + return released_snd; +} + +const Sound* Theme::get_dragging_snd(void) +{ + return dragging_snd; +} diff --git a/pool/shard007/C++/0091810_CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_memcpy_84_bad.cpp b/pool/shard007/C++/0091810_CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_memcpy_84_bad.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62f9b901c9e18614d0348ceff0d6ec6240df6ff1 --- /dev/null +++ b/pool/shard007/C++/0091810_CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_memcpy_84_bad.cpp @@ -0,0 +1,45 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_memcpy_84_bad.cpp +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.string.label.xml +Template File: sources-sink-84_bad.tmpl.cpp +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Allocate using new[] and set data pointer to a small buffer + * GoodSource: Allocate using new[] and set data pointer to a large buffer + * Sinks: memcpy + * BadSink : Copy string to data using memcpy + * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use + * + * */ +#ifndef OMITBAD + +#include "std_testcase.h" +#include "CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_memcpy_84.h" + +namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_memcpy_84 +{ +CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_memcpy_84_bad::CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_memcpy_84_bad(wchar_t * dataCopy) +{ + data = dataCopy; + /* FLAW: Allocate using new[] and point data to a small buffer that is smaller than the large buffer used in the sinks */ + data = new wchar_t[50]; + data[0] = L'\0'; /* null terminate */ +} + +CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_memcpy_84_bad::~CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_memcpy_84_bad() +{ + { + wchar_t source[100]; + wmemset(source, L'C', 100-1); /* fill with L'C's */ + source[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ + memcpy(data, source, 100*sizeof(wchar_t)); + data[100-1] = L'\0'; /* Ensure the destination buffer is null terminated */ + printWLine(data); + delete [] data; + } +} +} +#endif /* OMITBAD */ diff --git a/pool/shard007/C++/0091811_CharacterCreatorConsoleUI.cpp b/pool/shard007/C++/0091811_CharacterCreatorConsoleUI.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1ef38518c2b281b77c11ecbb1f9a150d4c5b0c5e --- /dev/null +++ b/pool/shard007/C++/0091811_CharacterCreatorConsoleUI.cpp @@ -0,0 +1,159 @@ +#include "CharacterCreatorConsoleUI.h" + +#include <iostream> + +namespace rpcc +{ + CharacterCreatorConsoleUI::CharacterCreatorConsoleUI() + : CharacterCreatorBaseUI() + {} + + CharacterCreatorConsoleUI::~CharacterCreatorConsoleUI() + {} + + void CharacterCreatorConsoleUI::selectRace(Character* ch) + { + std::cout << "Races disponibles: \n"; + std::vector<Race*> raceVector = DataManager::getRaceVector(); + for(unsigned int i=0; i<raceVector.size(); i++) + { + std::cout << "\t[" << i << "]: " << raceVector.at(i)->getName() << "\n"; + } + + std::cout << "Sélectionnez la race: "; + unsigned int ind; + std::cin >> ind; + + while(0>ind || ind>=raceVector.size()) + { + std::cout << "Erreur, le numéro " << ind << " n'est pas une entrée valide.\n"; + std::cout << "Sélectionnez la race: "; + std::cin >> ind; + } + + std::cout << "Vous avez choisi la race " << raceVector.at(ind)->getName() << ".\n"; + ch->setRace(raceVector.at(ind)); + } + + void CharacterCreatorConsoleUI::selectGender(Character* ch) + { + std::cout << "Sexes disponibles: \n"; + for(unsigned int i=0; i<(unsigned int)Gender::GENDER_SIZE; i++) + { + std::cout << "\t[" << i << "]: " << GENDER_NAME[i] << "\n"; + } + + std::cout << "Sélectionnez le sexe: "; + unsigned int ind; + std::cin >> ind; + + while(0>ind || ind>=(unsigned int)Gender::GENDER_SIZE) + { + std::cout << "Erreur, le numéro " << ind << " n'est pas une entrée valide.\n"; + std::cout << "Sélectionnez le sexe: "; + std::cin >> ind; + } + + std::cout << "Vous avez choisi le sexe " << GENDER_NAME[ind] << ".\n"; + ch->setGender((Gender)ind); + } + + void CharacterCreatorConsoleUI::selectClass(Character* ch) + { + std::cout << "Classes disponibles: \n"; + std::vector<std::string> classIDVector = ch->getAvailableClass(); + std::vector<Class*> classVector; + for(unsigned int i=0; i<classIDVector.size(); i++) + { + classVector.push_back(DataManager::getClassByKey(classIDVector.at(i))); + std::cout << "\t[" << i << "]: " << classVector.at(i)->getName() << "\n"; + } + + std::cout << "Sélectionnez la classe: "; + unsigned int ind; + std::cin >> ind; + + while(0>ind || ind>=classVector.size()) + { + ind = -1; + std::cout << "Erreur, le numéro " << ind << " n'est pas une entrée valide.\n"; + std::cout << "Sélectionnez la classe: "; + std::cin >> ind; + } + + std::cout << "Vous avez choisi la classe " << classVector.at(ind)->getName() << ".\n"; + ch->setClass(classVector.at(ind)); + } + + void CharacterCreatorConsoleUI::selectName(Character* ch) + { + std::cout << "Entrez le nom: "; + std::string name; + std::cin >> name; + + std::cout << "Vous avez choisi le nom " << name << ".\n"; + ch->setName(name); + } + + void CharacterCreatorConsoleUI::setAttributesScore(Character* ch) + { + AttributeSet* ass = ch->getAttributesSet(); + + while(1) + { + std::cout << ass->toStringCreation(); + + std::cout << "\nEntrez: "; + std::string command; + std::cin >> command; + + if("q" == command) + break; + + if(command.size()!=4) + continue; + + std::string key = command.substr(1,3); + + if('-'==command.at(0)) + { + if(ass->isDecrementable(key)) + ass->decrementByID(key); + } + else if('+'==command.at(0)) + if(ass->isIncrementable(key)) + ass->incrementByID(key); + } + } + + void CharacterCreatorConsoleUI::setWeaponProficiency(Character* ch) + { + WeaponProficiencySet* wps = ch->getWeaponProficiencySet(); + + while(1) + { + std::cout << wps->toStringCreation(); + + std::cout << "\nEntrez: "; + std::string command; + std::cin >> command; + + if("q" == command) + break; + + if(command.size()<2) + continue; + + std::string key = command.substr(1,command.size()-1); + + if('-'==command.at(0)) + { + if(wps->isDecrementable(key)) + wps->decrementByID(key); + } + else if('+'==command.at(0)) + if(wps->isIncrementable(key)) + wps->incrementByID(key); + } + } +} diff --git a/pool/shard007/C++/0091812_ShortestPalindrome.cpp b/pool/shard007/C++/0091812_ShortestPalindrome.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9da12112576175cfe839b366832e8e6d6902e979 --- /dev/null +++ b/pool/shard007/C++/0091812_ShortestPalindrome.cpp @@ -0,0 +1,29 @@ +#include "ShortestPalindrome.hpp" + +#include <vector> +#include <algorithm> + +using namespace std; + +string ShortestPalindrome::shortestPalindrome(string s) { + if (s.size() <= 1) + return s; + + string reverse_str = s; + reverse(reverse_str.begin(), reverse_str.end()); + string new_str = s + "#" + reverse_str; + vector<int> position(new_str.size(), 0); + + for (int i = 1; i < position.size(); i++) { + int pre_pos = position[i - 1]; + + while (pre_pos > 0 && new_str[pre_pos] != new_str[i]) + pre_pos = position[pre_pos - 1]; + + position[i] = pre_pos + ((new_str[pre_pos] == new_str[i]) ? 1 : 0); + } + + string tail = s.substr(position[position.size() - 1]); + reverse(tail.begin(), tail.end()); + return tail + s; +} diff --git a/pool/shard007/C++/0091815_HttpRequestBuilder.cpp b/pool/shard007/C++/0091815_HttpRequestBuilder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..03cc745feca4a466e8a525d620d3d86b660dc54d --- /dev/null +++ b/pool/shard007/C++/0091815_HttpRequestBuilder.cpp @@ -0,0 +1,144 @@ +/* + * #%L + * %% + * Copyright (C) 2011 - 2017 BMW Car IT GmbH + * %% + * 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. + * #L% + */ +#include "libjoynrclustercontroller/httpnetworking/HttpRequestBuilder.h" +#include "joynr/exceptions/JoynrException.h" +#include "libjoynrclustercontroller/httpnetworking/DefaultHttpRequest.h" + +#include <curl/curl.h> + +namespace joynr +{ + +INIT_LOGGER(HttpRequestBuilder); + +HttpRequestBuilder::HttpRequestBuilder(const std::string& url) + : handle(nullptr), headers(nullptr), content(), built(false) +{ + handle = HttpNetworking::getInstance()->getCurlHandlePool()->getHandle(url); + curl_easy_setopt(handle, CURLOPT_URL, url.c_str()); +} + +HttpRequestBuilder::~HttpRequestBuilder() +{ + if (!built) { + if (headers != nullptr) { + curl_slist_free_all(headers); + } + HttpNetworking::getInstance()->getCurlHandlePool()->returnHandle(handle); + } +} + +HttpRequestBuilder* HttpRequestBuilder::withProxy(const std::string& proxy) +{ + curl_easy_setopt(handle, CURLOPT_PROXY, proxy.c_str()); + return this; +} + +HttpRequestBuilder* HttpRequestBuilder::withCertificateAuthority(const std::string& caFile) +{ + curl_easy_setopt(handle, CURLOPT_CAINFO, caFile.c_str()); + return this; +} + +HttpRequestBuilder* HttpRequestBuilder::withClientCertificate(const std::string& certificateFile) +{ + curl_easy_setopt(handle, CURLOPT_SSLCERT, certificateFile.c_str()); + return this; +} + +HttpRequestBuilder* HttpRequestBuilder::withClientCertificatePassword(const std::string& password) +{ + curl_easy_setopt(handle, CURLOPT_KEYPASSWD, password.c_str()); + return this; +} + +HttpRequestBuilder* HttpRequestBuilder::withDebug() +{ + curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L); + return this; +} + +HttpRequestBuilder* HttpRequestBuilder::postContent(const std::string& data) +{ + content = data; + return this; +} + +HttpRequestBuilder* HttpRequestBuilder::asPost() +{ + curl_easy_setopt(handle, CURLOPT_POST, 1); + curl_easy_setopt(handle, CURLOPT_POSTFIELDSIZE, 0); + + // Workaround for server behaviour described here: + // http://curl.haxx.se/mail/lib-2011-12/0348.html + addHeader("Expect", ""); + return this; +} + +HttpRequestBuilder* HttpRequestBuilder::asDelete() +{ + curl_easy_setopt(handle, CURLOPT_CUSTOMREQUEST, "DELETE"); + return this; +} + +HttpRequestBuilder* HttpRequestBuilder::withTimeout(std::chrono::milliseconds timeout) +{ + curl_easy_setopt(handle, CURLOPT_TIMEOUT_MS, timeout.count()); + return this; +} + +HttpRequestBuilder* HttpRequestBuilder::withConnectTimeout(std::chrono::milliseconds timeout) +{ + curl_easy_setopt(handle, CURLOPT_CONNECTTIMEOUT_MS, timeout.count()); + return this; +} + +HttpRequestBuilder* HttpRequestBuilder::acceptGzip() +{ + curl_easy_setopt(handle, CURLOPT_ACCEPT_ENCODING, "gzip"); + return this; +} + +HttpRequestBuilder* HttpRequestBuilder::withContentType(const std::string& contentType) +{ + addHeader("Content-Type", contentType); + return this; +} + +HttpRequestBuilder* HttpRequestBuilder::addHeader(const std::string& name, const std::string& value) +{ + std::string header(name + ": " + value); + headers = curl_slist_append(headers, header.c_str()); + return this; +} + +HttpRequest* HttpRequestBuilder::build() +{ + if (built) { + JOYNR_LOG_WARN(logger, + "The method build of HttpBuilder may be called only once on a specific " + "instance. Throwing an Exception from worker thread."); + throw exceptions::JoynrRuntimeException( + "The method build of HttpBuilder may be called only once on a specific instance"); + } + built = true; + return new DefaultHttpRequest(handle, content, headers); +} + +} // namespace joynr diff --git a/pool/shard007/C++/0091821_TestReceiverReport.cpp b/pool/shard007/C++/0091821_TestReceiverReport.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eac415f1d1c66aa963845a69cdb6f6989fb1d949 --- /dev/null +++ b/pool/shard007/C++/0091821_TestReceiverReport.cpp @@ -0,0 +1,110 @@ +#include "common.hpp" +#include "RTC/RTCP/ReceiverReport.hpp" +#include "RTC/RTCP/SenderReport.hpp" // sizeof(SenderReport::Header) +#include <catch2/catch.hpp> + +using namespace RTC::RTCP; + +namespace TestReceiverReport +{ + // RTCP Receiver Report Packet. + + // clang-format off + uint8_t buffer[] = + { + 0x81, 0xc9, 0x00, 0x07, // Type: 201 (Receiver Report), Count: 1, Length: 7 + 0x5d, 0x93, 0x15, 0x34, // Sender SSRC: 0x5d931534 + // Receiver Report + 0x01, 0x93, 0x2d, 0xb4, // SSRC. 0x01932db4 + 0x00, 0x00, 0x00, 0x01, // Fraction lost: 0, Total lost: 1 + 0x00, 0x00, 0x00, 0x00, // Extended highest sequence number: 0 + 0x00, 0x00, 0x00, 0x00, // Jitter: 0 + 0x00, 0x00, 0x00, 0x00, // Last SR: 0 + 0x00, 0x00, 0x00, 0x05 // DLSR: 0 + }; + // clang-format on + + // Receiver Report buffer start point. + uint8_t* rrBuffer = buffer + Packet::CommonHeaderSize + sizeof(uint32_t) /*Sender SSRC*/; + + uint32_t ssrc{ 0x01932db4 }; + uint8_t fractionLost{ 0 }; + uint8_t totalLost{ 1 }; + uint32_t lastSeq{ 0 }; + uint32_t jitter{ 0 }; + uint32_t lastSenderReport{ 0 }; + uint32_t delaySinceLastSenderReport{ 5 }; + + void verify(ReceiverReport* report) + { + REQUIRE(report->GetSsrc() == ssrc); + REQUIRE(report->GetFractionLost() == fractionLost); + REQUIRE(report->GetTotalLost() == totalLost); + REQUIRE(report->GetLastSeq() == lastSeq); + REQUIRE(report->GetJitter() == jitter); + REQUIRE(report->GetLastSenderReport() == lastSenderReport); + REQUIRE(report->GetDelaySinceLastSenderReport() == delaySinceLastSenderReport); + } +} // namespace TestReceiverReport + +using namespace TestReceiverReport; + +SCENARIO("RTCP RR parsing", "[parser][rtcp][rr]") +{ + SECTION("parse RR packet") + { + ReceiverReportPacket* packet = ReceiverReportPacket::Parse(buffer, sizeof(buffer)); + + auto* report = *(packet->Begin()); + + verify(report); + + SECTION("serialize packet instance") + { + uint8_t serialized[sizeof(buffer)] = { 0 }; + + packet->Serialize(serialized); + + SECTION("compare serialized packet with original buffer") + { + REQUIRE(std::memcmp(buffer, serialized, sizeof(buffer)) == 0); + } + } + + delete packet; + } + + SECTION("parse RR") + { + ReceiverReport* report = ReceiverReport::Parse(rrBuffer, ReceiverReport::HeaderSize); + + REQUIRE(report); + + verify(report); + + delete report; + } + + SECTION("create RR") + { + // Create local report and check content. + ReceiverReport report1; + + report1.SetSsrc(ssrc); + report1.SetFractionLost(fractionLost); + report1.SetTotalLost(totalLost); + report1.SetLastSeq(lastSeq); + report1.SetJitter(jitter); + report1.SetLastSenderReport(lastSenderReport); + report1.SetDelaySinceLastSenderReport(delaySinceLastSenderReport); + + verify(&report1); + + SECTION("create a report out of the existing one") + { + ReceiverReport report2(&report1); + + verify(&report2); + } + } +} diff --git a/pool/shard007/C++/0091822_aboutqemailscrapper.cpp b/pool/shard007/C++/0091822_aboutqemailscrapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b5b3e6411471947473bf644263a4209613cf794a --- /dev/null +++ b/pool/shard007/C++/0091822_aboutqemailscrapper.cpp @@ -0,0 +1,52 @@ +/* + * aboutqemailscrapper.cpp + * QEmailScrapper: Utility for scrapping a file in search of emails + * Copyright (C) 2012 Daniel Ripoll <info@danielripoll.es> + * http://danielripoll.es + * + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +#include "aboutqemailscrapper.h" +#include "ui_aboutqemailscrapper.h" + + +AboutQEmailScrapper::AboutQEmailScrapper(QWidget *parent) : + QDialog(parent), + ui(new Ui::AboutQEmailScrapper) +{ + ui->setupUi(this); + ui->mui_texbrowser->viewport()->setAutoFillBackground(false); + ui->mui_texbrowser->setFrameShape(QTextBrowser::NoFrame); + ui->mui_texbrowser->setFrameShadow(QTextBrowser::Plain); + ui->mui_logo->viewport()->setAutoFillBackground(false); + ui->mui_logo->setFrameShape(QTextBrowser::NoFrame); + ui->mui_logo->setFrameShadow(QTextBrowser::Plain); + + QString qtversion_string = ui->mui_version->text(); + qtversion_string.replace("__QTVERSION__",QT_VERSION_STR); + qtversion_string.replace("__ARCH__",mlGetArch()); + ui->mui_version->setText(qtversion_string); + + QString version_string = ui->mui_title->text(); + version_string.replace("__VERSION__",mlGetVersion()); + ui->mui_title->setText(version_string); +} + +AboutQEmailScrapper::~AboutQEmailScrapper() +{ + delete ui; +} diff --git a/pool/shard007/C++/0091826_devtools_window.cc b/pool/shard007/C++/0091826_devtools_window.cc new file mode 100644 index 0000000000000000000000000000000000000000..9c5705ce68f4da5c1ea5ed8930ddab14f1f4c075 --- /dev/null +++ b/pool/shard007/C++/0091826_devtools_window.cc @@ -0,0 +1,221 @@ +// Copyright (c) 2009 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 "app/l10n_util.h" +#include "base/command_line.h" +#include "chrome/browser/browser.h" +#include "chrome/browser/browser_list.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/browser_window.h" +#include "chrome/browser/debugger/devtools_manager.h" +#include "chrome/browser/debugger/devtools_window.h" +#include "chrome/browser/profile.h" +#include "chrome/browser/tab_contents/navigation_controller.h" +#include "chrome/browser/tab_contents/navigation_entry.h" +#include "chrome/browser/tab_contents/tab_contents.h" +#include "chrome/browser/tab_contents/tab_contents_view.h" +#include "chrome/browser/tabs/tab_strip_model.h" +#include "chrome/common/bindings_policy.h" +#include "chrome/common/chrome_switches.h" +#include "chrome/common/pref_names.h" +#include "chrome/common/pref_service.h" +#include "chrome/common/render_messages.h" +#include "chrome/common/url_constants.h" +#include "grit/generated_resources.h" + + +// static +TabContents* DevToolsWindow::GetDevToolsContents(TabContents* inspected_tab) { + if (!inspected_tab) { + return NULL; + } + DevToolsClientHost* client_host = DevToolsManager::GetInstance()-> + GetDevToolsClientHostFor(inspected_tab->render_view_host()); + if (!client_host) { + return NULL; + } + + DevToolsWindow* window = client_host->AsDevToolsWindow(); + if (!window || !window->is_docked()) { + return NULL; + } + return window->tab_contents(); +} + +DevToolsWindow::DevToolsWindow(Profile* profile, + RenderViewHost* inspected_rvh, + bool docked) + : profile_(profile), + browser_(NULL), + inspected_window_(NULL), + docked_(docked) { + // Create TabContents with devtools. + tab_contents_ = new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL); + GURL url(std::string(chrome::kChromeUIDevToolsURL) + "devtools.html"); + tab_contents_->render_view_host()->AllowBindings(BindingsPolicy::DOM_UI); + tab_contents_->controller().LoadURL(url, GURL(), PageTransition::START_PAGE); + + // Wipe out page icon so that the default application icon is used. + NavigationEntry* entry = tab_contents_->controller().GetActiveEntry(); + entry->favicon().set_bitmap(SkBitmap()); + entry->favicon().set_is_valid(true); + + // Register on-load actions. + registrar_.Add(this, + NotificationType::LOAD_STOP, + Source<NavigationController>(&tab_contents_->controller())); + registrar_.Add(this, + NotificationType::TAB_CLOSING, + Source<NavigationController>(&tab_contents_->controller())); + + inspected_tab_ = inspected_rvh->delegate()->GetAsTabContents(); +} + +DevToolsWindow::~DevToolsWindow() { +} + +DevToolsWindow* DevToolsWindow::AsDevToolsWindow() { + return this; +} + +void DevToolsWindow::SendMessageToClient(const IPC::Message& message) { + RenderViewHost* target_host = tab_contents_->render_view_host(); + IPC::Message* m = new IPC::Message(message); + m->set_routing_id(target_host->routing_id()); + target_host->Send(m); +} + +void DevToolsWindow::InspectedTabClosing() { + if (docked_) { + // Update dev tools to reflect removed dev tools window. + inspected_window_->UpdateDevTools(); + // In case of docked tab_contents we own it, so delete here. + delete tab_contents_; + + delete this; + } else { + // First, initiate self-destruct to free all the registrars. + // Then close all tabs. Browser will take care of deleting tab_contents + // for us. + Browser* browser = browser_; + delete this; + browser->CloseAllTabs(); + } +} + +void DevToolsWindow::Show() { + if (docked_) { + // Just tell inspected browser to update splitter. + inspected_window_ = GetInspectedBrowserWindow(); + if (inspected_window_) { + tab_contents_->set_delegate(this); + inspected_window_->UpdateDevTools(); + tab_contents_->view()->SetInitialFocus(); + return; + } else { + // Sometimes we don't know where to dock. Stay undocked. + docked_ = false; + } + } + + if (!browser_) { + CreateDevToolsBrowser(); + } + browser_->window()->Show(); + tab_contents_->view()->SetInitialFocus(); +} + +void DevToolsWindow::Activate() { + if (!docked_ && !browser_->window()->IsActive()) { + browser_->window()->Activate(); + } +} + +void DevToolsWindow::SetDocked(bool docked) { + if (docked_ == docked) { + return; + } + docked_ = docked; + + if (docked) { + // Detach window from the external devtools browser. It will lead to + // the browser object's close and delete. Remove observer first. + TabStripModel* tabstrip_model = browser_->tabstrip_model(); + tabstrip_model->DetachTabContentsAt( + tabstrip_model->GetIndexOfTabContents(tab_contents_)); + browser_ = NULL; + } else { + // Update inspected window to hide split and reset it. + inspected_window_->UpdateDevTools(); + inspected_window_ = NULL; + } + Show(); +} + +RenderViewHost* DevToolsWindow::GetRenderViewHost() { + return tab_contents_->render_view_host(); +} + +void DevToolsWindow::CreateDevToolsBrowser() { + // TODO(pfeldman): Make browser's getter for this key static. + std::wstring wp_key = L""; + wp_key.append(prefs::kBrowserWindowPlacement); + wp_key.append(L"_"); + wp_key.append(L"DevToolsApp"); + + PrefService* prefs = g_browser_process->local_state(); + if (!prefs->FindPreference(wp_key.c_str())) { + prefs->RegisterDictionaryPref(wp_key.c_str()); + } + + const DictionaryValue* wp_pref = prefs->GetDictionary(wp_key.c_str()); + if (!wp_pref) { + DictionaryValue* defaults = prefs->GetMutableDictionary(wp_key.c_str()); + defaults->SetInteger(L"left", 100); + defaults->SetInteger(L"top", 100); + defaults->SetInteger(L"right", 740); + defaults->SetInteger(L"bottom", 740); + defaults->SetBoolean(L"maximized", false); + defaults->SetBoolean(L"always_on_top", false); + } + + browser_ = Browser::CreateForApp(L"DevToolsApp", profile_, false); + browser_->tabstrip_model()->AddTabContents( + tab_contents_, -1, false, PageTransition::START_PAGE, true); +} + +BrowserWindow* DevToolsWindow::GetInspectedBrowserWindow() { + for (BrowserList::const_iterator it = BrowserList::begin(); + it != BrowserList::end(); ++it) { + Browser* browser = *it; + for (int i = 0; i < browser->tab_count(); ++i) { + TabContents* tab_contents = browser->GetTabContentsAt(i); + if (tab_contents == inspected_tab_) { + return browser->window(); + } + } + } + return NULL; +} + +void DevToolsWindow::Observe(NotificationType type, + const NotificationSource& source, + const NotificationDetails& details) { + if (type == NotificationType::LOAD_STOP) { + tab_contents_->render_view_host()-> + ExecuteJavascriptInWebFrame( + L"", docked_ ? L"WebInspector.setAttachedWindow(true);" : + L"WebInspector.setAttachedWindow(false);"); + } else if (type == NotificationType::TAB_CLOSING) { + if (Source<NavigationController>(source).ptr() == + &tab_contents_->controller()) { + // This happens when browser closes all of its tabs as a result + // of window.Close event. + // Notify manager that this DevToolsClientHost no longer exists and + // initiate self-destuct here. + NotifyCloseListener(); + delete this; + } + } +} diff --git a/pool/shard007/C++/0091844_collision_object_control.cpp b/pool/shard007/C++/0091844_collision_object_control.cpp new file mode 100644 index 0000000000000000000000000000000000000000..18a4d0a87d00a3c8f52c745b077d543dbb39eeda --- /dev/null +++ b/pool/shard007/C++/0091844_collision_object_control.cpp @@ -0,0 +1,55 @@ +//////////////////////////////////////////////////////////////////////////// +// Created : 13.03.2009 +// Author : Armen Abroyan +// Copyright (C) GSC Game World - 2009 +//////////////////////////////////////////////////////////////////////////// + +#include "pch.h" +#include "collision_object_control.h" + +namespace xray { +namespace editor { + +using math::float4x4; + +collision_object_transform_control::collision_object_transform_control( xray::collision::geometry const* geometry, + transform_control_base^ owner_control, + enum_transform_axis axis ): +collision_object ( geometry ), +m_owner ( owner_control ), +m_axis ( axis ) +{ + m_transform_original.identity(); + m_transform_general.identity(); + set_type ( collision_type_control ); +} + +enum_transform_axis collision_object_transform_control::get_axis ( ) const +{ + return m_axis; +} + +void collision_object_transform_control::set_matrix ( xray::math::float4x4 const& matrix ) +{ + m_transform_general = matrix; + collision_object::set_matrix ( m_transform_original*m_transform_general ); +} + +void collision_object_transform_control::set_matrix_original ( xray::math::float4x4 const& matrix ) +{ + m_transform_original = matrix; + set_matrix( m_transform_general ); +} + +xray::math::float4x4 const& collision_object_transform_control::get_matrix_original ( ) const +{ + return m_transform_original; +} + +//enum_collision_object_type collision_object_transform_control::get_type ( ) const +//{ +// return enum_collision_object_type_control; +//} + +}// namespace editor +}// namespace xray diff --git a/pool/shard007/C++/0091845_OGL_FBO.cpp b/pool/shard007/C++/0091845_OGL_FBO.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d097d4d199778e8f41891458d482c6b461e7c61d --- /dev/null +++ b/pool/shard007/C++/0091845_OGL_FBO.cpp @@ -0,0 +1,213 @@ +/* + + Copyright (C) 2015 and beyond by Jeremiah Morris + and the "Aleph One" developers. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + This license is contained in the file "COPYING", + which is included with this source code; it is available online at + http://www.gnu.org/licenses/gpl.html + + Framebuffer Object utilities +*/ + +#include "cseries.h" +#include "OGL_FBO.h" + +#ifdef HAVE_OPENGL + +#include "OGL_Setup.h" +#include "OGL_Render.h" + +std::vector<FBO *> FBO::active_chain; + +FBO::FBO(GLuint w, GLuint h, bool srgb) : _h(h), _w(w), _srgb(srgb) { + glGenFramebuffersEXT(1, &_fbo); + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _fbo); + + glGenRenderbuffersEXT(1, &_depthBuffer); + glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, _depthBuffer); + glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, _w, _h); + glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, _depthBuffer); + + glGenTextures(1, &texID); + glBindTexture(GL_TEXTURE_RECTANGLE_ARB, texID); + glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, srgb ? GL_SRGB : GL_RGB8, _w, _h, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); + glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_RECTANGLE_ARB, texID, 0); + assert(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) == GL_FRAMEBUFFER_COMPLETE_EXT); + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); +} + +void FBO::activate(bool clear, GLuint fboTarget) { + if (!active_chain.size() || active_chain.back() != this) { + active_chain.push_back(this); + _fboTarget = fboTarget; + glBindFramebufferEXT(fboTarget, _fbo); + glPushAttrib(GL_VIEWPORT_BIT); + glViewport(0, 0, _w, _h); + if (_srgb) + glEnable(GL_FRAMEBUFFER_SRGB_EXT); + else + glDisable(GL_FRAMEBUFFER_SRGB_EXT); + if (clear) + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + } +} + +void FBO::deactivate() { + if (active_chain.size() && active_chain.back() == this) { + active_chain.pop_back(); + glPopAttrib(); + + GLuint prev_fbo = 0; + bool prev_srgb = Using_sRGB; + if (active_chain.size()) { + prev_fbo = active_chain.back()->_fbo; + prev_srgb = active_chain.back()->_srgb; + } + glBindFramebufferEXT(_fboTarget, prev_fbo); + if (prev_srgb) + glEnable(GL_FRAMEBUFFER_SRGB_EXT); + else + glDisable(GL_FRAMEBUFFER_SRGB_EXT); + } +} + +void FBO::draw() { + glBindTexture(GL_TEXTURE_RECTANGLE_ARB, texID); + glEnable(GL_TEXTURE_RECTANGLE_ARB); + OGL_RenderTexturedRect(0, 0, _w, _h, 0, _h, _w, 0); + glDisable(GL_TEXTURE_RECTANGLE_ARB); +} + +void FBO::prepare_drawing_mode(bool blend) { + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + glLoadIdentity(); + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glLoadIdentity(); + + glDisable(GL_DEPTH_TEST); + if (!blend) + glDisable(GL_BLEND); + + glOrtho(0, _w, _h, 0, -1, 1); + glColor4f(1.0, 1.0, 1.0, 1.0); +} + +void FBO::reset_drawing_mode() { + glEnable(GL_BLEND); + glEnable(GL_DEPTH_TEST); + glMatrixMode(GL_PROJECTION); + glPopMatrix(); + glMatrixMode(GL_MODELVIEW); + glPopMatrix(); +} + +void FBO::draw_full(bool blend) { + prepare_drawing_mode(blend); + draw(); + reset_drawing_mode(); +} + +FBO::~FBO() { + glDeleteFramebuffersEXT(1, &_fbo); + glDeleteRenderbuffersEXT(1, &_depthBuffer); +} + + +void FBOSwapper::activate() { + if (active) + return; + if (draw_to_first) + first.activate(clear_on_activate); + else + second.activate(clear_on_activate); + active = true; + clear_on_activate = false; +} + +void FBOSwapper::deactivate() { + if (!active) + return; + if (draw_to_first) + first.deactivate(); + else + second.deactivate(); + active = false; +} + +void FBOSwapper::swap() { + deactivate(); + draw_to_first = !draw_to_first; + clear_on_activate = true; +} + +void FBOSwapper::draw(bool blend) { + current_contents().draw_full(blend); +} + +void FBOSwapper::filter(bool blend) { + activate(); + draw(blend); + swap(); +} + +void FBOSwapper::copy(FBO& other, bool srgb) { + clear_on_activate = true; + activate(); + other.draw_full(false); + swap(); +} + +void FBOSwapper::blend(FBO& other, bool srgb) { + activate(); + if (!srgb) + glDisable(GL_FRAMEBUFFER_SRGB_EXT); + else + glEnable(GL_FRAMEBUFFER_SRGB_EXT); + other.draw_full(true); + deactivate(); +} + +void FBOSwapper::blend_multisample(FBO& other) { + swap(); + activate(); + + // set up FBO passed in as texture #1 + glActiveTextureARB(GL_TEXTURE1_ARB); + glBindTexture(GL_TEXTURE_RECTANGLE_ARB, other.texID); + glEnable(GL_TEXTURE_RECTANGLE_ARB); + glActiveTextureARB(GL_TEXTURE0_ARB); + + glClientActiveTextureARB(GL_TEXTURE1_ARB); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + GLint multi_coordinates[8] = { 0, GLint(other._h), GLint(other._w), GLint(other._h), GLint(other._w), 0, 0, 0 }; + glTexCoordPointer(2, GL_INT, 0, multi_coordinates); + glClientActiveTextureARB(GL_TEXTURE0_ARB); + + draw(true); + + // tear down multitexture stuff + glActiveTextureARB(GL_TEXTURE1_ARB); + glDisable(GL_TEXTURE_RECTANGLE_ARB); + glActiveTextureARB(GL_TEXTURE0_ARB); + + glClientActiveTextureARB(GL_TEXTURE1_ARB); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + glClientActiveTextureARB(GL_TEXTURE0_ARB); + + deactivate(); +} + +#endif diff --git a/pool/shard007/C++/0091846_TheNumberGameDiv2.cpp b/pool/shard007/C++/0091846_TheNumberGameDiv2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cedc48f6d7331318ba395f0c75445d5bfc823627 --- /dev/null +++ b/pool/shard007/C++/0091846_TheNumberGameDiv2.cpp @@ -0,0 +1,68 @@ +//# bfs, strings, transformation +//# => trivial +#include <algorithm> +#include <cassert> +#include <cctype> +#include <cmath> +#include <cstdio> +#include <cstring> +#include <ctime> +#include <fstream> +#include <functional> +#include <iostream> +#include <iterator> +#include <map> +#include <numeric> +#include <queue> +#include <set> +#include <string> +#include <utility> +#include <vector> +#include <sstream> + +using namespace std; + +string tostr(int A) { + ostringstream os; + os << A; + return os.str(); +} +class TheNumberGameDiv2 { +public: + int minimumMoves(int A, int B) { + string a = tostr(A); + string b = tostr(B); + set<string> done; + done.insert(a); + queue<string> Q; + Q.push(a); + int dist = 0; + int sz = 1; + while (!Q.empty()) { + if (sz == 0) { + sz = Q.size(); + ++dist; + } + a = Q.front(); + Q.pop(); + --sz; + if (a == b) { + return dist; + } + if (a.size() < b.size()) continue; + if (a.size() > 1) { + string t = a.substr(0, a.size()-1); + if (!done.count(t)) { + done.insert(t); + Q.push(t); + } + } + reverse(a.begin(), a.end()); + if (!done.count(a)) { + done.insert(a); + Q.push(a); + } + } + return -1; + } +}; diff --git a/pool/shard007/C++/0091848_AwsEc2NetworkInterfaceAttachment.cpp b/pool/shard007/C++/0091848_AwsEc2NetworkInterfaceAttachment.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a003160f3c4667a64d556905c275fec9e04625eb --- /dev/null +++ b/pool/shard007/C++/0091848_AwsEc2NetworkInterfaceAttachment.cpp @@ -0,0 +1,163 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include <aws/securityhub/model/AwsEc2NetworkInterfaceAttachment.h> +#include <aws/core/utils/json/JsonSerializer.h> + +#include <utility> + +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +namespace Aws +{ +namespace SecurityHub +{ +namespace Model +{ + +AwsEc2NetworkInterfaceAttachment::AwsEc2NetworkInterfaceAttachment() : + m_attachTimeHasBeenSet(false), + m_attachmentIdHasBeenSet(false), + m_deleteOnTermination(false), + m_deleteOnTerminationHasBeenSet(false), + m_deviceIndex(0), + m_deviceIndexHasBeenSet(false), + m_instanceIdHasBeenSet(false), + m_instanceOwnerIdHasBeenSet(false), + m_statusHasBeenSet(false) +{ +} + +AwsEc2NetworkInterfaceAttachment::AwsEc2NetworkInterfaceAttachment(JsonView jsonValue) : + m_attachTimeHasBeenSet(false), + m_attachmentIdHasBeenSet(false), + m_deleteOnTermination(false), + m_deleteOnTerminationHasBeenSet(false), + m_deviceIndex(0), + m_deviceIndexHasBeenSet(false), + m_instanceIdHasBeenSet(false), + m_instanceOwnerIdHasBeenSet(false), + m_statusHasBeenSet(false) +{ + *this = jsonValue; +} + +AwsEc2NetworkInterfaceAttachment& AwsEc2NetworkInterfaceAttachment::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("AttachTime")) + { + m_attachTime = jsonValue.GetString("AttachTime"); + + m_attachTimeHasBeenSet = true; + } + + if(jsonValue.ValueExists("AttachmentId")) + { + m_attachmentId = jsonValue.GetString("AttachmentId"); + + m_attachmentIdHasBeenSet = true; + } + + if(jsonValue.ValueExists("DeleteOnTermination")) + { + m_deleteOnTermination = jsonValue.GetBool("DeleteOnTermination"); + + m_deleteOnTerminationHasBeenSet = true; + } + + if(jsonValue.ValueExists("DeviceIndex")) + { + m_deviceIndex = jsonValue.GetInteger("DeviceIndex"); + + m_deviceIndexHasBeenSet = true; + } + + if(jsonValue.ValueExists("InstanceId")) + { + m_instanceId = jsonValue.GetString("InstanceId"); + + m_instanceIdHasBeenSet = true; + } + + if(jsonValue.ValueExists("InstanceOwnerId")) + { + m_instanceOwnerId = jsonValue.GetString("InstanceOwnerId"); + + m_instanceOwnerIdHasBeenSet = true; + } + + if(jsonValue.ValueExists("Status")) + { + m_status = jsonValue.GetString("Status"); + + m_statusHasBeenSet = true; + } + + return *this; +} + +JsonValue AwsEc2NetworkInterfaceAttachment::Jsonize() const +{ + JsonValue payload; + + if(m_attachTimeHasBeenSet) + { + payload.WithString("AttachTime", m_attachTime); + + } + + if(m_attachmentIdHasBeenSet) + { + payload.WithString("AttachmentId", m_attachmentId); + + } + + if(m_deleteOnTerminationHasBeenSet) + { + payload.WithBool("DeleteOnTermination", m_deleteOnTermination); + + } + + if(m_deviceIndexHasBeenSet) + { + payload.WithInteger("DeviceIndex", m_deviceIndex); + + } + + if(m_instanceIdHasBeenSet) + { + payload.WithString("InstanceId", m_instanceId); + + } + + if(m_instanceOwnerIdHasBeenSet) + { + payload.WithString("InstanceOwnerId", m_instanceOwnerId); + + } + + if(m_statusHasBeenSet) + { + payload.WithString("Status", m_status); + + } + + return payload; +} + +} // namespace Model +} // namespace SecurityHub +} // namespace Aws diff --git a/pool/shard007/C++/0091849_qmljscomponentnamedialog.cpp b/pool/shard007/C++/0091849_qmljscomponentnamedialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d288bbde26e9d85b860f225c9b141e78c3683f4b --- /dev/null +++ b/pool/shard007/C++/0091849_qmljscomponentnamedialog.cpp @@ -0,0 +1,103 @@ +/************************************************************************** +** +** This file is part of Qt Creator +** +** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). +** +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** +** GNU Lesser General Public License Usage +** +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this file. +** Please review the following information to ensure the GNU Lesser General +** Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** Other Usage +** +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +**************************************************************************/ + +#include "qmljscomponentnamedialog.h" +#include "ui_qmljscomponentnamedialog.h" + +#include <QtCore/QFileInfo> +#include <QtGui/QFileDialog> + +using namespace QmlJSEditor::Internal; + +ComponentNameDialog::ComponentNameDialog(QWidget *parent) : + QDialog(parent), + ui(new Ui::ComponentNameDialog) +{ + ui->setupUi(this); + + connect(ui->choosePathButton, SIGNAL(clicked()), + this, SLOT(choosePath())); + connect(ui->pathEdit, SIGNAL(textChanged(QString)), + this, SLOT(validate())); + connect(ui->componentNameEdit, SIGNAL(textChanged(QString)), + this, SLOT(validate())); +} + +ComponentNameDialog::~ComponentNameDialog() +{ + delete ui; +} + +void ComponentNameDialog::go(QString *proposedName, + QString *proposedPath, + QWidget *parent) +{ + Q_ASSERT(proposedName); + Q_ASSERT(proposedPath); + + ComponentNameDialog d(parent); + d.ui->componentNameEdit->setText(*proposedName); + d.ui->pathEdit->setText(*proposedPath); + + if (QDialog::Accepted == d.exec()) { + *proposedName = d.ui->componentNameEdit->text(); + *proposedPath = d.ui->pathEdit->text(); + } +} + +void ComponentNameDialog::choosePath() +{ + QString dir = QFileDialog::getExistingDirectory(this, tr("Choose a path"), + ui->pathEdit->text()); + if (!dir.isEmpty()) + ui->pathEdit->setText(dir); +} + +void ComponentNameDialog::validate() +{ + const QString msg = isValid(); + ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(msg.isEmpty()); + ui->messageLabel->setText(msg); +} + +QString ComponentNameDialog::isValid() const +{ + QString compName = ui->componentNameEdit->text(); + if (compName.isEmpty() || !compName[0].isUpper()) + return tr("Invalid component name"); + + QString path = ui->pathEdit->text(); + if (path.isEmpty() || !QFileInfo(path).isDir()) + return tr("Invalid path"); + + return QString(); +} diff --git a/pool/shard007/C++/0091851_InitShader.cpp b/pool/shard007/C++/0091851_InitShader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d7c5bac15c8b8152e8dd9bef982cce32f9f0abd5 --- /dev/null +++ b/pool/shard007/C++/0091851_InitShader.cpp @@ -0,0 +1,101 @@ + +#include "Angel.h" + +//#define _CRT_SECURE_NO_WARNINGS + +namespace Angel { + +// Create a NULL-terminated string by reading the provided file +static char* +readShaderSource(const char* shaderFile) +{ + //FILE* fp = fopen(shaderFile, "r"); + FILE* fp; + fopen_s(&fp, shaderFile, "r"); + + if ( fp == NULL ) { return NULL; } + + fseek(fp, 0L, SEEK_END); + long size = ftell(fp); + + fseek(fp, 0L, SEEK_SET); + char* buf = new char[size + 1]; + fread(buf, 1, size, fp); + + buf[size] = '\0'; + fclose(fp); + + return buf; +} + + +// Create a GLSL program object from vertex and fragment shader files +GLuint +InitShader(const char* vShaderFile, const char* fShaderFile) +{ + struct Shader { + const char* filename; + GLenum type; + GLchar* source; + } shaders[2] = { + { vShaderFile, GL_VERTEX_SHADER, NULL }, + { fShaderFile, GL_FRAGMENT_SHADER, NULL } + }; + + GLuint program = glCreateProgram(); + + for ( int i = 0; i < 2; ++i ) { + Shader& s = shaders[i]; + s.source = readShaderSource( s.filename ); + if ( shaders[i].source == NULL ) { + std::cerr << "Failed to read " << s.filename << std::endl; + exit( EXIT_FAILURE ); + } + + GLuint shader = glCreateShader( s.type ); + glShaderSource( shader, 1, (const GLchar**) &s.source, NULL ); + glCompileShader( shader ); + + GLint compiled; + glGetShaderiv( shader, GL_COMPILE_STATUS, &compiled ); + if ( !compiled ) { + std::cerr << s.filename << " failed to compile:" << std::endl; + GLint logSize; + glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &logSize ); + char* logMsg = new char[logSize]; + glGetShaderInfoLog( shader, logSize, NULL, logMsg ); + std::cerr << logMsg << std::endl; + delete [] logMsg; + + exit( EXIT_FAILURE ); + } + + delete [] s.source; + + glAttachShader( program, shader ); + } + + /* link and error check */ + glLinkProgram(program); + + GLint linked; + glGetProgramiv( program, GL_LINK_STATUS, &linked ); + if ( !linked ) { + std::cerr << "Shader program failed to link" << std::endl; + GLint logSize; + glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logSize); + char* logMsg = new char[logSize]; + glGetProgramInfoLog( program, logSize, NULL, logMsg ); + std::cerr << logMsg << std::endl; + delete [] logMsg; + + exit( EXIT_FAILURE ); + } + + /* use program object */ + glUseProgram(program); + + return program; +} + +} // Close namespace Angel block diff --git a/pool/shard007/C++/0091857_main.cpp b/pool/shard007/C++/0091857_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a6b23fb471872ed47088a38ba5a3cb0d4f34be59 --- /dev/null +++ b/pool/shard007/C++/0091857_main.cpp @@ -0,0 +1,43 @@ +#include <iostream> + +#include "BigInt.hpp" + +int main() +{ + try + { + BigInt pi; + + int iterations; + + std::cout << "Enter number of iterations:" << std::endl; + std::cin >> iterations; + + int power; + std::cout << "Enter desired power to raise 10 to:" << std::endl; + std::cin >> power; + + BigInt multiplier(10); + multiplier ^= power; + + BigInt i(iterations); + + for (; i > 0; i -= 1) + { + BigInt pi_part(multiplier * (fact(i)^2) * (BigInt(2)^(i + 1)) / fact(2 * i + 1)); + std::cout << "pi_part["<<i<<"]: " << pi_part << std::endl; + pi += pi_part; + } + + std::string &str = pi.get_string_repr_ref(); + str[0] = '3'; + str.insert(1, ".", 1); + + } + catch (const std::exception& ex) + { + std::cerr << ex.what() << std::endl; + } + + return 0; +} diff --git a/pool/shard007/C++/0091860_gucefWEB_CAsyncHttpServerResponseHandler.cpp b/pool/shard007/C++/0091860_gucefWEB_CAsyncHttpServerResponseHandler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a61668af36244dd8ac87a448ae7b8c6bde6e9d62 --- /dev/null +++ b/pool/shard007/C++/0091860_gucefWEB_CAsyncHttpServerResponseHandler.cpp @@ -0,0 +1,214 @@ +/* + * gucefWEB: GUCEF module providing Web application functionality + * for standardized protocols + * + * Copyright (C) 1998 - 2020. Dinand Vanvelzen + * + * 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. + */ + +/*-------------------------------------------------------------------------// +// // +// INCLUDES // +// // +//-------------------------------------------------------------------------*/ + +#include <string.h> +#include <time.h> + +#ifndef GUCEF_CORE_CTASKMANAGER_H +#include "gucefCORE_CTaskManager.h" +#define GUCEF_CORE_CTASKMANAGER_H +#endif /* GUCEF_CORE_CTASKMANAGER_H */ + +#ifndef GUCEF_WEB_CHTTPSERVER_H +#include "gucefWEB_CHTTPServer.h" +#define GUCEF_WEB_CHTTPSERVER_H +#endif /* GUCEF_WEB_CHTTPSERVER_H */ + +#include "gucefWEB_CAsyncHttpServerResponseHandler.h" + +/*-------------------------------------------------------------------------// +// // +// NAMESPACE // +// // +//-------------------------------------------------------------------------*/ + +namespace GUCEF { +namespace WEB { + +/*-------------------------------------------------------------------------// +// // +// GLOBAL VARS // +// // +//-------------------------------------------------------------------------*/ + +const CORE::CString CAsyncHttpServerResponseHandler::TaskType = "AsyncHttpServerResponseHandler"; +const CORE::CEvent CAsyncHttpServerResponseHandler::AsyncHttpServerResponseHandlingCompletedEvent = "GUCEF::COM::CAsyncHttpServerResponseHandler::AsyncHttpServerResponseHandlingCompletedEvent"; + +/*-------------------------------------------------------------------------// +// // +// IMPLEMENTATION // +// // +//-------------------------------------------------------------------------*/ + +CAsyncHttpResponseData::CAsyncHttpResponseData( CAsyncHttpRequestData* request ) + : CHttpResponseData() + , httpServer( GUCEF_NULL ) + , clientConnectionId( 0 ) + , remoteClientAddress() +{GUCEF_TRACE; + + if ( GUCEF_NULL != request ) + { + httpServer = request->httpServer; + clientConnectionId = request->clientConnectionId; + remoteClientAddress = request->remoteClientAddress; + keepConnectionsAlive = request->keepConnectionsAlive; + } +} + +/*-------------------------------------------------------------------------*/ + +CAsyncHttpResponseData::CAsyncHttpResponseData( const CAsyncHttpResponseData& src ) + : CHttpResponseData( src ) + , httpServer( src.httpServer ) + , clientConnectionId( src.clientConnectionId ) + , remoteClientAddress( src.remoteClientAddress ) +{GUCEF_TRACE; + +} + +/*-------------------------------------------------------------------------*/ + +CAsyncHttpResponseData::~CAsyncHttpResponseData() +{GUCEF_TRACE; + +} + +/*-------------------------------------------------------------------------*/ + +CORE::CICloneable* +CAsyncHttpResponseData::Clone( void ) const +{GUCEF_TRACE; + + return new CAsyncHttpResponseData( *this ); +} + +/*-------------------------------------------------------------------------*/ + +void +CAsyncHttpServerResponseHandler::RegisterEvents( void ) +{GUCEF_TRACE; + + AsyncHttpServerResponseHandlingCompletedEvent.Initialize(); +} + +/*-------------------------------------------------------------------------*/ + +CAsyncHttpServerResponseHandler::CAsyncHttpServerResponseHandler( void ) + : CORE::CTaskConsumer() +{GUCEF_TRACE; + + RegisterEvents(); +} + +/*-------------------------------------------------------------------------*/ + +CAsyncHttpServerResponseHandler::CAsyncHttpServerResponseHandler( const CAsyncHttpServerResponseHandler& src ) + : CORE::CTaskConsumer() +{GUCEF_TRACE; + +} + +/*-------------------------------------------------------------------------*/ + +CAsyncHttpServerResponseHandler::~CAsyncHttpServerResponseHandler() +{GUCEF_TRACE; + +} + +/*-------------------------------------------------------------------------*/ + +CORE::CString +CAsyncHttpServerResponseHandler::GetType( void ) const +{GUCEF_TRACE; + + return TaskType; +} + +/*-------------------------------------------------------------------------*/ + +bool +CAsyncHttpServerResponseHandler::OnTaskStart( CORE::CICloneable* taskData ) +{GUCEF_TRACE; + + GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "AsyncHttpServerResponseHandler(" + CORE::PointerToString( this ) + "):OnTaskStart" ); + return true; +} + +/*-------------------------------------------------------------------------*/ + +bool +CAsyncHttpServerResponseHandler::OnTaskCycle( CORE::CICloneable* taskData ) +{GUCEF_TRACE; + + GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "AsyncHttpServerResponseHandler(" + CORE::PointerToString( this ) + "):OnTaskCycle" ); + + CAsyncHttpResponseData* httpResponseData = static_cast< CAsyncHttpResponseData* >( taskData ); + if ( GUCEF_NULL == httpResponseData ) + { + GUCEF_ERROR_LOG( CORE::LOGLEVEL_NORMAL, "AsyncHttpServerResponseHandler(" + CORE::PointerToString( this ) + "):OnTaskCycle: No task data (http response) to operate upon" ); + return true; + } + + CORE::CDynamicBuffer fullResponse; + if ( httpResponseData->Serialize( fullResponse ) ) + { + httpResponseData->httpServer->SendResponseASync( httpResponseData->clientConnectionId , + fullResponse , + httpResponseData->remoteClientAddress ); + } + return true; +} + +/*-------------------------------------------------------------------------*/ + +void +CAsyncHttpServerResponseHandler::OnTaskEnding( CORE::CICloneable* taskData , + bool willBeForced ) +{GUCEF_TRACE; + +} + +/*-------------------------------------------------------------------------*/ + +void +CAsyncHttpServerResponseHandler::OnTaskEnded( CORE::CICloneable* taskData , + bool wasForced ) +{GUCEF_TRACE; + + GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "AsyncHttpServerResponseHandler(" + CORE::PointerToString( this ) + "):OnTaskEnded" ); + CORE::CTaskConsumer::OnTaskEnded( taskData, wasForced ); +} + +/*-------------------------------------------------------------------------// +// // +// NAMESPACE // +// // +//-------------------------------------------------------------------------*/ + +}; /* namespace WEB */ +}; /* namespace GUCEF */ + +/*-------------------------------------------------------------------------*/ diff --git a/pool/shard007/C++/0091861_utility_mac.cpp b/pool/shard007/C++/0091861_utility_mac.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2397f7cc8c04c4ecabb4678ca44d29f599ee4314 --- /dev/null +++ b/pool/shard007/C++/0091861_utility_mac.cpp @@ -0,0 +1,126 @@ +/* + * Copyright (C) by Daniel Molkentin <danimo@owncloud.com> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#include <CoreServices/CoreServices.h> +#include <CoreFoundation/CoreFoundation.h> + +static void setupFavLink_private(const QString &folder) +{ + // Finder: Place under "Places"/"Favorites" on the left sidebar + CFStringRef folderCFStr = CFStringCreateWithCString(0, folder.toUtf8().data(), kCFStringEncodingUTF8); + CFURLRef urlRef = CFURLCreateWithFileSystemPath (0, folderCFStr, kCFURLPOSIXPathStyle, true); + + LSSharedFileListRef placesItems = LSSharedFileListCreate(0, kLSSharedFileListFavoriteItems, 0); + if (placesItems) { + //Insert an item to the list. + LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(placesItems, + kLSSharedFileListItemLast, 0, 0, + urlRef, 0, 0); + if (item) + CFRelease(item); + } + CFRelease(placesItems); + CFRelease(folderCFStr); + CFRelease(urlRef); +} + +bool hasLaunchOnStartup_private(const QString &) +{ + // this is quite some duplicate code with setLaunchOnStartup, at some point we should fix this FIXME. + bool returnValue = false; + QString filePath = QDir(QCoreApplication::applicationDirPath()+QLatin1String("/../..")).absolutePath(); + CFStringRef folderCFStr = CFStringCreateWithCString(0, filePath.toUtf8().data(), kCFStringEncodingUTF8); + CFURLRef urlRef = CFURLCreateWithFileSystemPath (0, folderCFStr, kCFURLPOSIXPathStyle, true); + LSSharedFileListRef loginItems = LSSharedFileListCreate(0, kLSSharedFileListSessionLoginItems, 0); + if (loginItems) { + // We need to iterate over the items and check which one is "ours". + UInt32 seedValue; + CFArrayRef itemsArray = LSSharedFileListCopySnapshot(loginItems, &seedValue); + CFStringRef appUrlRefString = CFURLGetString(urlRef); // no need for release + for (int i = 0; i < CFArrayGetCount(itemsArray); i++) { + LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(itemsArray, i); + CFURLRef itemUrlRef = NULL; + + if (LSSharedFileListItemResolve(item, 0, &itemUrlRef, NULL) == noErr) { + CFStringRef itemUrlString = CFURLGetString(itemUrlRef); + if (CFStringCompare(itemUrlString,appUrlRefString,0) == kCFCompareEqualTo) { + returnValue = true; + } + CFRelease(itemUrlRef); + } + } + CFRelease(itemsArray); + } + CFRelease(loginItems); + CFRelease(folderCFStr); + CFRelease(urlRef); + return returnValue; +} + +void setLaunchOnStartup_private(const QString &appName, const QString& guiName, bool enable) +{ + Q_UNUSED(appName) + Q_UNUSED(guiName) + QString filePath = QDir(QCoreApplication::applicationDirPath()+QLatin1String("/../..")).absolutePath(); + CFStringRef folderCFStr = CFStringCreateWithCString(0, filePath.toUtf8().data(), kCFStringEncodingUTF8); + CFURLRef urlRef = CFURLCreateWithFileSystemPath (0, folderCFStr, kCFURLPOSIXPathStyle, true); + LSSharedFileListRef loginItems = LSSharedFileListCreate(0, kLSSharedFileListSessionLoginItems, 0); + + if (loginItems && enable) { + //Insert an item to the list. + LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(loginItems, + kLSSharedFileListItemLast, 0, 0, + urlRef, 0, 0); + if (item) + CFRelease(item); + CFRelease(loginItems); + } else if (loginItems && !enable){ + // We need to iterate over the items and check which one is "ours". + UInt32 seedValue; + CFArrayRef itemsArray = LSSharedFileListCopySnapshot(loginItems, &seedValue); + CFStringRef appUrlRefString = CFURLGetString(urlRef); + for (int i = 0; i < CFArrayGetCount(itemsArray); i++) { + LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(itemsArray, i); + CFURLRef itemUrlRef = NULL; + + if (LSSharedFileListItemResolve(item, 0, &itemUrlRef, NULL) == noErr) { + CFStringRef itemUrlString = CFURLGetString(itemUrlRef); + if (CFStringCompare(itemUrlString,appUrlRefString,0) == kCFCompareEqualTo) { + LSSharedFileListItemRemove(loginItems,item); // remove it! + } + CFRelease(itemUrlRef); + } + } + CFRelease(itemsArray); + CFRelease(loginItems); + }; + + CFRelease(folderCFStr); + CFRelease(urlRef); +} + +static bool hasDarkSystray_private() +{ + bool returnValue = false; + CFStringRef interfaceStyleKey = CFSTR("AppleInterfaceStyle"); + CFStringRef interfaceStyle = NULL; + CFStringRef darkInterfaceStyle = CFSTR("Dark"); + interfaceStyle = (CFStringRef)CFPreferencesCopyAppValue(interfaceStyleKey, + kCFPreferencesCurrentApplication); + if (interfaceStyle != NULL) { + returnValue = (kCFCompareEqualTo == CFStringCompare(interfaceStyle, darkInterfaceStyle, 0)); + CFRelease(interfaceStyle); + } + return returnValue; +} + diff --git a/pool/shard007/C++/0091866_megastar.cpp b/pool/shard007/C++/0091866_megastar.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6cdadcf87e3ab6c39a5e5dd1ac6a1608ddea7cc0 --- /dev/null +++ b/pool/shard007/C++/0091866_megastar.cpp @@ -0,0 +1,74 @@ +#include "megastar.h" + +using namespace std; +/** Constructor. All Megastars (initially) move diagonally down the screen and have maxHealth of 1 + @param pix the QPixmap the represent the Megastar + @param x the x coord at which to appear + @param y the y coord at which to appear + @param w the width of the Megastar + @param h the height of the Megastar + @param speed the speed the Megastar will move + @param rocketToAvoid the Rocket that the Megastar moves away from +*/ +Megastar::Megastar(QPixmap* pic, int x, int y, int w, int h, int speed, Rocket* rocketToAvoid) : Thing(pic, x, y, w, h, speed, speed, 1) { + offScreen = false; + collisionCounts = true; + rocket_ = rocketToAvoid; + speed_ = speed; +} + +/** Default constructor */ +Megastar::Megastar(){} +/** Destructor */ +Megastar::~Megastar(){} + +/** Returns true if the Megastar is intersecting with a Thing, false otherwise. If true, adds 1 to the Thing's megastar_ count and flags offScreen as true + @param rocket the Thing the Megastar is checking if it's colliding with +*/ +bool Megastar::collidesWith(Thing* rocket){ + if (rocket->getPic() == pic_) + return false; + + bool collide = collidesWithItem(rocket, Qt::IntersectsItemShape); + if (collide && collisionCounts) + { + rocket->addMegastar(); // adds Megastar + offScreen = true; + collisionCounts = false; + return true; + } + else + return false; +} + +/** The function that makes the Megastar move to avoid the rocket + @param windowMaxX the x-area the Megastar can move in without being considered offScreen + @param windowMaxY the y-area the Megastar can move in without being considered offScreen +*/void Megastar::move(int windowMaxX, int windowMaxY) +{ + + int diffX = rocket_->getX() - (x_+width_); + int diffY = rocket_->getY() - (y_+height_); + + //if within a certain range of the rocket, moves to avoid it + if (diffX < 15 && diffY < 15) + { + velocityX_ = (x_ - rocket_->getX())/15*speed_; + velocityY_ = (y_ - rocket_->getY())/15*speed_; + } + // otherwise, moves diagonally at original speed + else + { + velocityX_ = speed_; + velocityY_ = speed_; + } + + x_ += velocityX_; + y_ += velocityY_; + setPos(x_,y_); + + // keep track of whether on screen or not + if ( (x_+width_)< 0 || (y_+height_)< 0 || (x_ > windowMaxX ) || ( y_ > windowMaxY ) ) + offScreen = true; + +} diff --git a/pool/shard007/C++/0091870_agent.cpp b/pool/shard007/C++/0091870_agent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9b1945622850f3016b6621bf743520e1c08d2519 --- /dev/null +++ b/pool/shard007/C++/0091870_agent.cpp @@ -0,0 +1,126 @@ +#include "agent.h" +#include "agent_adaptor.h" +#include "Keyboard.h" +#include "MainWindow.h" + +#include <QtDBus> +#include <QInputDialog> +#include <QMessageBox> + +Agent::Agent(MainWindow *window, QString path) +{ + new AgentAdaptor(this); + QDBusConnection::systemBus().registerObject(path, this); + win = window; +} + +Agent::~Agent() +{ +} + +void Agent::reject(const char *msg) +{ + sendErrorReply("org.bluez.Error.Rejected", msg); +} + +void Agent::Authorize(const QDBusObjectPath &in0, const QString &in1) +{ + Q_UNUSED(in0); + Q_UNUSED(in1); + + QMessageBox::StandardButton reply; + reply = QMessageBox::question(win, "Authorize connection ?", + "Authorize connection ?", QMessageBox::Yes | QMessageBox::No); + if (reply == QMessageBox::Yes) + return; + reject("Connection rejected by user"); +} + +void Agent::Cancel() +{ + QString message("Pairing remote device failed."); + win->pairFailed(message); +} + +void Agent::ConfirmModeChange(const QString &in0) +{ + QString message("Authorize mode change to " + in0 + " ?"); + QMessageBox::StandardButton reply; + reply = QMessageBox::question(win, "Mode change", + message, QMessageBox::Yes | QMessageBox::No); + if (reply == QMessageBox::Yes) + return; + reject("Mode change by user"); +} + +void Agent::DisplayPasskey(const QDBusObjectPath &in0, uint in1, uchar in2) +{ + Q_UNUSED(in0); + Q_UNUSED(in2); + + QString message; + message.sprintf("Passkey is %i", in1); + QMessageBox::information(win, "Passkey", message); +} + +void Agent::Release() +{ + // TODO release it before program closes +} + +void Agent::RequestConfirmation(const QDBusObjectPath &in0, uint in1) +{ + Q_UNUSED(in0); + + QString message; + message.sprintf("Confirm passkey %i ?", in1); + QMessageBox::StandardButton reply; + reply = QMessageBox::question(win, "Request confirmation", + message, QMessageBox::Yes | QMessageBox::No); + if (reply == QMessageBox::Yes) + return; + reject("Passkey doesn't match"); +} + +uint Agent::RequestPasskey(const QDBusObjectPath &in0) +{ + Q_UNUSED(in0); + + Keyboard keyboard; + if (!keyboard.exec()) + return 0; + + bool valid; + uint ret = keyboard.getText().toUInt(&valid, 10); + if (!valid) + return 0; + + return ret; +} + +QString Agent::RequestPinCode(const QDBusObjectPath &in0) +{ + Q_UNUSED(in0); + + Keyboard keyboard; + if (!keyboard.exec()) + return QString(); + + return keyboard.getText(); +} + +void Agent::deviceCreated(QDBusPendingCallWatcher *call) +{ + QDBusPendingReply<QDBusObjectPath> reply = *call; + + if (reply.isValid()) { + win->pairSuccessful(); + return; + } + + QDBusError error = reply.error(); + QString message("Pairing failed: " + error.name() + " " + error.message()); + win->pairFailed(message); + + call->deleteLater(); +} diff --git a/pool/shard007/C++/0091871_Header_Linked_List.cpp b/pool/shard007/C++/0091871_Header_Linked_List.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b09df4d30a578fab01ff16fd09332739ebb636d6 --- /dev/null +++ b/pool/shard007/C++/0091871_Header_Linked_List.cpp @@ -0,0 +1,96 @@ +#include <iostream> +#include <conio.h> + +using namespace std; + +struct node{ + int info; + node *next; +}*ptr,*head,*start; + + +//Function for creating new node and Inserting data in the node +struct node* insert(struct node* head,int data){ + ptr=new node; + ptr->next=NULL; + ptr->info=data; + + head->next=ptr; + cout<<"Data Inserted\n"; + return ptr; +} + +//Function for searching item in Linked List +int search(struct node* start,int item){ + ptr=start->next; + int f,k; + f=0; + k=0; + while(ptr!=NULL){ + k++; + if(ptr->info==item){ + f++; + cout<<"Item Found at Node: "<<k<<"\n"; + } + ptr=ptr->next; + } + return f; +} + +//Function for Printing the Linked List +void printLL(struct node* start){ + + ptr=start->next; + + while(ptr!=NULL){ + cout<<ptr->info<<"->"; + ptr=ptr->next; + } + cout<<"\n"; + +} + +int main(){ + +int c=1,k=0,item,data; + +ptr=new node; +ptr->next=NULL; +start=head=ptr; + +while(c<4 && c>0){ + cout<<"1.Insert\n2.Search Item\n3.Link List\n"; + cin>>c; + + switch(c){ + case 1: + cout<<"Enter Data\n"; + cin>>data; + + head=insert(head,data); + break; + + case 2: + cout<<"Enter Item that you want to find\n"; + cin>>item; + + int f; + f=search(start,item); + if(f==0){ + cout<<"Item Not Found\n"; + } + break; + + case 3: + printLL(start); + break; + + default: + cout<<"Wrong Choice\nExiting...\n"; + } + +} + +getch(); +return 0; +} \ No newline at end of file diff --git a/pool/shard007/C++/0091872_wxCodeCompletionBoxBase.cpp b/pool/shard007/C++/0091872_wxCodeCompletionBoxBase.cpp new file mode 100644 index 0000000000000000000000000000000000000000..98781e5d1e3f7576398ebfef11ca64b05a7d5bc2 --- /dev/null +++ b/pool/shard007/C++/0091872_wxCodeCompletionBoxBase.cpp @@ -0,0 +1,59 @@ +////////////////////////////////////////////////////////////////////// +// This file was auto-generated by codelite's wxCrafter Plugin +// wxCrafter project file: wxCodeCompletionBox.wxcp +// Do not modify this file by hand! +////////////////////////////////////////////////////////////////////// + +#include "wxCodeCompletionBoxBase.h" + +#include "codelite_exports.h" + +// Declare the bitmap loading function +extern void wxC9ED9AInitBitmapResources(); + +static bool bBitmapLoaded = false; + +wxCodeCompletionBoxBase::wxCodeCompletionBoxBase(wxWindow* parent, long style) + : wxPopupWindow(parent, style) +{ + if(!bBitmapLoaded) { + // We need to initialise the default bitmap handler + wxXmlResource::Get()->AddHandler(new wxBitmapXmlHandler); + wxC9ED9AInitBitmapResources(); + bBitmapLoaded = true; + } + + wxBoxSizer* mainSizer = new wxBoxSizer(wxHORIZONTAL); + this->SetSizer(mainSizer); + + m_mainPanel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDLG_UNIT(this, wxSize(-1, -1)), wxTAB_TRAVERSAL); + + mainSizer->Add(m_mainPanel, 1, wxEXPAND, WXC_FROM_DIP(0)); + + wxBoxSizer* boxSizer43 = new wxBoxSizer(wxVERTICAL); + m_mainPanel->SetSizer(boxSizer43); + + m_list = new clThemedListCtrl(m_mainPanel, wxID_ANY, wxDefaultPosition, wxDLG_UNIT(m_mainPanel, wxSize(-1, -1)), + wxDV_NO_HEADER | wxDV_ROW_LINES | wxDV_SINGLE | wxBORDER_NONE); + + boxSizer43->Add(m_list, 1, wxALL | wxEXPAND, WXC_FROM_DIP(1)); + + SetName(wxT("wxCodeCompletionBoxBase")); + SetSize(wxDLG_UNIT(this, wxSize(-1, -1))); + if(GetSizer()) { + GetSizer()->Fit(this); + } + // Connect events + m_list->Connect(wxEVT_COMMAND_DATAVIEW_SELECTION_CHANGED, + wxDataViewEventHandler(wxCodeCompletionBoxBase::OnSelectionChanged), NULL, this); + m_list->Connect(wxEVT_COMMAND_DATAVIEW_ITEM_ACTIVATED, + wxDataViewEventHandler(wxCodeCompletionBoxBase::OnSelectionActivated), NULL, this); +} + +wxCodeCompletionBoxBase::~wxCodeCompletionBoxBase() +{ + m_list->Disconnect(wxEVT_COMMAND_DATAVIEW_SELECTION_CHANGED, + wxDataViewEventHandler(wxCodeCompletionBoxBase::OnSelectionChanged), NULL, this); + m_list->Disconnect(wxEVT_COMMAND_DATAVIEW_ITEM_ACTIVATED, + wxDataViewEventHandler(wxCodeCompletionBoxBase::OnSelectionActivated), NULL, this); +} diff --git a/pool/shard007/C++/0091876_audio_oss.cpp b/pool/shard007/C++/0091876_audio_oss.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2a55c9a12589cc2a042d9ecdbc22497788cefbf1 --- /dev/null +++ b/pool/shard007/C++/0091876_audio_oss.cpp @@ -0,0 +1,216 @@ +// +// guitune - program for tuning instruments (actually an oscilloscope) +// Copyright (C) 1999 Florian Berger +// Copyright (C) 2013-2015 Yann Collette +// Email: florian.berger@jk.uni-linz.ac.at +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License Version 2 as +// published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +// + +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> +#include <sys/ioctl.h> +#include <linux/soundcard.h> + +#include <unistd.h> +#include <stdio.h> +#include <time.h> +#include <stdlib.h> +#include <string.h> +#include <math.h> + +#include <iostream> + +#include <QtWidgets> + +#include "audio_oss.h" +#include "resources.h" +#include "guitune.h" +#include "osziview.h" +#include "logview.h" + +extern double KAMMERTON, KAMMERTON_LOG; + +AudioOSS::AudioOSS(QString audio_name) : AudioBase(audio_name), audio(0) +{ + // KAMMERTON: the reference A note (440 Hz for standard tuning = KAMMERTON_NORM + freqs[0] = KAMMERTON; // The reference frequency + lfreqs[0] = KAMMERTON_LOG; // The log of the reference frequency + + // Produce an octave + for(int i=1; i<12; i++) { + freqs [i] = freqs [i-1] * D_NOTE; + lfreqs[i] = lfreqs[i-1] + D_NOTE_LOG; + } +} + +AudioOSS::~AudioOSS() +{ + int ret = close_audio(); +} + +void AudioOSS::setDSPName(QString name) +{ + audio = close_audio(); + dsp_devicename = QString(name); + audio = init_audio(); +} + +int AudioOSS::close_audio() +{ + return close(audio); +} + +int AudioOSS::init_audio() +{ + std::cout << qPrintable(tr("initializing audio at ")) << qPrintable(dsp_devicename) << std::endl; + + audio = open(dsp_devicename.toStdString().c_str(), O_RDONLY); + if (audio == -1) { + perror(dsp_devicename.toStdString().c_str()); + exit(1); + } + fcntl(audio,F_SETFD,FD_CLOEXEC); // Set the 'audio' file descriptor (F_SETFD) to FD_CLOEXEC: if the FD_CLOEXEC flag in the third argument is 0, + // the file shall remain open across the exec functions; otherwise, the file shall be closed upon successful + // execution of one of the exec functions. + + if (dsp_devicename == QString("/dev/stdin")) { + std::cout << qPrintable(tr("reading data from stdin")) << std::endl; + blksize = 32; + std::cout << " blocksize = " << blksize << std::endl; + std::cout << " sampfreq = " << sampfreq << std::endl; + sampfreq_exact = sampfreq; + } else { + // Get the capabilities of the audio stream + int caps; + ioctl(audio, SNDCTL_DSP_GETCAPS, &caps); + std::cout << "OSS-Version " << int(caps & DSP_CAP_REVISION) << std::endl; + std::cout << " DUPLEX = " << int(caps & DSP_CAP_DUPLEX) << std::endl; + std::cout << " REALTIME = " << int(caps & DSP_CAP_REALTIME) << std::endl; + std::cout << " BATCH = " << int(caps & DSP_CAP_BATCH) << std::endl; + std::cout << " COPROC = " << int(caps & DSP_CAP_COPROC) << std::endl; + std::cout << " TRIGGER = " << int(caps & DSP_CAP_TRIGGER) << std::endl; + std::cout << " MMAP = " << int(caps & DSP_CAP_MMAP) << std::endl; + + blksize = 8; // 2^8 = 256 + // Automatically set the buffer allocation + ioctl(audio, SNDCTL_DSP_SETFRAGMENT, &blksize); + + // Get the block size after buffer allocation + ioctl(audio, SNDCTL_DSP_GETBLKSIZE, &blksize); + std::cout << "blocksize = " << blksize << std::endl; + + // Suspend the application until all samples have been played + ioctl(audio, SNDCTL_DSP_SYNC, NULL); + // Set the sample format to unsigned 8 bits + int a_sampsize = AFMT_U8; + ioctl(audio, SNDCTL_DSP_SETFMT, &a_sampsize); + // Set mono mode + int a_stereo = 0; + ioctl(audio, SNDCTL_DSP_STEREO, &a_stereo); + + int a_speed = sampfreq; + std::cout << "sampfreq = " << sampfreq << std::endl; + // Set the sampling rate + ioctl(audio, SNDCTL_DSP_SPEED, &a_speed); + ioctl(audio, SOUND_PCM_READ_RATE, &sampfreq); // Obsolete ! + std::cout << "sampfreq = " << sampfreq << std::endl; + sampfreq_exact = sampfreq; + } + + return(audio); +} + +void AudioOSS::proc_audio() +{ + int i,j,n,trig,trigpos; + static int k = 0; + unsigned char *c = NULL; + double ldf,mldf; + + processing_audio = 1; + trigpos = 0; + c = sample; + n = read(audio, c, blksize); + + // We search a 0 crossing value (beware: unsigned char !) + for(i=0; i<n && Abs(c[i]-128)<2; i++); + + j = 0; + trig = 0; + + if (i<n) do { + for( ; i<n-1; i++) /* n-1 because of POSTRIG uses i+1 */ + if (POSTRIG(c,i)) { + trig = 1; + trigpos = i; + } + if (trig==0) { + n = read(audio, c, blksize); + j++; + i=0; + } + // We loop over the samples until we have found a new 0 crossing value + } while((!trig) && j<NO_TRIG_LIMIT); + + if (trig) { + for(i=n-trigpos; i<sampnr; i+=n) { + c += n; + n = read(audio, c, blksize); + } + + // Plot the measured values + mw->getOsziPtr()->setSamplePtr(&sample[trigpos]); + mw->getOsziPtr()->paintSample(); + + freq_0t = (double)sampfreq * mw->getOsziPtr()->getfreq2(); + lfreq_0t = log(freq_0t); + + while(lfreq_0t < lfreqs[0] - D_NOTE_LOG/2.0) lfreq_0t += LOG_2; + while(lfreq_0t >= lfreqs[0] + LOG_2 - D_NOTE_LOG/2.0) lfreq_0t -= LOG_2; + + mldf = D_NOTE_LOG; + note_0t = 0; + + for(i=0; i<12; i++) { + ldf = fabs(lfreq_0t - lfreqs[i]); + if (ldf < mldf) { + mldf = ldf; + note_0t = i; + } + } + + // Display the frequency + update_lfreq(); + + double nfreq_0t = freqs[note_0t]; + while(nfreq_0t/freq_0t > D_NOTE_SQRT) nfreq_0t /= 2.0; + while(freq_0t/nfreq_0t > D_NOTE_SQRT) nfreq_0t *= 2.0; + + // Display the note + update_nfreq(nfreq_0t); + } + + k++; + processing_audio = 0; +} + +void AudioOSS::setSampleFreq(int f) +{ + sampfreq = f; + audio = close_audio(); + audio = init_audio(); +} + diff --git a/pool/shard007/C++/0091877_navdata.cpp b/pool/shard007/C++/0091877_navdata.cpp new file mode 100644 index 0000000000000000000000000000000000000000..75d4bc921910094e714a055624f5a0de9744d0ab --- /dev/null +++ b/pool/shard007/C++/0091877_navdata.cpp @@ -0,0 +1,208 @@ +#include "rqt_ardrone/navdata/navdata.h" +#include <pluginlib/class_list_macros.h> +#include <QStringList> + +#include <qwt_compass.h> +#include <qwt_compass_rose.h> +#include <qwt_dial_needle.h> + +namespace rqt_ardrone { + +Navdata::Navdata() +: rqt_gui_cpp::Plugin() +, widget_(0) +{ + setObjectName("ArdroneNavdata"); +} + +void Navdata::initPlugin(qt_gui_cpp::PluginContext& context) +{ + QStringList argv = context.argv(); + + widget_ = new QWidget(); + ui_.setupUi(widget_); + context.addWidget(widget_); + + /* Setup plot data */ + altdSamples_ = new NavdataStampedSamples(0, 3000.0); + xVelSamples_ = new NavdataStampedSamples(-1000.0, 1000.0); + yVelSamples_ = new NavdataStampedSamples(-1000.0, 1000.0); + zVelSamples_ = new NavdataStampedSamples(-1000.0, 1000.0); + + altdCurve_.setData(altdSamples_); + xVelCurve_.setData(xVelSamples_); + yVelCurve_.setData(yVelSamples_); + zVelCurve_.setData(zVelSamples_); + + /* Setup plot grids */ + altdGrid_.setPen(QPen(Qt::darkGray, 0.25, Qt::DashLine)); + xVelGrid_.setPen(QPen(Qt::darkGray, 0.25, Qt::DashLine)); + yVelGrid_.setPen(QPen(Qt::darkGray, 0.25, Qt::DashLine)); + zVelGrid_.setPen(QPen(Qt::darkGray, 0.25, Qt::DashLine)); + + /* Setup plots */ + ui_.altdPlot->setAxisTitle(QwtPlot::yLeft, "Altitude (mm)"); + altdCurve_.attach(ui_.altdPlot); + altdGrid_.attach(ui_.altdPlot); + + ui_.xVelPlot->setAxisTitle(QwtPlot::yLeft, "X Velocity (mm/s)"); + xVelCurve_.attach(ui_.xVelPlot); + xVelGrid_.attach(ui_.xVelPlot); + + ui_.yVelPlot->setAxisTitle(QwtPlot::yLeft, "Y Velocity (mm/s)"); + yVelCurve_.attach(ui_.yVelPlot); + yVelGrid_.attach(ui_.yVelPlot); + + ui_.zVelPlot->setAxisTitle(QwtPlot::yLeft, "Z Velocity (mm/s)"); + zVelCurve_.attach(ui_.zVelPlot); + zVelGrid_.attach(ui_.zVelPlot); + + /* Setup replot timer */ + connect(&replotTimer_, SIGNAL(timeout()), this, SLOT(replot())); + + /* Setup compass */ + ui_.yawCompass->setScaleComponents(QwtAbstractScaleDraw::Backbone | + QwtAbstractScaleDraw::Ticks | QwtAbstractScaleDraw::Labels); + ui_.yawCompass->setScaleTicks(0, 0, 3); + + QMap<double, QString> map; + for (double d = 0.0; d < 360.0; d += 60.0) + { + QString label; + label.sprintf("%.0f", 360.0 - d); + map.insert(d, label); + } + ui_.yawCompass->setLabelMap(map); + ui_.yawCompass->setScale(36, 5, 0); + + ui_.yawCompass->setNeedle( + new QwtDialSimpleNeedle(QwtDialSimpleNeedle::Ray, true, Qt::gray)); + + /* Setup navball */ + navballScene_.addItem(&navball_); + + ui_.navballView->setStyleSheet("background-color: transparent"); + ui_.navballView->setScene(&navballScene_); + + /* Setup status panel */ + statusPanelScene_.addItem(&statusPanel_); + + ui_.statusPanelView->setStyleSheet("background-color: transparent"); + ui_.statusPanelView->setScene(&statusPanelScene_); + + + /* Subscribe to the required topics */ + updateSubscriptions(); + + /* Update the GUI upon receiving a new navdata packet */ + connect(this, SIGNAL(navdataChanged()), this, SLOT(update())); + + /* Start timer */ + replotTimer_.start(50); +} + +void Navdata::shutdownPlugin() +{ + /* Shutdown any subscribers / publishers */ + sub_navdata_.shutdown(); + + /* Disconnect all signals */ + disconnect(this, SIGNAL(navdataChanged()), this, SLOT(update())); + disconnect(&replotTimer_, SIGNAL(timeout()), this, SLOT(replot())); + + /* Detach plot items */ + altdCurve_.detach(); + xVelCurve_.detach(); + yVelCurve_.detach(); + zVelCurve_.detach(); + + altdGrid_.detach(); + xVelGrid_.detach(); + yVelGrid_.detach(); + zVelGrid_.detach(); + + /* Stop timer */ + replotTimer_.stop(); +} + +void Navdata::saveSettings(qt_gui_cpp::Settings& plugin_settings, qt_gui_cpp::Settings& instance_settings) const +{ + // TODO save intrinsic configuration, usually using: + // instance_settings.setValue(k, v) +} + +void Navdata::restoreSettings(const qt_gui_cpp::Settings& plugin_settings, const qt_gui_cpp::Settings& instance_settings) +{ + // TODO restore intrinsic configuration, usually using: + // v = instance_settings.value(k) +} + +void Navdata::updateSubscriptions() +{ + /* Subscribe to navdata topic */ + sub_navdata_ = getNodeHandle().subscribe<ardrone_autonomy::Navdata>( + "/ardrone/navdata", 1, &Navdata::receiveNavdata, this); +} + +void Navdata::receiveNavdata(ardrone_autonomy::Navdata::ConstPtr const& navdata) +{ + /* Store navdata and emit signal */ + navdata_ = *navdata; + + /* Update */ + emit navdataChanged(); +} + +void Navdata::update() +{ + /* Plots */ + altdSamples_->append(QPointF(navdata_.tm / 1e6, navdata_.altd)); + xVelSamples_->append(QPointF(navdata_.tm / 1e6, navdata_.vx)); + yVelSamples_->append(QPointF(navdata_.tm / 1e6, navdata_.vy)); + zVelSamples_->append(QPointF(navdata_.tm / 1e6, navdata_.vz)); + + /* Environment measurements */ + ui_.batteryBar->setValue(navdata_.batteryPercent); + ui_.pressureBar->setValue(navdata_.pressure / 1000.0); + ui_.temperatureBar->setValue(navdata_.temp); + + /* Roll, pitch, yaw */ + navball_.setRoll(navdata_.rotX); + navball_.setPitch(navdata_.rotY); + ui_.yawCompass->setValue(-navdata_.rotZ); + + /* Drone status */ + statusPanel_.setStatus((StatusPanel::DroneStatus) navdata_.state); +} + +void Navdata::replot() +{ + /* Replot everything */ + replot(ui_.altdPlot, altdSamples_); + replot(ui_.xVelPlot, xVelSamples_); + replot(ui_.yVelPlot, yVelSamples_); + replot(ui_.zVelPlot, zVelSamples_); + + /* Redraw everything */ + navballScene_.update(); + statusPanelScene_.update(); +} + +void Navdata::replot(QwtPlot * p, NavdataStampedSamples * s) +{ + /* Adjust axis scale and replot */ + + p->setAxisScale(QwtPlot::xBottom, + s->xMin(), + s->xMax()); + p->setAxisScale(QwtPlot::yLeft, + s->yMin(), + s->yMax()); + p->replot(); +} + + + +} // namespace + +PLUGINLIB_DECLARE_CLASS(rqt_ardrone, Navdata, rqt_ardrone::Navdata, rqt_gui_cpp::Plugin) diff --git a/pool/shard007/C++/0091888_GsCachedArea.cpp b/pool/shard007/C++/0091888_GsCachedArea.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a6ffee41b02c74359c1005d061bd5b144aff9227 --- /dev/null +++ b/pool/shard007/C++/0091888_GsCachedArea.cpp @@ -0,0 +1,100 @@ +#include <cassert> +#include "GsCachedArea.h" +#include "GsPixelFormats.h" + +static bool DoMemoryRangesOverlap(uint32 start1, uint32 size1, uint32 start2, uint32 size2) +{ + uint32 min1 = start1; + uint32 max1 = start1 + size1; + + uint32 min2 = start2; + uint32 max2 = start2 + size2; + + if(max1 < min2) return false; + if(min1 > max2) return false; + + return true; +} + +CGsCachedArea::CGsCachedArea() +{ + ClearDirtyPages(); +} + +void CGsCachedArea::SetArea(uint32 psm, uint32 bufPtr, uint32 bufWidth, uint32 height) +{ + m_psm = psm; + m_bufPtr = bufPtr; + m_bufWidth = bufWidth; + m_height = height; +} + +std::pair<uint32, uint32> CGsCachedArea::GetPageRect() const +{ + auto texturePageSize = CGsPixelFormats::GetPsmPageSize(m_psm); + uint32 pageCountX = (m_bufWidth + texturePageSize.first - 1) / texturePageSize.first; + uint32 pageCountY = (m_height + texturePageSize.second - 1) / texturePageSize.second; + return std::make_pair(pageCountX, pageCountY); +} + +uint32 CGsCachedArea::GetPageCount() const +{ + auto pageRect = GetPageRect(); + return pageRect.first * pageRect.second; +} + +uint32 CGsCachedArea::GetSize() const +{ + return GetPageCount() * CGsPixelFormats::PAGESIZE; +} + +void CGsCachedArea::Invalidate(uint32 memoryStart, uint32 memorySize) +{ + uint32 areaSize = GetSize(); + + if(DoMemoryRangesOverlap(memoryStart, memorySize, m_bufPtr, areaSize)) + { + //Find the pages that are touched by this transfer + uint32 pageStart = (memoryStart < m_bufPtr) ? 0 : ((memoryStart - m_bufPtr) / CGsPixelFormats::PAGESIZE); + uint32 pageCount = std::min<uint32>(GetPageCount(), (memorySize + CGsPixelFormats::PAGESIZE - 1) / CGsPixelFormats::PAGESIZE); + + for(unsigned int i = 0; i < pageCount; i++) + { + SetPageDirty(pageStart + i); + } + + //Wouldn't make sense to go through here and not have at least a dirty page + assert(HasDirtyPages()); + } +} + +bool CGsCachedArea::IsPageDirty(uint32 pageIndex) const +{ + assert(pageIndex < sizeof(m_dirtyPages) * 8); + unsigned int dirtyPageSection = pageIndex / (sizeof(m_dirtyPages[0]) * 8); + unsigned int dirtyPageIndex = pageIndex % (sizeof(m_dirtyPages[0]) * 8); + return (m_dirtyPages[dirtyPageSection] & (1ULL << dirtyPageIndex)) != 0; +} + +void CGsCachedArea::SetPageDirty(uint32 pageIndex) +{ + assert(pageIndex < sizeof(m_dirtyPages) * 8); + unsigned int dirtyPageSection = pageIndex / (sizeof(m_dirtyPages[0]) * 8); + unsigned int dirtyPageIndex = pageIndex % (sizeof(m_dirtyPages[0]) * 8); + m_dirtyPages[dirtyPageSection] |= (1ULL << dirtyPageIndex); +} + +bool CGsCachedArea::HasDirtyPages() const +{ + DirtyPageHolder dirtyStatus = 0; + for(unsigned int i = 0; i < MAX_DIRTYPAGES_SECTIONS; i++) + { + dirtyStatus |= m_dirtyPages[i]; + } + return (dirtyStatus != 0); +} + +void CGsCachedArea::ClearDirtyPages() +{ + memset(m_dirtyPages, 0, sizeof(m_dirtyPages)); +} diff --git a/pool/shard007/C++/0091898_skinreader.cpp b/pool/shard007/C++/0091898_skinreader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..03d7407fa996b20b6fc16f9968bdea30e9daed7c --- /dev/null +++ b/pool/shard007/C++/0091898_skinreader.cpp @@ -0,0 +1,184 @@ +/*************************************************************************** + * This file is based on qmmp source file * + * src/plugins/Ui/skinned/skinreader.cpp * + * which is * + * Copyright (C) 2007-2016 by Ilya Kotov * + * forkotov02@hotmail.ru * + ***************************************************************************/ + +#include <QDir> +#include <QList> +#include <QFileInfo> +#include <QProcess> +#include <QByteArray> +#include <QApplication> +#include <QFile> +#include <qmmp/qmmp.h> +#include "skinreader.h" + +SkinReader::SkinReader(QObject *parent) + : QObject(parent) +{ + m_process = new QProcess(this); + //create cache dir + QDir dir(Qmmp::configDir()); + dir.mkdir("cache"); + dir.cd("cache"); + dir.mkdir("thumbs"); + dir.mkdir("skin"); +} + +void SkinReader::generateThumbs() +{ + m_previewMap.clear(); + QDir dir(Qmmp::configDir() + "skins"); + dir.setFilter( QDir::Files | QDir::Hidden | QDir::NoSymLinks); + QFileInfoList f = dir.entryInfoList(); +#if defined(Q_OS_WIN) && !defined(Q_OS_CYGWIN) + dir.setPath(qApp->applicationDirPath()+"/skins"); +#else + dir.setPath(qApp->applicationDirPath()+"/../share/qmmp/skins"); +#endif + dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks); + f << dir.entryInfoList(); + QDir cache_dir(Qmmp::configDir() + "cache/thumbs"); + cache_dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks); + QFileInfoList d = cache_dir.entryInfoList(); + //clear removed skins from cache + foreach(QFileInfo thumbFile, d) { + bool del = true; + foreach(QFileInfo fileInfo, f) { + if (fileInfo.baseName () == thumbFile.baseName ()) + { + del = false; + break; + } + } + if (del) { + qDebug("SkinReader: deleting %s from cache", + qPrintable(thumbFile.fileName ())); + + cache_dir.remove(thumbFile.fileName ()); + } + } + //add new skins to cache + foreach(QFileInfo fileInfo, f) + { + bool create = true; + foreach(QFileInfo thumbInfo, d) { + if (fileInfo.baseName () == thumbInfo.baseName ()) { + create = false; + break; + } + } + if (create) { + qDebug("SkinReader: adding %s to cache", + qPrintable(fileInfo.fileName ())); + QString name = fileInfo.fileName ().toLower(); + + if (name.endsWith(".tgz") || name.endsWith(".tar.gz") || name.endsWith(".tar.bz2")) + untar(fileInfo.filePath (), cache_dir.absolutePath (), true); + else if (name.endsWith(".zip") || name.endsWith(".wsz")) + unzip(fileInfo.filePath (), cache_dir.absolutePath (), true); + } + } + //add thumbs to map + cache_dir.refresh(); + d = cache_dir.entryInfoList(); + foreach(QFileInfo fileInfo, f) { + foreach(QFileInfo thumbInfo, d) + { + if (fileInfo.baseName () == thumbInfo.baseName ()) + { + m_previewMap.insert(fileInfo.absoluteFilePath (), + thumbInfo.absoluteFilePath ()); + break; + } + } + } +} + +void SkinReader::unpackSkin(const QString &path) +{ + //remove old skin + QDir dir(Qmmp::configDir() + "cache/skin"); + dir.setFilter( QDir::Files | QDir::Hidden | QDir::NoSymLinks); + QFileInfoList f = dir.entryInfoList(); + foreach(QFileInfo file, f) + dir.remove(file.fileName()); + //unpack + QString name = QFileInfo(path).fileName().toLower(); + if (name.endsWith(".tgz") || name.endsWith(".tar.gz") || name.endsWith(".tar.bz2")) + untar(path, Qmmp::configDir() + "cache/skin", false); + else if (name.endsWith(".zip") || name.endsWith(".wal")) + unzip(path, Qmmp::configDir() + "cache/skin", false); +} + +const QStringList SkinReader::skins() +{ + return m_previewMap.keys(); +} + +const QPixmap SkinReader::getPreview(const QString &skinPath) +{ + return QPixmap(m_previewMap.value(skinPath)); +} + +void SkinReader::untar(const QString &from, const QString &to, bool preview) +{ + QByteArray array; + QStringList args; + //list archive + args << "tf" <<from; + m_process->start("tar", args); + m_process->waitForFinished(); + array = m_process->readAllStandardOutput (); + QString str = QString(array); + QStringList outputList = str.split("\n", QString::SkipEmptyParts); + foreach(QString str, outputList) { + str = str.trimmed(); + args.clear(); + if (!preview || (str.contains("/main.", Qt::CaseInsensitive) + || str.startsWith("main.", Qt::CaseInsensitive))) { + args << "xvfk" << from << "-O" << str; + m_process->start("tar", args); + m_process->waitForStarted(); + m_process->waitForFinished(); + array = m_process->readAllStandardOutput (); + + QString name; + if (preview) + name = from.section('/',-1) + (".") + str.section('.', -1); + else + name = str.contains('/') ? str.section('/',-1).toLower() : str.toLower(); + + QFile file(to+"/"+name); + file.open(QIODevice::WriteOnly); + file.write(array); + file.close(); + } + } +} + +void SkinReader::unzip(const QString &from, const QString &to, bool preview) +{ + QStringList args; + if (preview) { + args << "-C" << "-o" << "-qq" << "-d" << to << from << "main.*" << "*/main.*"; + QProcess::execute("unzip", args); + QDir dir(to); + dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks); + QFileInfoList fileList = dir.entryInfoList(); + foreach(QFileInfo thumbInfo, fileList) + { + if (thumbInfo.fileName().startsWith("main.", Qt::CaseInsensitive)) + { + dir.rename(thumbInfo.fileName(), from.section('/', -1) + + "." + thumbInfo.suffix ()); + } + } + } else { + args << "-o" << "-qq" << "-d" << to << from; + QProcess::execute("unzip", args); + } +} diff --git a/pool/shard007/C++/0091909_traffic_light_protected_scenario.cc b/pool/shard007/C++/0091909_traffic_light_protected_scenario.cc new file mode 100644 index 0000000000000000000000000000000000000000..c935b9c9a6ba088fdd26e8f64a43ee90af0c282a --- /dev/null +++ b/pool/shard007/C++/0091909_traffic_light_protected_scenario.cc @@ -0,0 +1,126 @@ +/****************************************************************************** + * Copyright 2018 The Apollo 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. + *****************************************************************************/ + +/** + * @file + **/ + +#include "modules/planning/scenarios/traffic_light/protected/traffic_light_protected_scenario.h" + +#include "modules/planning/proto/planning_config.pb.h" + +#include "cyber/common/log.h" +#include "modules/planning/common/frame.h" +#include "modules/planning/common/planning_context.h" +#include "modules/planning/scenarios/traffic_light/protected/stage_approach.h" +#include "modules/planning/scenarios/traffic_light/protected/stage_intersection_cruise.h" + +namespace apollo { +namespace planning { +namespace scenario { +namespace traffic_light { + +using hdmap::HDMapUtil; +using perception::TrafficLight; + +void TrafficLightProtectedScenario::Init() { + if (init_) { + return; + } + + Scenario::Init(); + + if (!GetScenarioConfig()) { + AERROR << "fail to get scenario specific config"; + return; + } + + if (PlanningContext::GetScenarioInfo() + ->current_traffic_light_overlaps.empty()) { + AERROR << "Could not find traffic-light(s)"; + return; + } + + for (const auto& traffic_light_overlap : + PlanningContext::GetScenarioInfo()->current_traffic_light_overlaps) { + const std::string traffic_light_overlap_id = + traffic_light_overlap.object_id; + hdmap::SignalInfoConstPtr traffic_light = + HDMapUtil::BaseMap().GetSignalById( + hdmap::MakeMapId(traffic_light_overlap_id)); + if (!traffic_light) { + AERROR << "Could not find traffic light: " << traffic_light_overlap_id; + } + } + + init_ = true; +} + +apollo::common::util::Factory< + ScenarioConfig::StageType, Stage, + Stage* (*)(const ScenarioConfig::StageConfig& stage_config)> + TrafficLightProtectedScenario::s_stage_factory_; + +void TrafficLightProtectedScenario::RegisterStages() { + if (!s_stage_factory_.Empty()) { + s_stage_factory_.Clear(); + } + s_stage_factory_.Register( + ScenarioConfig::TRAFFIC_LIGHT_PROTECTED_APPROACH, + [](const ScenarioConfig::StageConfig& config) -> Stage* { + return new TrafficLightProtectedStageApproach(config); + }); + s_stage_factory_.Register( + ScenarioConfig::TRAFFIC_LIGHT_PROTECTED_INTERSECTION_CRUISE, + [](const ScenarioConfig::StageConfig& config) -> Stage* { + return new TrafficLightProtectedStageIntersectionCruise(config); + }); +} + +std::unique_ptr<Stage> TrafficLightProtectedScenario::CreateStage( + const ScenarioConfig::StageConfig& stage_config) { + if (s_stage_factory_.Empty()) { + RegisterStages(); + } + auto ptr = s_stage_factory_.CreateObjectOrNull(stage_config.stage_type(), + stage_config); + if (ptr) { + ptr->SetContext(&context_); + } + return ptr; +} + +bool TrafficLightProtectedScenario::IsTransferable( + const Scenario& current_scenario, const Frame& frame) { + return false; +} + +/* + * read scenario specific configs and set in context_ for stages to read + */ +bool TrafficLightProtectedScenario::GetScenarioConfig() { + if (!config_.has_traffic_light_protected_config()) { + AERROR << "miss scenario specific config"; + return false; + } + context_.scenario_config.CopyFrom(config_.traffic_light_protected_config()); + return true; +} + +} // namespace traffic_light +} // namespace scenario +} // namespace planning +} // namespace apollo diff --git a/pool/shard007/C++/0091911_compatibilityutils.test.cpp b/pool/shard007/C++/0091911_compatibilityutils.test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6b027722d5aa2e3679ef383c2756c997c534d05f --- /dev/null +++ b/pool/shard007/C++/0091911_compatibilityutils.test.cpp @@ -0,0 +1,74 @@ +// ************************************************************************************************ +// +// qt-mvvm: Model-view-view-model framework for large GUI applications +// +//! @file mvvm/tests/testmodel/compatibilityutils.test.cpp +//! @brief Implements class CLASS? +//! +//! @homepage http://www.bornagainproject.org +//! @license GNU General Public License v3 or higher (see COPYING) +//! @copyright Forschungszentrum Jülich GmbH 2020 +//! @authors Gennady Pospelov et al, Scientific Computing Group at MLZ (see CITATION, AUTHORS) +// +// ************************************************************************************************ + +#include "google_test.h" +#include "mvvm/model/groupitem.h" +#include "mvvm/model/mvvm_types.h" +#include "mvvm/model/propertyitem.h" +#include "mvvm/model/sessionitemcontainer.h" +#include "mvvm/model/sessionitemdata.h" +#include "mvvm/serialization/compatibilityutils.h" + +using namespace ModelView; + +//! Test of CompatibilityUtilsTest. + +class CompatibilityUtilsTest : public ::testing::Test { +public: + ~CompatibilityUtilsTest(); +}; + +CompatibilityUtilsTest::~CompatibilityUtilsTest() = default; + +//! Testing IsCompatibleSingleProperty. + +TEST_F(CompatibilityUtilsTest, IsCompatibleSinglePropertyTag) +{ + TagInfo tag = TagInfo::propertyTag("thickness", Constants::PropertyType); + SessionItemContainer container(tag); + + // to be compatible, container should have PropertyItem in it already + EXPECT_FALSE(Compatibility::IsCompatibleSinglePropertyTag(container, tag)); + + EXPECT_TRUE(container.insertItem(new PropertyItem, 0)); + EXPECT_TRUE(Compatibility::IsCompatibleSinglePropertyTag(container, tag)); +} + +//! Testing IsCompatibleSingleProperty. + +TEST_F(CompatibilityUtilsTest, IsCompatibleUniversalTag) +{ + TagInfo tag = TagInfo::universalTag("layers"); + SessionItemContainer container(tag); + + // to be compatible, container should be empty + EXPECT_TRUE(Compatibility::IsCompatibleUniversalTag(container, tag)); + + EXPECT_TRUE(container.insertItem(new PropertyItem, 0)); + EXPECT_FALSE(Compatibility::IsCompatibleUniversalTag(container, tag)); +} + +//! Testing IsCompatibleSingleProperty. + +TEST_F(CompatibilityUtilsTest, IsCompatibleGroupTag) +{ + TagInfo tag = TagInfo::universalTag(GroupItem::T_GROUP_ITEMS); + SessionItemContainer container(tag); + + // to be compatible, container should be non-empty + EXPECT_FALSE(Compatibility::IsCompatibleGroupTag(container, tag)); + + EXPECT_TRUE(container.insertItem(new PropertyItem, 0)); + EXPECT_TRUE(Compatibility::IsCompatibleGroupTag(container, tag)); +} diff --git a/pool/shard007/C++/0091915_ppm_view.cc b/pool/shard007/C++/0091915_ppm_view.cc new file mode 100644 index 0000000000000000000000000000000000000000..ace6b21050828b47fcf2700a33244098281df6c9 --- /dev/null +++ b/pool/shard007/C++/0091915_ppm_view.cc @@ -0,0 +1,94 @@ +// ppm_view.cc +// viewer and translator for ppm images +// Copyright (c) 2014 John K. Johnstone + +#include <fstream> +using namespace std; + +#include "miscellany.h" // GetSuffix, ChangeSuffixPlusDot +#include "ppm.h" // ReadPPM, WritePPM, FlipPPMforOpenGL +#include "viewer.h" +using namespace pierre; + +static void Usage() +{ + cout + << "view an image in ppm format" << endl << endl + << " -a: output original image in ascii ppm format" << endl + << " -r: output original image in raw ppm format" << endl + << " -g: output as grayscale image, in raw ppm format" << endl + << " -b: output as bitmap using 3x3 dithering, in raw ppm format" << endl + << endl + << "input: foo.ppm" << endl + << "output (potential): foo_P3.ppm, foo_P6.ppm, foo_gray.ppm OR foo_bitmap.ppm" << endl; + exit(-1); +} + +int main (int argc, char **argv) +{ + bool output_ascii = 0; + bool output_raw = 0; + bool output_gray = 0; + bool output_bitmap = 0; + if (argc == 1) Usage(); + int args_parsed = 1; + while (args_parsed < argc) + { + if ('-' == argv[args_parsed][0]) + switch (argv[args_parsed++][1]) + { + case 'a': output_ascii = 1; break; + case 'r': output_raw = 1; break; + case 'g': output_gray = 1; break; + case 'b': output_bitmap = 1; break; + case 'h': + default: Usage(); break; + } + else args_parsed++; + } + + string ppmName = argv[argc-1]; + string suffix; GetSuffix (ppmName, suffix); assert (suffix=="ppm"); + + Viewer viewer; + ifstream infile (argv[argc-1]); + ReadPPM (infile, viewer.img_); + + // stub to be completed by 470/670 teams + 770: + // create grayscale PPM image in viewer.img_gray_ + + // stub to be completed only by 670 teams + 770: + // create bitmap PPM image in viewer.img_dither_ + + if (output_ascii) + { + // stub to be completed by everyone + ; + } + else if (output_raw) + { + suffix = "_P6.ppm"; + ChangeSuffixPlusDot (ppmName, suffix); + ofstream outfile (ppmName.c_str()); + WritePPM (viewer.img_, outfile, 0); + } + else if (output_gray) + { + // stub to be completed by all x70 students : + // output the grayscale image, named foo_gray.ppm + ; + } + else if (output_bitmap) + { + // stub to be completed by 670 and 770 students + // output the bitmap image, named foo_bitmap.ppm + ; + } + FlipPPMforOpenGL (viewer.img_); + /* uncomment once these images are generated + FlipPPMforOpenGL (viewer.img_gray_); + FlipPPMforOpenGL (viewer.img_dither_); + */ + viewer.init (argv[argc-1]); + return 0; +} diff --git a/pool/shard007/C++/0091922_LibCurlFtp.cpp b/pool/shard007/C++/0091922_LibCurlFtp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0ec4d054a4ba832a78be7c92adce7613baa2e252 --- /dev/null +++ b/pool/shard007/C++/0091922_LibCurlFtp.cpp @@ -0,0 +1,163 @@ +#include "LibCurlFtp.h" +#include <QDataStream> +#include <stdio.h> + + +static bool compareCFileInfo(const CFileInfo &f1, const CFileInfo &f2) +{ + return f1.path.length() > f2.path.length(); + +} + +CFtp::CFtp() +{ + + +} + +CFtp::~CFtp() +{ + +} + +int CFtp::mkdir(const QString &dir) +{ + return 0; +} + +int CFtp::put(const QString & localFile, const QString & remoteFile, const QString &suffix /*= QString(".tmp")*/, TransferType type /*= Binary*/) +{ + QString filename, url; + if (remoteFile.startsWith("/")) + { + filename = remoteFile.split("/").last(); + QString dir = remoteFile.mid(0, remoteFile.lastIndexOf("/")); + url = makeUrl2(dir); + } + else + { + filename = remoteFile; + url = makeUrl2(""); + } + + + + QString cmdTmpName = "RNFR " + filename + suffix; + QString cmdOrgName = "RNTO " + filename; + QString strUrl = url + filename + suffix; + //strUrl += filename + sendsuffix; + struct curl_slist *headerlist = NULL; + headerlist = curl_slist_append(headerlist, cmdTmpName.toLocal8Bit().toStdString().c_str()); + headerlist = curl_slist_append(headerlist, cmdOrgName.toLocal8Bit().toStdString().c_str()); + m_iRetCode = curl_easy_setopt(m_pCurlHandler, CURLOPT_UPLOAD, 1); + ////////////////////////////////////////////////////////////////////////// + // ¶ÏµãÐø´« + std::FILE *pfile = fopen(localFile.toLocal8Bit().toStdString().c_str(), "rb"); + if (pfile == NULL) + { + QSLOG_ERROR(QString("open file %1 failure").arg(localFile)); + return -1; + } + QSharedPointer<std::FILE> autoclose(pfile, fclose); + double size = getFileSize(remoteFile); + fseek(pfile,0 , SEEK_END); + long fileLen = ftell(pfile); + if (size != double(-1.0) ) + { + if ((long)size != fileLen) + { + if (0 != remove(remoteFile)) + { + QSLOG_ERROR(errorString()); + } + } + else + { + // ÎļþÒѾ­´æÔÚ + return m_iRetCode; + } + } + fseek(pfile, 0, SEEK_SET); + + + m_iRetCode = curl_easy_setopt(m_pCurlHandler, CURLOPT_APPEND, 0); + m_iRetCode = curl_easy_setopt(m_pCurlHandler, CURLOPT_URL, strUrl.toLocal8Bit().toStdString().c_str()); + m_iRetCode = curl_easy_setopt(m_pCurlHandler, CURLOPT_FTP_CREATE_MISSING_DIRS, 1); + m_iRetCode = curl_easy_setopt(m_pCurlHandler, CURLOPT_READDATA, pfile); + m_iRetCode = curl_easy_setopt(m_pCurlHandler, CURLOPT_READFUNCTION, ReadFromFile); + m_iRetCode = curl_easy_setopt(m_pCurlHandler, CURLOPT_POSTQUOTE, headerlist); + m_iRetCode = curl_easy_perform(m_pCurlHandler); + curl_slist_free_all(headerlist); + return m_iRetCode; +} + +int CFtp::put(const QByteArray & data, const QString & file, TransferType type /*= Binary*/) +{ + return 0; +} + +int CFtp::rename(const QString &oldname, const QString &newname) +{ + return 0; +} + + +int CFtp::remove(const QString &file) +{ + QString filename, url; + if (file.startsWith("/")) + { + filename = file.split("/").last(); + QString dir = file.mid(0, file.lastIndexOf("/")); + url = makeUrl2(dir); + } + else + { + filename = file; + url = makeUrl2(""); + } + + QString szCmd = QString("DELE %1").arg(filename); + //m_iRetCode = curl_easy_setopt(m_pCurlHandler, CURLOPT_URL, url); + struct curl_slist *headerlist = NULL; + headerlist = curl_slist_append(headerlist, szCmd.toLocal8Bit().toStdString().c_str()); + m_iRetCode = curl_easy_setopt(m_pSecCurlHandler, CURLOPT_POSTQUOTE, headerlist); + m_iRetCode = curl_easy_setopt(m_pSecCurlHandler, CURLOPT_URL, url.toLocal8Bit().toStdString().c_str()); + prepare(); + m_iRetCode = curl_easy_perform(m_pSecCurlHandler); + curl_slist_free_all(headerlist); + return m_iRetCode; +} + + +int CFtp::rmdir(const QString &dir) +{ + QString dirname, url; + //if (dir.startsWith("/")) + //{ + // dirname = dir.split("/").last(); + // QString dir = dir.mid(0, dir.lastIndexOf("/")); + // url = makeUrl(dir); + //} + //else + { + dirname = dir; + url = makeUrl2(""); + } + QString szCmd = QString("RMD %1").arg(dirname); + //m_iRetCode = curl_easy_setopt(m_pCurlHandler, CURLOPT_URL, url); + struct curl_slist *headerlist = NULL; + headerlist = curl_slist_append(headerlist, szCmd.toLocal8Bit().toStdString().c_str()); + m_iRetCode = curl_easy_setopt(m_pSecCurlHandler, CURLOPT_POSTQUOTE, headerlist); + m_iRetCode = curl_easy_setopt(m_pSecCurlHandler, CURLOPT_URL, url.toLocal8Bit().toStdString().c_str()); + prepare(); + m_iRetCode = curl_easy_perform(m_pSecCurlHandler); + curl_slist_free_all(headerlist); + return m_iRetCode; +} + +QString CFtp::makeUrl(const QString &host, quint16 port) +{ + m_urlBody.append(QString("ftp://%1:%2").arg(host).arg(port)); + return makeUrl2(""); +} \ No newline at end of file diff --git a/pool/shard007/C++/0091930_CSVFileAdapter.cpp b/pool/shard007/C++/0091930_CSVFileAdapter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..908d00688aa8de94bfd1500e98cccc2fc4cb0e8e --- /dev/null +++ b/pool/shard007/C++/0091930_CSVFileAdapter.cpp @@ -0,0 +1,23 @@ +#include "CSVFileAdapter.h" + +namespace OpenSim { + +CSVFileAdapter::CSVFileAdapter() : + DelimFileAdapter(",", // delimiter for read + "," // delimiter for write + ) {} + +CSVFileAdapter* +CSVFileAdapter::clone() const { + return new CSVFileAdapter{*this}; +} + +void +CSVFileAdapter::write(const TimeSeriesTable& table, + const std::string& fileName) { + InputTables tables{}; + tables.emplace(tableString(), &table); + CSVFileAdapter{}.extendWrite(tables, fileName); +} + +} diff --git a/pool/shard007/C++/0091933_test_image_json.cpp b/pool/shard007/C++/0091933_test_image_json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2cb6b2897bbf914c9140f17caec63baa9d3fb4ca --- /dev/null +++ b/pool/shard007/C++/0091933_test_image_json.cpp @@ -0,0 +1,33 @@ +#include <stdio.h> +#include <stdlib.h> +#include <topshop/ImageJSON.h> + +#define ROXLU_USE_LOG +#define ROXLU_IMPLEMENTATION +#include <tinylib.h> + +int main() { + + printf("\n\ntest_image_json\n\n"); + rx_log_init(); + + top::ImageJSON img_json; + top::ImageInfo img_info; + std::string filepath; + + double now = rx_hrtime(); + filepath = rx_get_exe_path() +"/../data/test/image.json"; + if (0 != img_json.parse(filepath, img_info)) { + printf("Error: cannot parse the json.\n"); + exit(EXIT_FAILURE); + } + + printf("\n-----------------------------------------------\n"); + printf("+ username: %s\n", img_info.username.c_str()); + printf("-----------------------------------------------\n"); + printf("+ took: %f ms\n", (double(rx_hrtime()) - now)/10e6); + printf("-----------------------------------------------\n"); + + printf("\n"); + return 0; +} diff --git a/pool/shard007/C++/0091937_async_connection.cpp b/pool/shard007/C++/0091937_async_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..72c95364bf72af07b2a2d2e0ee0fcf0268e1b535 --- /dev/null +++ b/pool/shard007/C++/0091937_async_connection.cpp @@ -0,0 +1,130 @@ +#include <libdariadb/utils/exception.h> +#include <cassert> +#include <common/async_connection.h> +#include <functional> + +using namespace std::placeholders; + +using namespace boost::asio; + +using namespace dariadb; +using namespace dariadb::net; + +AsyncConnection::AsyncConnection(NetData_Pool *pool, onDataRecvHandler onRecv, + onNetworkErrorHandler onErr) { + _pool = pool; + _async_con_id = 0; + _messages_to_send = 0; + _is_stoped = true; + _on_recv_hadler = onRecv; + _on_error_handler = onErr; +} + +AsyncConnection::~AsyncConnection() noexcept(false) { + full_stop(); +} + +void AsyncConnection::set_pool(NetData_Pool *pool) { + _pool = pool; +} + +void AsyncConnection::start(const socket_ptr &sock) { + if (!_is_stoped) { + return; + } + _sock = sock; + _is_stoped = false; + _begin_stoping_flag = false; + readNextAsync(); +} + +void AsyncConnection::mark_stoped() { + _begin_stoping_flag = true; +} + +void AsyncConnection::full_stop() { + mark_stoped(); + try { + if (auto spt = _sock.lock()) { + if (spt->is_open()) { + spt->close(); + } + } + } catch (...) { + } +} + +void AsyncConnection::send(const NetData_ptr &d) { + if (!_begin_stoping_flag) { + auto ptr = shared_from_this(); + + auto ds = d->as_buffer(); + auto send_buffer = std::get<1>(ds); + auto send_buffer_size = std::get<0>(ds); + + if (auto spt = _sock.lock()) { + _messages_to_send++; + auto buf = buffer(send_buffer, send_buffer_size); + async_write(*spt.get(), buf, [ptr, d](auto err, auto read_bytes) { + // logger("AsyncConnection::onDataSended #", _async_con_id, " readed ", + // read_bytes); + ptr->_messages_to_send--; + assert(ptr->_messages_to_send >= 0); + if (err) { + ptr->_on_error_handler(err); + } + ptr->_pool->free(d); + }); + } + } +} + +void AsyncConnection::readNextAsync() { + using boost::system::error_code; + if (auto spt = _sock.lock()) { + auto ptr = shared_from_this(); + NetData_ptr d = this->_pool->construct(); + async_read(*spt.get(), buffer((uint8_t *)(&d->size), MARKER_SIZE), + [ptr, d, spt](auto err, auto read_bytes) { + if (err) { + if (err == boost::asio::error::operation_aborted) { + return; + } + ptr->_on_error_handler(err); + } else { + if (read_bytes != MARKER_SIZE) { + THROW_EXCEPTION("exception on async readMarker. #", + ptr->_async_con_id, + " - wrong marker size: expected ", MARKER_SIZE, + " readed ", read_bytes); + } + auto buf = buffer((uint8_t *)(&d->data), d->size); + async_read(*spt.get(), buf, [ptr, d](auto err, auto read_bytes) { + // logger("AsyncConnection::onReadData #", _async_con_id, + // " + // readed ", read_bytes); + if (err) { + ptr->_on_error_handler(err); + } else { + bool cancel_flag = false; + bool dont_free_mem = false; + try { + ptr->_on_recv_hadler(d, cancel_flag, dont_free_mem); + } catch (std::exception &ex) { + THROW_EXCEPTION("exception on async readData. #", + ptr->_async_con_id, " - ", ex.what()); + } + + if (!dont_free_mem) { + ptr->_pool->free(d); + } + + if (!cancel_flag) { + ptr->readNextAsync(); + } + } + }); + } + }); + } +} diff --git a/pool/shard007/C++/0091940_Prim_s_algorithm.cpp b/pool/shard007/C++/0091940_Prim_s_algorithm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..efcf662c8268dd50e8069dd025f504eece27eb1e --- /dev/null +++ b/pool/shard007/C++/0091940_Prim_s_algorithm.cpp @@ -0,0 +1,135 @@ +#include <iostream> +#include <map> +#include <set> +#include <queue> +#include <vector> +#include <functional> +#include <limits> + +using namespace std; + +class AdjacencyList { +public: + + AdjacencyList() = default; + + ~AdjacencyList() = default; + + void insertVertex(int vertex) { + if (vertices.find(vertex) == vertices.end()) + vertices[vertex] = set < int > {}; + } + + void insertEdge(int u, int v, int weight = 1) { + if (vertices.find(u) != vertices.end()) { + vertices[u].insert(v); + if (weights.find(make_pair(u, v)) == weights.end()) + weights[make_pair(u, v)] = weight; + } else { + vertices[u] = set < int > {v}; + weights[make_pair(u, v)] = weight; + } + insertVertex(v); + } + + void insertBidirectionalEdge(int u, int v, int weight = 1) { + insertEdge(u, v, weight); + insertEdge(v, u, weight); + } + + void printList() { + for (auto vertex: vertices) { + cout << vertex.first << ": "; + for (auto adjacent: vertex.second) + cout << adjacent << " "; + cout << endl; + } + } + + void printWeights() { + for (auto edge: weights) { + cout << edge.first.first << " -> " << edge.first.second << " = " << edge.second << endl; + } + } + + void updateWeight(int u, int v, int weight) { + auto edge = make_pair(u, v); + if (weights.find(edge) != weights.end()) + weights[edge] = weight; + } + + void prim(int vertex) { + if (vertices.find(vertex) == vertices.end()) + cout << "Vertex v doesnt exist in the graph"; + else { + auto cmp = [](const pair<int, int> &a, const pair<int, int> &b) { + return a.second > b.second; + }; + + map<int, int> distances; + for (auto vertex : vertices) + distances[vertex.first] = numeric_limits<int>::max(); + distances[vertex] = 0; + + loadUnvisitedVertices(); + + priority_queue < pair < int, int >, vector < pair < int, int >>, decltype(cmp) > priorityQueue(cmp); + auto firstPair = make_pair(vertex, 0); + priorityQueue.push(firstPair); + + while (!priorityQueue.empty()) { + auto currentPair = priorityQueue.top(); + priorityQueue.pop(); + + int currentVertex = currentPair.first; + int currentDistance = currentPair.second; + unvisitedVertices[currentVertex] = true; + + if (distances[currentVertex] >= currentDistance) { + auto adjacentVertices = vertices[currentVertex]; + for (auto adjacent : adjacentVertices) { + if (unvisitedVertices[adjacent]) + continue; + + int currentWeight = weights[make_pair(currentVertex, adjacent)]; + if (currentWeight < distances[adjacent]) { + distances[adjacent] = currentWeight; + priorityQueue.push(make_pair(adjacent, distances[adjacent])); + } + } + } + } + + for (auto destination : distances) + cout << "From vertex " << vertex << " to vertex " << destination.first << " : " << destination.second + << endl; + } + } + +private: + + map<int, set<int> > vertices; + + map<int, bool> unvisitedVertices; + + map<pair<int, int>, int> weights; + + void loadUnvisitedVertices() { + if (!unvisitedVertices.empty()) + unvisitedVertices.clear(); + for (auto vertex: vertices) { + unvisitedVertices[vertex.first] = false; + } + } + +}; + +int main() { + AdjacencyList list = AdjacencyList(); + list.insertBidirectionalEdge(1, 2, 2); + list.insertBidirectionalEdge(2, 5, 3); + list.insertBidirectionalEdge(5, 4, 5); + list.prim(1); + return 0; +} + diff --git a/pool/shard007/C++/0091944_PageBase.cpp b/pool/shard007/C++/0091944_PageBase.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3cdb55653afce6b32797c68b0affb4bf0900bdee --- /dev/null +++ b/pool/shard007/C++/0091944_PageBase.cpp @@ -0,0 +1,110 @@ +// PageBase.cpp : ʵÏÖÎļþ +// + +#include "stdafx.h" +//#include "FxClient.h" +#include "PageBase.h" +#include "afxdialogex.h" + + +// CPageBase ¶Ô»°¿ò + +IMPLEMENT_DYNAMIC(CPageBase, CDialog) + +CPageBase::CPageBase(UINT nDlgID, CWnd* pParent /*=NULL*/) + : CDialog(nDlgID, pParent) + , m_pszTitle(NULL) +{ + +} + +CPageBase::~CPageBase() +{ + if(m_pszTitle!=NULL) delete [] m_pszTitle; +} + +void CPageBase::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); +} + + +BEGIN_MESSAGE_MAP(CPageBase, CDialog) + ON_WM_PAINT() +END_MESSAGE_MAP() + + +// CPageBase ÏûÏ¢´¦Àí³ÌÐò + + +BOOL CPageBase::OnInitDialog() +{ + CDialog::OnInitDialog(); + + //³õʼ»¯Ò³ÃæÊÓͼλÖà + CRect rect; + GetWindowRect(&rect); + MoveWindow(212, 12, rect.Width(), rect.Height());//ÒÆ¶¯×Ó´°¿ÚλÖà + + //×ÖÌå³õʼ»¯ + memset(&m_lfBaseFont, 0, sizeof(m_lfBaseFont)); + lstrcpy(m_lfBaseFont.lfFaceName, _T("ºÚÌå")); + m_lfBaseFont.lfHeight = 14; + m_lfBaseFont.lfWidth=0; + m_lfBaseFont.lfWeight = FW_NORMAL; + m_lfBaseFont.lfItalic = FALSE; + m_lfBaseFont.lfEscapement=0; + m_lfBaseFont.lfOrientation=0; + m_lfBaseFont.lfStrikeOut=0; + m_lfBaseFont.lfUnderline=0; + m_lfBaseFont.lfCharSet = DEFAULT_CHARSET; + m_lfBaseFont.lfOutPrecision = OUT_DEFAULT_PRECIS; + m_lfBaseFont.lfClipPrecision = CLIP_DEFAULT_PRECIS; + m_lfBaseFont.lfQuality = DEFAULT_QUALITY; + m_lfBaseFont.lfPitchAndFamily = FIXED_PITCH; + + return TRUE; // return TRUE unless you set the focus to a control + // Òì³£: OCX ÊôÐÔÒ³Ó¦·µ»Ø FALSE +} + + +void CPageBase::OnPaint() +{ + CPaintDC dc(this); + + //Ìî³ä±êÌâÀ¸±³¾° + CRect rcWnd; + GetClientRect(&rcWnd); + CRect rcTitle(1,1,rcWnd.right-1,rcWnd.top+25); + dc.FillSolidRect(&rcTitle,RGB(46,64,94)); + + //»æÖƱêÌâ + if(m_pszTitle!=NULL) + { + CFont font; + font.CreateFontIndirect(&m_lfBaseFont); + CFont * pOldFont=dc.SelectObject(&font); + int nOldBkMod=dc.SetBkMode(TRANSPARENT); + DWORD dwOldTxtColor=dc.SetTextColor(RGB(255,255,255)); + + CSize cz=dc.GetTextExtent(m_pszTitle); + int nTitleL=4; + int nTitleT=(24-cz.cy)/2+1; + dc.TextOut(nTitleL,nTitleT,m_pszTitle,_tcslen(m_pszTitle)); + + dc.SetTextColor(dwOldTxtColor); + dc.SetBkMode(nOldBkMod); + dc.SelectObject(pOldFont); + } +} + +//ÉèÖñêÌâÀ¸Îı¾ +void CPageBase::SetTitle(LPTSTR pszTitle) +{ + int nLen=_tcslen(pszTitle); + m_pszTitle=new TCHAR[nLen+1]; + _tcscpy(m_pszTitle,pszTitle); + m_pszTitle[nLen]=_T('\0'); + + Invalidate(); +} diff --git a/pool/shard007/C++/0091953_local_color_node.cpp b/pool/shard007/C++/0091953_local_color_node.cpp new file mode 100644 index 0000000000000000000000000000000000000000..81435cdb985e0bcb3b4db313e6ac58b1a849f07f --- /dev/null +++ b/pool/shard007/C++/0091953_local_color_node.cpp @@ -0,0 +1,73 @@ +/** + * This class subscribes to: + * /detected_ent_img + * and publishes an array of color info of detected entities + * /local_feat/color + * + * The published msg is the same using colorInfo.msg + * mean[0] for entity 1, mean[1] entity 2, etc + * var[] + * Therefore, the Array size for each mean and var is: + * no of detected entities + */ + +#include <ros/ros.h> +#include <cv_bridge/cv_bridge.h> +#include <sensor_msgs/image_encodings.h> +#include <opencv2/imgproc/imgproc.hpp> +#include <opencv2/highgui/highgui.hpp> + +#include <visor/local_color_node.hpp> + +#include <visor/MPEG7FexLib_src_OpenCV22/Feature.h> + + +LocalColorFeat::LocalColorFeat() { + sub_ = nh_.subscribe("/detected_ent_img", 1, + &LocalColorFeat::localColorCb, this); + pub_ = nh_.advertise<visor::localColor>("/local_feat/color",1); + cv::namedWindow( "test", CV_WINDOW_AUTOSIZE); +} + +LocalColorFeat::~LocalColorFeat() { +} + +void LocalColorFeat::localColorCb( + const visor::detEntityArray::ConstPtr& msg +){ + cv_bridge::CvImagePtr cv_ptr; + + lcolor_.object_color.clear(); + lcolor_.header.stamp = msg->header.stamp; + lcolor_.object_count = msg->count; + cinfo_.header.stamp = msg->header.stamp; + cinfo_.size = 64; //msg->count; + for (int i=0; i<msg->count; i++) { + try { + cv_ptr = cv_bridge::toCvCopy(msg->entity[i], sensor_msgs::image_encodings::BGR8); + // ROS_WARN("OBJECT %d: ", i); + Frame* frame = new Frame( cv_ptr->image ); + XM::ColorStructureDescriptor* csd = Feature::getColorStructureD(frame, cinfo_.size); + cinfo_.desc.clear(); + for(int i = 0; i < csd->GetSize(); i++) { + // std::cout << (int)csd->GetElement(i) << " "; + // Assign each element to cinfo_.desc + cinfo_.desc.push_back((int)csd->GetElement(i)); + } + // std::cout << std::endl; + delete csd; + lcolor_.object_color.push_back(cinfo_); + } catch (cv_bridge::Exception& e) { + ROS_ERROR("LOCAL COLOR <- cv_bridge exception: %s", e.what()); + return; + } + } + pub_.publish(lcolor_); +} + +int main(int argc, char **argv) { + ros::init(argc, argv, "local_color_feat"); + LocalColorFeat lcf; + ros::spin(); + return 0; +} \ No newline at end of file diff --git a/pool/shard007/C++/0091956_display_configuration_controller_unittest.cc b/pool/shard007/C++/0091956_display_configuration_controller_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..67be11e62653ca8705b200c3375e00e805948abd --- /dev/null +++ b/pool/shard007/C++/0091956_display_configuration_controller_unittest.cc @@ -0,0 +1,99 @@ +// Copyright 2017 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 "ash/display/display_configuration_controller.h" + +#include "ash/display/display_configuration_controller_test_api.h" +#include "ash/rotator/screen_rotation_animator.h" +#include "ash/shell.h" +#include "ash/test/ash_test_base.h" +#include "ash/wallpaper/wallpaper_controller_impl.h" +#include "base/command_line.h" +#include "ui/display/manager/display_manager.h" + +namespace ash { +namespace { + +display::Display::Rotation GetDisplayRotation(int64_t display_id) { + return Shell::Get() + ->display_manager() + ->GetDisplayInfo(display_id) + .GetActiveRotation(); +} + +class DisplayConfigurationControllerSmoothRotationTest : public AshTestBase { + public: + DisplayConfigurationControllerSmoothRotationTest() = default; + + DisplayConfigurationControllerSmoothRotationTest( + const DisplayConfigurationControllerSmoothRotationTest&) = delete; + DisplayConfigurationControllerSmoothRotationTest& operator=( + const DisplayConfigurationControllerSmoothRotationTest&) = delete; + + ~DisplayConfigurationControllerSmoothRotationTest() override = default; + + void SetUp() override { + AshTestBase::SetUp(); + // ScreenRotionAnimator skips animation if the wallpaper isn't ready. + Shell::Get()->wallpaper_controller()->set_bypass_decode_for_testing(); + Shell::Get()->wallpaper_controller()->ShowDefaultWallpaperForTesting(); + } +}; + +} // namespace + +using DisplayConfigurationControllerTest = AshTestBase; + +TEST_F(DisplayConfigurationControllerTest, OnlyHasOneAnimator) { + display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay(); + DisplayConfigurationControllerTestApi testapi( + Shell::Get()->display_configuration_controller()); + ScreenRotationAnimator* old_screen_rotation_animator = + testapi.GetScreenRotationAnimatorForDisplay(display.id()); + + Shell::Get()->display_manager()->SetDisplayRotation( + display.id(), display::Display::ROTATE_0, + display::Display::RotationSource::USER); + old_screen_rotation_animator->Rotate( + display::Display::ROTATE_90, display::Display::RotationSource::USER, + DisplayConfigurationController::ANIMATION_SYNC); + + ScreenRotationAnimator* new_screen_rotation_animator = + testapi.GetScreenRotationAnimatorForDisplay(display.id()); + new_screen_rotation_animator->Rotate( + display::Display::ROTATE_180, display::Display::RotationSource::USER, + DisplayConfigurationController::ANIMATION_SYNC); + EXPECT_EQ(old_screen_rotation_animator, new_screen_rotation_animator); +} + +TEST_F(DisplayConfigurationControllerTest, GetTargetRotationWithAnimation) { + display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay(); + DisplayConfigurationController* controller = + Shell::Get()->display_configuration_controller(); + DisplayConfigurationControllerTestApi(controller).SetDisplayAnimator(true); + controller->SetDisplayRotation( + display.id(), display::Display::ROTATE_180, + display::Display::RotationSource::USER, + DisplayConfigurationController::ANIMATION_SYNC); + EXPECT_EQ(display::Display::ROTATE_180, + controller->GetTargetRotation(display.id())); + EXPECT_EQ(display::Display::ROTATE_180, GetDisplayRotation(display.id())); +} + +TEST_F(DisplayConfigurationControllerSmoothRotationTest, + GetTargetRotationWithAnimation) { + display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay(); + DisplayConfigurationController* controller = + Shell::Get()->display_configuration_controller(); + DisplayConfigurationControllerTestApi(controller).SetDisplayAnimator(true); + controller->SetDisplayRotation( + display.id(), display::Display::ROTATE_180, + display::Display::RotationSource::USER, + DisplayConfigurationController::ANIMATION_ASYNC); + EXPECT_EQ(display::Display::ROTATE_180, + controller->GetTargetRotation(display.id())); + EXPECT_EQ(display::Display::ROTATE_0, GetDisplayRotation(display.id())); +} + +} // namespace ash diff --git a/pool/shard007/C++/0091964_hex_file.cc b/pool/shard007/C++/0091964_hex_file.cc new file mode 100644 index 0000000000000000000000000000000000000000..bfebc1b44b54000ba5391fe128fbb6f2c9299356 --- /dev/null +++ b/pool/shard007/C++/0091964_hex_file.cc @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2007 MIPS Technologies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer; + * redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution; + * neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Authors: Jaidev Patwardhan + */ + +#include <cctype> +#include <cstdio> +#include <list> +#include <string> + +#include "base/loader/hex_file.hh" +#include "base/loader/symtab.hh" +#include "base/cprintf.hh" +#include "mem/port_proxy.hh" + +using namespace std; +/* + * Load a Hex File into memory. Currently only used with MIPS + * BARE_IRON mode. A hex file consists of [Address Data] tuples that + * get directly loaded into physical memory. The address specified is + * a word address (i.e., to get the byte address, shift left by 2) The + * data is a full 32-bit hex value. +*/ +HexFile::HexFile(const string _filename) + : filename(_filename) +{ + fp = fopen(filename.c_str(), "r"); + if (fp == NULL) + panic("Unable to open %s\n", filename.c_str()); +} + +HexFile::~HexFile() +{ +} + +bool +HexFile::loadSections(PortProxy& memProxy) +{ + char Line[64]; + Addr MemAddr; + uint32_t Data; + while (!feof(fp)) { + char *ret = fgets(Line, sizeof(Line), fp); + if (!ret) + panic("malformed file"); + parseLine(Line, &MemAddr, &Data); + if (MemAddr != 0) { + // Now, write to memory + memProxy.writeBlob(MemAddr << 2, (uint8_t *)&Data, sizeof(Data)); + } + } + return true; +} + +void +HexFile::parseLine(char *Str, Addr *A, uint32_t *D) +{ + int i = 0; + bool Flag = false; + *A = 0; + *D = 0; + int Digit = 0; + unsigned Number = 0; + + /* Skip white spaces */ + while (Str[i] != '\0' && Str[i]==' ') + i++; + + /* Ok, we're at some character...process things */ + while (Str[i] != '\0') { + if (Str[i] >= '0' && Str[i] <= '9') { + Digit = Str[i] - '0'; + } else if (Str[i] >= 'a' && Str[i] <= 'f') { + Digit = Str[i] - 'a' + 10; + } else if (Str[i] >= 'A' && Str[i] <= 'F') { + Digit=Str[i]-'A'+10; + } else if (Str[i] == ' ' || Str[i] == '\n') { + if (Number == 0) + return; + if (Flag == false) { + *A = Number; + Number = 0; + Flag = true; + } else { + *D = Number; + return; + } + } else { + // Ok, we've encountered a non-hex character, cannot be a + // valid line, skip and return 0's + *A = 0; + *D = 0; + return; + } + + Number <<= 4; + Number += Digit; + i++; + } + + if (Flag != true) { + *A = 0; + *D = 0; + } else { + *D = Number; + } +} + +void +HexFile::close() +{ + fclose(fp); +} diff --git a/pool/shard007/C++/0091965_bitcoind.cpp b/pool/shard007/C++/0091965_bitcoind.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0217a742cb9234924a3f14e532069d99584d10b9 --- /dev/null +++ b/pool/shard007/C++/0091965_bitcoind.cpp @@ -0,0 +1,177 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2013 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "clientversion.h" +#include "rpcserver.h" +#include "init.h" +#include "main.h" +#include "noui.h" +#include "scheduler.h" +#include "util.h" + +#include <boost/algorithm/string/predicate.hpp> +#include <boost/filesystem.hpp> +#include <boost/thread.hpp> + +/* Introduction text for doxygen: */ + +/*! \mainpage Developer documentation + * + * \section intro_sec Introduction + * + * This is the developer documentation of the reference client for an experimental new digital currency called Gamecredits (https://github.com/gamecredits-project/GameCredits/), + * which enables instant payments to anyone, anywhere in the world. Gamecredits uses peer-to-peer technology to operate + * with no central authority: managing transactions and issuing money are carried out collectively by the network. + * + * The software is a community-driven open source project, released under the MIT license. + * + * \section Navigation + * Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code. + */ + +static bool fDaemon; + +void WaitForShutdown(boost::thread_group* threadGroup) +{ + bool fShutdown = ShutdownRequested(); + // Tell the main threads to shutdown. + while (!fShutdown) + { + MilliSleep(200); + fShutdown = ShutdownRequested(); + } + if (threadGroup) + { + threadGroup->interrupt_all(); + threadGroup->join_all(); + } +} + +////////////////////////////////////////////////////////////////////////////// +// +// Start +// +bool AppInit(int argc, char* argv[]) +{ + boost::thread_group threadGroup; + CScheduler scheduler; + + bool fRet = false; + + // + // Parameters + // + // If Qt is used, parameters/gamecredits.conf are parsed in qt/gamecredits.cpp's main() + ParseParameters(argc, argv); + + // Process help and version before taking care about datadir + if (mapArgs.count("-?") || mapArgs.count("-help") || mapArgs.count("-version")) + { + std::string strUsage = _("GameCredits Core Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n"; + + if (mapArgs.count("-version")) + { + strUsage += LicenseInfo(); + } + else + { + strUsage += "\n" + _("Usage:") + "\n" + + " gamecreditsd [options] " + _("Start GameCredits Core Daemon") + "\n"; + + strUsage += "\n" + HelpMessage(HMM_BITCOIND); + } + + fprintf(stdout, "%s", strUsage.c_str()); + return false; + } + + try + { + if (!boost::filesystem::is_directory(GetDataDir(false))) + { + fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str()); + return false; + } + try + { + ReadConfigFile(mapArgs, mapMultiArgs); + } catch (const std::exception& e) { + fprintf(stderr,"Error reading configuration file: %s\n", e.what()); + return false; + } + // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) + if (!SelectParamsFromCommandLine()) { + fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n"); + return false; + } + + // Command-line RPC + bool fCommandLine = false; + for (int i = 1; i < argc; i++) + if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "gamecredits:")) + fCommandLine = true; + + if (fCommandLine) + { + fprintf(stderr, "Error: There is no RPC client functionality in gamecreditsd anymore. Use the gamecredits-cli utility instead.\n"); + exit(1); + } +#ifndef WIN32 + fDaemon = GetBoolArg("-daemon", false); + if (fDaemon) + { + fprintf(stdout, "GameCredits server starting\n"); + + // Daemonize + pid_t pid = fork(); + if (pid < 0) + { + fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno); + return false; + } + if (pid > 0) // Parent process, pid is child process id + { + return true; + } + // Child process falls through to rest of initialization + + pid_t sid = setsid(); + if (sid < 0) + fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno); + } +#endif + SoftSetBoolArg("-server", true); + + fRet = AppInit2(threadGroup, scheduler); + } + catch (const std::exception& e) { + PrintExceptionContinue(&e, "AppInit()"); + } catch (...) { + PrintExceptionContinue(NULL, "AppInit()"); + } + + if (!fRet) + { + threadGroup.interrupt_all(); + // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of + // the startup-failure cases to make sure they don't result in a hang due to some + // thread-blocking-waiting-for-another-thread-during-startup case + } else { + WaitForShutdown(&threadGroup); + } + Shutdown(); + + return fRet; +} + +int main(int argc, char* argv[]) +{ + SetupEnvironment(); + + // Connect gamecreditsd signal handlers + noui_connect(); + + return (AppInit(argc, argv) ? 0 : 1); +} diff --git a/pool/shard007/C++/0091972_ValueEvent.cpp b/pool/shard007/C++/0091972_ValueEvent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5aef0113cbedb3b3982339afba8514a931ec456c --- /dev/null +++ b/pool/shard007/C++/0091972_ValueEvent.cpp @@ -0,0 +1,81 @@ +/*************************************************************************** + ValueEvent.cpp - description + ------------------- + begin : mar mar 4 2003 + copyright : (C) 2003 by Emmanuel Promayon + email : Emmanuel.Promayon@imag.fr + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +///a valueEvent of a load is composed of a value and a date + +#include "ValueEvent.h" + +//--------- isActive ---------- +bool ValueEvent::isActive(const SReal t) const { + return (t>=date); +} + +//--------- getValue ---------- +double ValueEvent::getValue() { + return value; +} + +double ValueEvent::getValue(const double t) { + if (isActive(t)) + return getValue(); + else + return 0.0; +} + +double ValueEvent::getValue(const double t, ValueEvent * nextEvent) { + if (isActive(t)) { + return (getValue() + + (t-getDate()) + *((nextEvent->getValue() - getValue())/(nextEvent->getDate()-getDate())) ); + } else + return 0.0; // Value is not active +} + + +//--------- getDate ---------- +double ValueEvent::getDate() const { + return date; +} + +// --------------- xmlPrint --------------- +void ValueEvent::xmlPrint(std::ostream & o) { + o << "\t" << "<valueEvent date=\"" << date + << "\" value=\"" << value + << "\"/>" << std::endl; +} + +// --------------- operator << --------------- +std::ostream & operator << (std::ostream &o, ValueEvent e) { + + o << "\t" << "<valueEvent date=\"" << e.getDate() + << "\" value=\"" << e.getValue() + << "\"/>" << std::endl; + + return o; +} + +// --------------- setDate --------------- +void ValueEvent::setDate(const double d) { + date = d; +} + +// --------------- setValue --------------- +void ValueEvent::setValue(const double v) { + value = v; +} + + diff --git a/pool/shard007/C++/0091974_search_query_params.cpp b/pool/shard007/C++/0091974_search_query_params.cpp new file mode 100644 index 0000000000000000000000000000000000000000..916c0393b350ab828d2d12d3f235f95c3321a11d --- /dev/null +++ b/pool/shard007/C++/0091974_search_query_params.cpp @@ -0,0 +1,142 @@ +#include "search/search_query_params.hpp" + +#include "indexer/feature_impl.hpp" +#include "indexer/scales.hpp" + +#include "base/assert.hpp" + +#include "std/algorithm.hpp" + +namespace search +{ +namespace +{ +class DoAddStreetSynonyms +{ +public: + DoAddStreetSynonyms(SearchQueryParams & params) : m_params(params) {} + + void operator()(SearchQueryParams::TString const & s, size_t i) + { + if (s.size() > 2) + return; + string const ss = strings::ToUtf8(strings::MakeLowerCase(s)); + + // All synonyms should be lowercase! + if (ss == "n") + AddSym(i, "north"); + if (ss == "w") + AddSym(i, "west"); + if (ss == "s") + AddSym(i, "south"); + if (ss == "e") + AddSym(i, "east"); + if (ss == "nw") + AddSym(i, "northwest"); + if (ss == "ne") + AddSym(i, "northeast"); + if (ss == "sw") + AddSym(i, "southwest"); + if (ss == "se") + AddSym(i, "southeast"); + } + +private: + SearchQueryParams::TSynonymsVector & GetSyms(size_t i) const + { + size_t const count = m_params.m_tokens.size(); + if (i < count) + return m_params.m_tokens[i]; + ASSERT_EQUAL(i, count, ()); + return m_params.m_prefixTokens; + } + + void AddSym(size_t i, string const & sym) { GetSyms(i).push_back(strings::MakeUniString(sym)); } + + SearchQueryParams & m_params; +}; +} // namespace + +SearchQueryParams::SearchQueryParams() : m_scale(scales::GetUpperScale()) {} + +void SearchQueryParams::Clear() +{ + m_tokens.clear(); + m_prefixTokens.clear(); + m_langs.clear(); + m_scale = scales::GetUpperScale(); +} + +void SearchQueryParams::EraseTokens(vector<size_t> & eraseInds) +{ + eraseInds.erase(unique(eraseInds.begin(), eraseInds.end()), eraseInds.end()); + ASSERT(is_sorted(eraseInds.begin(), eraseInds.end()), ()); + + // fill temporary vector + vector<TSynonymsVector> newTokens; + + size_t skipI = 0; + size_t const count = m_tokens.size(); + size_t const eraseCount = eraseInds.size(); + for (size_t i = 0; i < count; ++i) + { + if (skipI < eraseCount && eraseInds[skipI] == i) + ++skipI; + else + newTokens.push_back(move(m_tokens[i])); + } + + // assign to m_tokens + newTokens.swap(m_tokens); + + if (skipI < eraseCount) + { + // it means that we need to skip prefix tokens + ASSERT_EQUAL(skipI + 1, eraseCount, (eraseInds)); + ASSERT_EQUAL(eraseInds[skipI], count, (eraseInds)); + m_prefixTokens.clear(); + } +} + +void SearchQueryParams::ProcessAddressTokens() +{ + // Erases all number tokens. + // Assumes that USA street name numbers are end with "st, nd, rd, th" suffixes. + vector<size_t> toErase; + ForEachToken([&toErase](SearchQueryParams::TString const & s, size_t i) + { + if (feature::IsNumber(s)) + toErase.push_back(i); + }); + EraseTokens(toErase); + + // Adds synonyms for N, NE, NW, etc. + ForEachToken(DoAddStreetSynonyms(*this)); +} + +template <class ToDo> +void SearchQueryParams::ForEachToken(ToDo && toDo) +{ + size_t const count = m_tokens.size(); + for (size_t i = 0; i < count; ++i) + { + ASSERT(!m_tokens[i].empty(), ()); + ASSERT(!m_tokens[i].front().empty(), ()); + toDo(m_tokens[i].front(), i); + } + + if (!m_prefixTokens.empty()) + { + ASSERT(!m_prefixTokens.front().empty(), ()); + toDo(m_prefixTokens.front(), count); + } +} +} // namespace search + +string DebugPrint(search::SearchQueryParams const & params) +{ + ostringstream os; + os << "SearchQueryParams [ m_tokens=" << DebugPrint(params.m_tokens) + << ", m_prefixTokens=" << DebugPrint(params.m_prefixTokens) << "]"; + return os.str(); +} diff --git a/pool/shard007/C++/0091982_motor.cpp b/pool/shard007/C++/0091982_motor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..98754f699f3b6671dc293479af293b957f3b6253 --- /dev/null +++ b/pool/shard007/C++/0091982_motor.cpp @@ -0,0 +1,128 @@ +/* + Copyright 2016 Carter Turnbaugh + + This file is part of Terca ROV Drive. + + Terca ROV Drive is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Terca ROV Drive is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Terca ROV Drive. If not, see <http://www.gnu.org/licenses/>. +*/ +#include "motor.h" + +#include <sstream> +#include <fstream> +#include <unistd.h> + +using namespace std; + +void stop_motor(void * param){ + ((motor *) param)->stop(); +} + +motor::motor(short enable_pin, short forward_pin, short reverse_pin, bool safe) + : enable_pin{enable_pin}, forward_pin(forward_pin), reverse_pin(reverse_pin){ + if(safe){ + dog = new watchdog(&stop_motor, this); + } + else{ + dog = NULL; + } +} + +void motor::setup_pin(short pin){ + for(short i = 0; i < 2; i++){ // Needs to be done twice (not sure why) + ofstream export_file("/sys/class/gpio/export"); + export_file << pin; + export_file.close(); + + stringstream direction_file_name; + direction_file_name << "/sys/class/gpio/gpio" << pin << "/direction"; + + ofstream direction_file(direction_file_name.str().c_str()); + direction_file << "out"; + direction_file.close(); + + usleep(1000000); + } +} + +void motor::cleanup_pin(short pin){ + ofstream unexportFile("/sys/class/gpio/unexport"); + unexportFile << pin; + unexportFile.close(); +} + +void motor::write_pin(short pin, short value){ + stringstream value_file_name; + value_file_name << "/sys/class/gpio/gpio" << pin << "/value"; + + ofstream value_file(value_file_name.str().c_str()); + value_file << value; + value_file.close(); +} + +void motor::init(){ + setup_pin(enable_pin); + setup_pin(forward_pin); + setup_pin(reverse_pin); + disable(); + run(0); + + if(dog != NULL){ + dog->start(); + } +} + +void motor::cleanup(){ + cleanup_pin(enable_pin); + cleanup_pin(forward_pin); + cleanup_pin(reverse_pin); + + if(dog != NULL){ + dog->end(); + delete dog; + } +} + +void motor::run(short direction){ + if(dog != NULL){ + dog->kick(100); + } + + switch(direction){ + case 1: + write_pin(forward_pin, 1); + write_pin(reverse_pin, 0); + return; + case -1: + write_pin(forward_pin, 0); + write_pin(reverse_pin, 1); + return; + case 0: + default: + write_pin(forward_pin, 0); + write_pin(reverse_pin, 0); + return; + } +} + +void motor::enable(){ + write_pin(enable_pin, 1); +} + +void motor::stop(){ + run(0); +} + +void motor::disable(){ + write_pin(enable_pin, 0); +} diff --git a/pool/shard007/C++/0091984_ErrorInfo.cc b/pool/shard007/C++/0091984_ErrorInfo.cc new file mode 100644 index 0000000000000000000000000000000000000000..aef5bd0163195e8a56b5fea7b23b3307ba517fe7 --- /dev/null +++ b/pool/shard007/C++/0091984_ErrorInfo.cc @@ -0,0 +1,72 @@ +/** + * Copyright (C) 2011 Eric Huang + * + * This file is part of rectpack. + * + * rectpack is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * rectpack is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with rectpack. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "ErrorInfo.h" + +ErrorInfo::ErrorInfo() : + m_bKorfAttempted(false), + m_bMineAttempted(false) { +} + +ErrorInfo::ErrorInfo(const RDimensions& b, + const std::deque<RDimensions>& v, bool bKorf, + bool bMine) : + m_Box(b), + m_vInstance(v), + m_bKorfFeasible(bKorf), + m_bMineFeasible(bMine), + m_bKorfAttempted(false), + m_bMineAttempted(false) { +} + +ErrorInfo::ErrorInfo(const RDimensions& b, + const std::deque<RDimensions>& v, bool bKorf, + bool bMine, bool bKorf2, bool bMine2) : + m_Box(b), + m_vInstance(v), + m_bKorfFeasible(bKorf), + m_bMineFeasible(bMine), + m_bKorfAttempted(bKorf2), + m_bMineAttempted(bMine2) { +} + +ErrorInfo::~ErrorInfo() { +} + +std::ostream& operator<<(std::ostream& os, const ErrorInfo& ei) { + os << ei.m_Box; + if(ei.m_bKorfAttempted != ei.m_bMineAttempted) { + if(ei.m_bKorfAttempted) + os << " Rich tried but you didn't."; + else + os << " you tried but Rich didn't."; + os << " Instance was:"; + } + else { + os << " should be " + << (ei.m_bKorfFeasible ? "feasible" : "infeasible") + << " with squares"; + } + std::deque<RDimensions>::const_iterator i = ei.m_vInstance.begin(); + if(i != ei.m_vInstance.end()) + os << *i; + for(++i; i != ei.m_vInstance.end(); ++i) + os << ',' << *i; + return(os); +} diff --git a/pool/shard007/C++/0091987_broken.cpp b/pool/shard007/C++/0091987_broken.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7aa627abb74affcca20aea7baef0b1e0b2c773cb --- /dev/null +++ b/pool/shard007/C++/0091987_broken.cpp @@ -0,0 +1,75 @@ +// 2009-03-26 +#include <stdio.h> +#include <string.h> +char infile[20000000]; +char outfile[20000000]; +char s[1000001]; +char *ip,*op; +char c; +int x; +int in() +{ + x=0; + for(;;) + { + c=*ip++; + if (c<=32) return x; + x=(x<<1)+(x<<3)+c-'0'; + } +} +int d; +void out(int x) +{ + if (x<10) + *op++=x+'0'; + else + { + d=x/10; + out(d); + d=(d<<1)+(d<<3); + *op++=x-d+'0'; + } +} +int get_string(char* t) +{ + while ((*t++=*ip++)>=32); + return t-s; +} +int main() +{ + fread_unlocked(infile,20000000,1,stdin); +// read(0,infile,20000000); + ip=infile; + op=outfile; + int N,best,cnt,l; + char *begin,*end; + int used[256]; + for(;;) + { + if (!(N=in())) break; + getchar(); + l=get_string(s); + best=cnt=0; + begin=end=s; + memset(used,0,sizeof(used)); + while (*end>=32) + { + if (++used[*end++]==1) + cnt++; + if (cnt>N) + { + while (--used[*begin++]); + cnt=N; + } + if (end-begin>best) + best=end-begin; + if (l-(begin-s)<=best) + break; + } + printf("%d\n",best); +// out(best); +// *op++='\n'; + } +// fwrite(outfile,op-outfile,1,stdout); + return 0; +} diff --git a/pool/shard007/C++/0091988_RecordingBench.cpp b/pool/shard007/C++/0091988_RecordingBench.cpp new file mode 100644 index 0000000000000000000000000000000000000000..45a91288f556513567234661e2f90057307f711e --- /dev/null +++ b/pool/shard007/C++/0091988_RecordingBench.cpp @@ -0,0 +1,93 @@ +/* + * Copyright 2014 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include "RecordingBench.h" +#include "SkBBHFactory.h" +#include "SkLiteDL.h" +#include "SkLiteRecorder.h" +#include "SkPictureRecorder.h" + +PictureCentricBench::PictureCentricBench(const char* name, const SkPicture* pic) : fName(name) { + // Flatten the source picture in case it's trivially nested (useless for timing). + SkPictureRecorder rec; + pic->playback(rec.beginRecording(pic->cullRect(), nullptr, + SkPictureRecorder::kPlaybackDrawPicture_RecordFlag)); + fSrc = rec.finishRecordingAsPicture(); +} + +const char* PictureCentricBench::onGetName() { + return fName.c_str(); +} + +bool PictureCentricBench::isSuitableFor(Backend backend) { + return backend == kNonRendering_Backend; +} + +SkIPoint PictureCentricBench::onGetSize() { + return SkIPoint::Make(SkScalarCeilToInt(fSrc->cullRect().width()), + SkScalarCeilToInt(fSrc->cullRect().height())); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// + +RecordingBench::RecordingBench(const char* name, const SkPicture* pic, bool useBBH, bool lite) + : INHERITED(name, pic) + , fUseBBH(useBBH) +{ + // If we're recording into an SkLiteDL, also record _from_ one. + if (lite) { + fDL.reset(new SkLiteDL()); + SkLiteRecorder r; + r.reset(fDL.get(), fSrc->cullRect().roundOut()); + fSrc->playback(&r); + } +} + +void RecordingBench::onDraw(int loops, SkCanvas*) { + if (fDL) { + SkLiteRecorder rec; + while (loops --> 0) { + SkLiteDL dl; + rec.reset(&dl, fSrc->cullRect().roundOut()); + fDL->draw(&rec); + } + + } else { + SkRTreeFactory factory; + SkPictureRecorder recorder; + while (loops --> 0) { + fSrc->playback(recorder.beginRecording(fSrc->cullRect(), fUseBBH ? &factory : nullptr)); + (void)recorder.finishRecordingAsPicture(); + } + } +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// +#include "SkSerialProcs.h" + +DeserializePictureBench::DeserializePictureBench(const char* name, sk_sp<SkData> data) + : fName(name) + , fEncodedPicture(std::move(data)) +{} + +const char* DeserializePictureBench::onGetName() { + return fName.c_str(); +} + +bool DeserializePictureBench::isSuitableFor(Backend backend) { + return backend == kNonRendering_Backend; +} + +SkIPoint DeserializePictureBench::onGetSize() { + return SkIPoint::Make(128, 128); +} + +void DeserializePictureBench::onDraw(int loops, SkCanvas*) { + for (int i = 0; i < loops; ++i) { + SkPicture::MakeFromData(fEncodedPicture.get()); + } +} diff --git a/pool/shard007/C++/0091990_1.cc b/pool/shard007/C++/0091990_1.cc new file mode 100644 index 0000000000000000000000000000000000000000..afca7e8d41d94170585269de22b6f3f07dcb7353 --- /dev/null +++ b/pool/shard007/C++/0091990_1.cc @@ -0,0 +1,99 @@ +// 1999-05-11 bkoz + +// Copyright (C) 1999-2013 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// <http://www.gnu.org/licenses/>. + +// 21.3.3 string capacity + +#include <string> +#include <testsuite_hooks.h> + +void test01() +{ + // POD types : resize, capacity, reserve + bool test __attribute__((unused)) = true; + std::string str01; + typedef std::string::size_type size_type_s; + + size_type_s sz01 = str01.capacity(); + str01.reserve(100); + size_type_s sz02 = str01.capacity(); + VERIFY( sz02 >= sz01 ); + VERIFY( sz02 >= 100 ); + str01.reserve(); + sz01 = str01.capacity(); + VERIFY( sz01 == 0 ); + + sz01 = str01.size() + 5; + str01.resize(sz01); + sz02 = str01.size(); + VERIFY( sz01 == sz02 ); + + sz01 = str01.size() - 5; + str01.resize(sz01); + sz02 = str01.size(); + VERIFY( sz01 == sz02 ); + + std::string str05(30, 'q'); + std::string str06 = str05; + str05 = str06 + str05; + VERIFY( str05.capacity() >= str05.size() ); + VERIFY( str06.capacity() >= str06.size() ); + + // POD types: size, length, max_size, clear(), empty() + bool b01; + std::string str011; + b01 = str01.empty(); + VERIFY( b01 == true ); + sz01 = str01.size(); + sz02 = str01.length(); + VERIFY( sz01 == sz02 ); + str01.c_str(); + sz01 = str01.size(); + sz02 = str01.length(); + VERIFY( sz01 == sz02 ); + + sz01 = str01.length(); + str01.c_str(); + str011 = str01 + "_addendum_"; + str01.c_str(); + sz02 = str01.length(); + VERIFY( sz01 == sz02 ); + sz02 = str011.length(); + VERIFY( sz02 > sz01 ); + + // trickster allocator issues involved with these: + std::string str3 = "8-chars_8-chars_"; + std::string str4 = str3 + "7-chars"; + + sz01 = str01.size(); + sz02 = str01.max_size(); + VERIFY( sz02 >= sz01 ); + + sz01 = str01.size(); + str01.clear(); + b01 = str01.empty(); + VERIFY( b01 == true ); + sz02 = str01.size(); + VERIFY( sz01 >= sz02 ); +} + +int main() +{ + test01(); + return 0; +} diff --git a/pool/shard007/C++/0092003_WQApplication.cpp b/pool/shard007/C++/0092003_WQApplication.cpp new file mode 100644 index 0000000000000000000000000000000000000000..570af51aa1c8b884a25e878e94bca8abbcee206b --- /dev/null +++ b/pool/shard007/C++/0092003_WQApplication.cpp @@ -0,0 +1,147 @@ +/* + * Copyright (C) 2008 Emweb bvba, Kessel-Lo, Belgium. + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ +#include <iostream> +#include <boost/thread/condition.hpp> + +#include "wtwithqtlib/WQApplication.h" +#include "wtwithqtlib/DispatchThread.h" + +#include <Wt/WLogger> + +namespace Wt { + +WQApplication::WQApplication(const WEnvironment& env, bool withEventLoop) + : WApplication(env), + withEventLoop_(withEventLoop), + thread_(0), + finalized_(false), + recursiveEvent_(false) +{ } + +void WQApplication::initialize() +{ + log("debug") << "WQApplication: initialize()"; + WApplication::initialize(); + + create(); +} + +void WQApplication::finalize() +{ + log("debug") << "WQApplication: finalize()"; + WApplication::finalize(); + + destroy(); + thread_->destroy(); + + finalized_ = true; +} + +void WQApplication::notify(const WEvent& e) +{ + if (!thread_) { + log("debug") << "WQApplication: starting thread"; + thread_ = new DispatchThread(this, withEventLoop_); + thread_->start(); + thread_->waitDone(); + } + + if (recursiveEvent_) { + /* This could be from within a recursive event loop */ + log("debug") << "WQApplication: notify() from within QThread"; + realNotify(e); + return; + } + + if (e.eventType() == Wt::ResourceEvent && recursiveEvent_) { + /* + * We do not relay resource events while blocked in a recursive event + * loop, since these will not unlock a recursive event loop and + * thus we cannot communicate with the private thread when it's + * blocked in a recursive event loop + */ + log("debug") << "WQApplication: notify() for resource during recursive " + << "event, handling in thread pool."; + realNotify(e); + return; + } + + log("debug") << "WQApplication: notifying thread"; + thread_->notify(e); + + if (thread_->exception()) { + thread_->resetException(); + throw std::runtime_error("WQApplication: rethrowing exception"); + } + + if (finalized_) { + log("debug") << "WQApplication: joining thread"; + thread_->wait(); + delete thread_; + thread_ = 0; + } +} + +void WQApplication::realNotify(const WEvent& e) +{ + WApplication::notify(e); +} + +void WQApplication::waitForEvent() +{ + log("debug") << "WQApplication: [thread] waitForEvent()"; + + recursiveEvent_ = true; + + if (thread_->eventLock()) + thread_->eventLock()->unlock(); + + try { + Wt::WApplication::waitForEvent(); + } catch (...) { + if (thread_->eventLock()) + thread_->eventLock()->lock(); + recursiveEvent_ = false; + throw; + } + + if (thread_->eventLock()) + thread_->eventLock()->lock(); + recursiveEvent_ = false; + + log("debug") << "WQApplication: [thread] returning from waitForEvent()"; +} + +WString toWString(const QString& s) +{ + return WString::fromUTF8((const char *)s.toUtf8()); +} + +QString toQString(const WString& s) +{ + return QString::fromUtf8(s.toUTF8().c_str()); +} + +} diff --git a/pool/shard007/C++/0092013_Generics.cpp b/pool/shard007/C++/0092013_Generics.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9fd8ff60151861ae8fef5b6350366510960269b9 --- /dev/null +++ b/pool/shard007/C++/0092013_Generics.cpp @@ -0,0 +1,63 @@ +#include <iostream> + +class RectangleImpl { +public: + RectangleImpl(float w, float h) : width(w), height(h) {} + + float Area() const { + return width * height; + } + +private: + float width, height; +}; + +class CircleImpl { +public: + CircleImpl(float r) : radius(r) {} + + float Area() const { + return 3.14 * (radius * radius); + } + +private: + float radius; +}; + +class TriangleImpl { +public: + TriangleImpl(float b, float h) : base(b), height(h) {} + + float Area() const { + return 0.5 * base * height; + } + +private: + float base, height; +}; + +template <typename Impl> +class Shape { +public: + Shape(const Impl impl) : implementation(impl) {} + + void PrintArea() const { + std::cout << "area = " << implementation.Area() << std::endl; + } + +private: + const Impl implementation; +}; + +int main() { + + Shape<RectangleImpl> rect(RectangleImpl(10, 20)); + Shape<CircleImpl> circle(CircleImpl(5)); + Shape<TriangleImpl> triangle(TriangleImpl(10, 5)); + + rect.PrintArea(); + circle.PrintArea(); + triangle.PrintArea(); + + return 0; +} diff --git a/pool/shard007/C++/0092020_startPage.cpp b/pool/shard007/C++/0092020_startPage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..51c0768fbf30f784c39e8525e612e529edc2ad1d --- /dev/null +++ b/pool/shard007/C++/0092020_startPage.cpp @@ -0,0 +1,93 @@ +// +// startPage.cpp +// HelloOpenGL +// +// Created by wantnon (yang chao) on 14-2-7. +// +// + +#include "startPage.h" +#include "globalVars.h" +#include "menuPage.h" +#include "c3dSceneManger.h" +#include "c3dDeviceAndOSInfo.h" +#include "c3dGestureAnalyzer.h" +#include "passUnifoCallBack.h" +bool CstartPage::init(){ + const float wReso=Cc3dDeviceAndOSInfo::sharedDeviceAndOSInfo()->getResolutionSize().x(); + const float hReso=Cc3dDeviceAndOSInfo::sharedDeviceAndOSInfo()->getResolutionSize().y(); + const float width=Cc3dDeviceAndOSInfo::sharedDeviceAndOSInfo()->getScreenSize().x(); + const float height=Cc3dDeviceAndOSInfo::sharedDeviceAndOSInfo()->getScreenSize().y(); + string resoStr=numberToStr(wReso)+"x"+numberToStr(hReso); + //cout<<"resoStr:"<<resoStr<<endl; + //--quad_startPage_backGround + { + m_quad_startPage_backGround=new Ckey(); + m_quad_startPage_backGround->autorelease(); + m_quad_startPage_backGround->init(); + // + string imagePathShort="singleCellGameResource/data/global/tex/pageTexs/startPageTex/backGround_"; + imagePathShort+=resoStr+".png"; + Cc3dTexture* ptex=Cc3dTextureCache::sharedTextureCache()->addImage(imagePathShort,GL_CLAMP_TO_EDGE,GL_CLAMP_TO_EDGE); + const float texW=ptex->getWidth(); + const float texH=ptex->getHeight(); + float bx=0; + float by=0; + m_quad_startPage_backGround->genAndInit(bx, bx+width, by, by+height,0,wReso/texW,1-hReso/texH,1); + m_quad_startPage_backGround->getModel()->getMeshList()[0]->getSubMeshByIndex(0)->getIndexVBO()->genBuffers(); + m_quad_startPage_backGround->getModel()->getMeshList()[0]->getSubMeshByIndex(0)->setTexture(ptex); + m_quad_startPage_backGround->setKeyUpColor(1, 1, 1, 1); + m_quad_startPage_backGround->useKeyUpColor(); + m_quad_startPage_backGround->setCamera(camera2D); + m_quad_startPage_backGround->getModel()->getMeshList()[0]->setIsWriteDepthBuffer(false); + m_quad_startPage_backGround->setProgram(Cc3dProgramCache::sharedProgramCache()->getProgramByName("shaderNoLight")); + m_quad_startPage_backGround->setPassUnifoCallback(passUnifoCallback_noLight); + // + m_quad_startPage_backGround->reSetLeftDownCorner(0, 0); + m_quad_startPage_backGround->getModel()->getMeshList()[0]->getSubMeshByIndex(0)->submit(GL_STREAM_DRAW); + // + addChild(m_quad_startPage_backGround); + } + //----startMusic + Cc3dALSource*pALSource_startMusic=Cc3dAudioCache::sharedAudioCache()->createBufferAndSource("singleCellGameResource/data/global/audio/startMusic.wav","startMusic"); + this->addALSource(pALSource_startMusic); + pALSource_startMusic->setIsLooping(true); + //----switchPage + Cc3dALSource*pALSource_switchPage=Cc3dAudioCache::sharedAudioCache()->createBufferAndSource("singleCellGameResource/data/global/audio/switchPage.wav","switchPage"); + this->addALSource(pALSource_switchPage); + + + //----开始播放--abc + this->getALSourceByName("startMusic")->play(); + return true; +} +void CstartPage::update(){ + //----quad_startPage_backGround + //quad_startPage_backGround响应单击--abc + /* Cc3dTouch touch=Cc3dTouchSequence::sharedTouchSequence()->getLatestTouches()[0]; + cout<<"-----"<<endl; + touch.print(); + cout<<"timeCount: "<<timeCounter.getCount()<<endl; + */ + //if(Cc3dGestureAnalyzer::sharedGestureAnalyzer()->getIsTapOnce())cout<<"hi"<<endl; + if(m_quad_startPage_backGround->isContainPoint(Cc3dGestureAnalyzer::sharedGestureAnalyzer()->getPoint())&&Cc3dGestureAnalyzer::sharedGestureAnalyzer()->getIsTapOnce()){ + this->getALSourceByName("switchPage")->play(); + CmenuPage*menuPage=new CmenuPage(); + menuPage->autorelease(); + menuPage->init(); + Cc3dSceneManager::sharedSceneManager()->getRoot()->removeAllChildOnNextFrame(); + Cc3dSceneManager::sharedSceneManager()->getRoot()->addChild(menuPage); + + + } + +} +CstartPage::CstartPage(){ + m_quad_startPage_backGround=NULL; +} +CstartPage::~CstartPage(){ + //----remove unused resources in caches on next frame + Cc3dTextureCache::sharedTextureCache()->removeUnusedTexturesOnNextFrame(); + Cc3dAudioCache::sharedAudioCache()->removeUnusedBuffersAndSourcesOnNextFrame(); + +} diff --git a/pool/shard007/C++/0092023_GLOBJModel.cpp b/pool/shard007/C++/0092023_GLOBJModel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2b12315dff63361fea81e9c26d365a98266ed64d --- /dev/null +++ b/pool/shard007/C++/0092023_GLOBJModel.cpp @@ -0,0 +1,126 @@ +// +// Copyright(c) 2016-2017 benikabocha. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// + +#include "GLOBJModel.h" + +#include "../../GLTextureUtil.h" + +namespace saba +{ + GLOBJModel::GLOBJModel() + { + } + + GLOBJModel::~GLOBJModel() + { + Destroy(); + } + + bool GLOBJModel::Create(const OBJModel& objModel) + { + // Materialをコピー + auto materials = objModel.GetMaterials(); + + m_materials.clear(); + m_materials.reserve(materials.size()); + for (const auto& objMat : materials) + { + Material mat; + mat.m_name = objMat.m_name; + + mat.m_ambient = objMat.m_ambient; + mat.m_diffuse = objMat.m_diffuse; + mat.m_specular = objMat.m_specular; + mat.m_specularPower = objMat.m_specularPower; + mat.m_transparency = objMat.m_transparency; + + if (!objMat.m_ambientTex.empty()) + { + auto tex = CreateTextureFromFile(objMat.m_ambientTex); + mat.m_ambientTex = std::move(tex); + } + if (!objMat.m_diffuseTex.empty()) + { + auto tex = CreateTextureFromFile(objMat.m_diffuseTex); + mat.m_diffuseTex = std::move(tex); + } + if (!objMat.m_specularTex.empty()) + { + auto tex = CreateTextureFromFile(objMat.m_specularTex); + mat.m_specularTex = std::move(tex); + } + if (!objMat.m_transparencyTex.empty()) + { + auto tex = CreateTextureFromFile(objMat.m_transparencyTex); + mat.m_transparencyTex = std::move(tex); + } + + m_materials.push_back(mat); + } + + // Meshを作成 + using MB = MeshBuilder; + MB mb; + auto objPos = objModel.GetPositions(); + auto objNor = objModel.GetNormals(); + auto objUV = objModel.GetUVs(); + std::vector<glm::vec3>* positions; + std::vector<glm::vec3>* normals; + std::vector<glm::vec2>* uvs; + auto posID = mb.AddComponent(&positions); + auto norID = mb.AddComponent(&normals); + auto uvID = mb.AddComponent(&uvs); + *positions = objPos; + *normals = objNor; + *uvs = objUV; + m_bboxMin = objModel.GetBBoxMin(); + m_bboxMax = objModel.GetBBoxMax(); + + auto objFaces = objModel.GetFaces(); + for (const auto& face : objFaces) + { + auto polyID = mb.AddPolygon(); + mb.SetPolygon(polyID, posID, face.m_position[0], face.m_position[1], face.m_position[2]); + mb.SetPolygon(polyID, norID, face.m_normal[0], face.m_normal[1], face.m_normal[2]); + mb.SetPolygon(polyID, uvID, face.m_uv[0], face.m_uv[1], face.m_uv[2]); + mb.SetFaceMaterial(polyID, face.m_material); + } + mb.SortFaces(); + + std::vector<MB::SubMesh> objSubMeshes; + mb.MakeSubMeshList(&objSubMeshes); + + m_subMeshes.clear(); + m_subMeshes.reserve(objSubMeshes.size()); + for (const auto& objSubMesh : objSubMeshes) + { + SubMesh subMesh; + subMesh.m_beginIndex = (int)objSubMesh.m_startIndex; + subMesh.m_vertexCount = (int)objSubMesh.m_numVertices; + subMesh.m_materialID = objSubMesh.m_material; + m_subMeshes.push_back(subMesh); + } + + m_posVBO = mb.CreateVBO(posID); + m_norVBO = mb.CreateVBO(norID); + m_uvVBO = mb.CreateVBO(uvID); + + m_posBinder = mb.MakeVertexBinder(posID); + m_norBinder = mb.MakeVertexBinder(norID); + m_uvBinder = mb.MakeVertexBinder(uvID); + + return true; + } + + void GLOBJModel::Destroy() + { + m_posVBO.Destroy(); + m_norVBO.Destroy(); + m_uvVBO.Destroy(); + m_materials.clear(); + m_subMeshes.clear(); + } + +} diff --git a/pool/shard007/C++/0092027_fixedPoint.cpp b/pool/shard007/C++/0092027_fixedPoint.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6a366fec66c2f1e7ad2aa4b0f08bea1e8c4fa05d --- /dev/null +++ b/pool/shard007/C++/0092027_fixedPoint.cpp @@ -0,0 +1,80 @@ +#include "fixedPoint.hpp" + +#include <assert.h> +#include <iostream> + +typedef FixedPoint FP; + +// Gauss-Seidel +EMatrix FP::solve(const EMatrix& A, const EVector& rhs) { + using namespace Eigen; + const TriangularView<const EMatrix, StrictlyUpper> U = + A.triangularView<StrictlyUpper>(); + const TriangularView<const EMatrix, Lower> L = + A.triangularView<Lower>(); + EVector r = rhs; + EVector x = EVector::Zero( r.rows() ); + int j=0; + Timer t; t.start(); + while (j < ITER_MAX_NUM && + r.norm() > ITER_TOL ) { + + x = L.solve( rhs - U * x ); + r = rhs - A * x; +#ifdef DEBUG + std::cout << "residule : " << r.norm() << std::endl; +#endif + } + t.stop(); + this->num_iter = j; + this->residule = r.norm(); + this->time = t.get_elapsed_time(); + std::cout << "\n========================" << std::endl; + if (num_iter < ITER_MAX_NUM) { + std::cout << "Fixed point iteration has converged!" << std::endl; + } + else { + std::cout << "Fixed point iteration has NOT converge!" << std::endl; + } + std::cout << " iter # : " << num_iter << std::endl + << " residule : " << residule << std::endl + << " time : " << time << " s" << std::endl; + std::cout << "========================\n" << std::endl; + return x; +} + +EMatrix FP::solve(const EMatrix& A, const EVector& rhs, const Pcond& M) { + assert( rhs.cols() == 1 ); + EVector x = EVector::Zero( rhs.rows() ); + EVector r = rhs; + EVector del; + int j=0; + Timer t; t.start(); + while (j < ITER_MAX_NUM && + r.norm() > ITER_TOL ) { + + del = M / r ; + x += del; + r = rhs - A * x; + j ++; +#ifdef DEBUG + std::cout << "residule : " << r.norm() << std::endl; +#endif + } + t.stop(); + this->num_iter = j; + this->residule = r.norm(); + this->time = t.get_elapsed_time(); + std::cout << "\n========================" << std::endl; + if (num_iter < ITER_MAX_NUM) { + std::cout << "Fixed point iteration has converged!" << std::endl; + } + else { + std::cout << "Fixed point iteration has NOT converge!" << std::endl; + } + std::cout << " iter # : " << num_iter << std::endl + << " residule : " << residule << std::endl + << " time : " << time << " s" << std::endl; + std::cout << "========================\n" << std::endl; + return x; +} diff --git a/pool/shard007/C++/0092033_bond_harmonic_shift_cut_omp.cpp b/pool/shard007/C++/0092033_bond_harmonic_shift_cut_omp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a871fa8c0471f5eefcdb8bade0a19d908fc71552 --- /dev/null +++ b/pool/shard007/C++/0092033_bond_harmonic_shift_cut_omp.cpp @@ -0,0 +1,133 @@ +/* ---------------------------------------------------------------------- + LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator + http://lammps.sandia.gov, Sandia National Laboratories + Steve Plimpton, sjplimp@sandia.gov + + Copyright (2003) Sandia Corporation. Under the terms of Contract + DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains + certain rights in this software. This software is distributed under + the GNU General Public License. + + See the README file in the top-level LAMMPS directory. +------------------------------------------------------------------------- */ + +/* ---------------------------------------------------------------------- + Contributing author: Axel Kohlmeyer (Temple U) +------------------------------------------------------------------------- */ + +#include "bond_harmonic_shift_cut_omp.h" +#include "atom.h" +#include "comm.h" +#include "force.h" +#include "neighbor.h" +#include "timer.h" + +#include <cmath> + +#include "suffix.h" +using namespace LAMMPS_NS; + +/* ---------------------------------------------------------------------- */ + +BondHarmonicShiftCutOMP::BondHarmonicShiftCutOMP(class LAMMPS *lmp) + : BondHarmonicShiftCut(lmp), ThrOMP(lmp,THR_BOND) +{ + suffix_flag |= Suffix::OMP; +} + +/* ---------------------------------------------------------------------- */ + +void BondHarmonicShiftCutOMP::compute(int eflag, int vflag) +{ + ev_init(eflag,vflag); + + const int nall = atom->nlocal + atom->nghost; + const int nthreads = comm->nthreads; + const int inum = neighbor->nbondlist; + +#if defined(_OPENMP) +#pragma omp parallel default(none) shared(eflag,vflag) +#endif + { + int ifrom, ito, tid; + + loop_setup_thr(ifrom, ito, tid, inum, nthreads); + ThrData *thr = fix->get_thr(tid); + thr->timer(Timer::START); + ev_setup_thr(eflag, vflag, nall, eatom, vatom, thr); + + if (inum > 0) { + if (evflag) { + if (eflag) { + if (force->newton_bond) eval<1,1,1>(ifrom, ito, thr); + else eval<1,1,0>(ifrom, ito, thr); + } else { + if (force->newton_bond) eval<1,0,1>(ifrom, ito, thr); + else eval<1,0,0>(ifrom, ito, thr); + } + } else { + if (force->newton_bond) eval<0,0,1>(ifrom, ito, thr); + else eval<0,0,0>(ifrom, ito, thr); + } + } + thr->timer(Timer::BOND); + reduce_thr(this, eflag, vflag, thr); + } // end of omp parallel region +} + +template <int EVFLAG, int EFLAG, int NEWTON_BOND> +void BondHarmonicShiftCutOMP::eval(int nfrom, int nto, ThrData * const thr) +{ + int i1,i2,n,type; + double delx,dely,delz,ebond,fbond; + double rsq,r,dr,rk; + + const dbl3_t * _noalias const x = (dbl3_t *) atom->x[0]; + dbl3_t * _noalias const f = (dbl3_t *) thr->get_f()[0]; + const int3_t * _noalias const bondlist = (int3_t *) neighbor->bondlist[0]; + const int nlocal = atom->nlocal; + ebond = 0.0; + + for (n = nfrom; n < nto; n++) { + i1 = bondlist[n].a; + i2 = bondlist[n].b; + type = bondlist[n].t; + + delx = x[i1].x - x[i2].x; + dely = x[i1].y - x[i2].y; + delz = x[i1].z - x[i2].z; + + rsq = delx*delx + dely*dely + delz*delz; + r = sqrt(rsq); + + if (r>r1[type]) continue; + + dr = r - r0[type]; + rk = k[type] * dr; + + // force & energy + + if (r > 0.0) fbond = -2.0*rk/r; + else fbond = 0.0; + + if (EFLAG) + ebond = k[type]*(dr*dr -(r0[type]-r1[type])*(r0[type]-r1[type]) ); + + // apply force to each of 2 atoms + + if (NEWTON_BOND || i1 < nlocal) { + f[i1].x += delx*fbond; + f[i1].y += dely*fbond; + f[i1].z += delz*fbond; + } + + if (NEWTON_BOND || i2 < nlocal) { + f[i2].x -= delx*fbond; + f[i2].y -= dely*fbond; + f[i2].z -= delz*fbond; + } + + if (EVFLAG) ev_tally_thr(this,i1,i2,nlocal,NEWTON_BOND, + ebond,fbond,delx,dely,delz,thr); + } +} diff --git a/pool/shard007/C++/0092051_odometry_provider.cpp b/pool/shard007/C++/0092051_odometry_provider.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eec4fb091b19a6d63b1c5509d3bc6132d4fb5099 --- /dev/null +++ b/pool/shard007/C++/0092051_odometry_provider.cpp @@ -0,0 +1,196 @@ +#include <ros/ros.h> + +#include <sensor_msgs/JointState.h> +#include <nav_msgs/Odometry.h> + +#include <message_filters/subscriber.h> +#include <message_filters/synchronizer.h> +#include <message_filters/sync_policies/approximate_time.h> + +#include <tf/transform_listener.h> + +#include <string> +#include <utility> +#include <math.h> + +// robot's index in ROS ecosystem (if multiple instances) +std::string tf_prefix; + +// publisher in IMU for imu message +ros::Publisher publisher; + +double WHEELS_HALF_SPACING = 0.15; +double WHEEL_RADIUS = 0.098; + +double pos_x = 0; +double pos_y = 0; +double pos_th = 0; +double left_steps=-5; // range from -PI to PI +double right_steps=-5; +bool dir_left = true; // direction of rotation of left wheel true== forward +bool dir_right = true; // direction of rotation of right wheel true== forward +ros::Time last_time; + +double left_angular = 0; +double right_angular = 0; + +std::string odom_frame_id="/odom"; +std::string odom_publish_topic="odom"; +std::string odom_right_wheel="hal/rightMotor/getState"; +std::string odom_left_wheel="hal/leftMotor/getState"; + +// calculates inverse kinematic value of robot heading with differencial drive +double getYaw(const double velRight, const double velLeft) { + return (WHEEL_RADIUS * (velRight - velLeft)) / (2*WHEELS_HALF_SPACING); +} + +void setWheelSpacing(const std::string & motor_left_frame,const std::string & motor_right_frame) { + // tf listener for calculation of wheel spacing + tf::TransformListener listener; + tf::StampedTransform transform; + // get length in between wheels + try { + listener.waitForTransform(tf_prefix + motor_left_frame, + tf_prefix + motor_right_frame, + ros::Time::now(), ros::Duration(10.0)); + listener.lookupTransform(tf_prefix + motor_left_frame, + tf_prefix + motor_right_frame, + ros::Time(0), transform); + WHEELS_HALF_SPACING = transform.getOrigin().absolute().getY() / 2; + ROS_INFO("DPL: motor_controler WHEELS_HALF_SPACING: %f", + WHEELS_HALF_SPACING); + + } catch (tf::TransformException ex) { + ROS_ERROR("Problem with transformation between wheels: %s", ex.what()); + } +} +//! @brief Calculates angular velocity from old and new angle on joint +//! @param[in] old_steps - angle on joint in previous iteration +//! @param[in] new_steps - current angle on joint +//! @param[in] dir - direction of rotation true=forward, false = backward +//! @param[in] dt - time elapsed between measurement of old_steps and new_steps +//! @return Current angular velocity on the joint +//! +double getAngularVel(const double old_steps, const double new_steps, const bool dir,const double dt){ + if(dir && old_steps > 0 && new_steps < 0){ + // overflow from PI --> -PI + return (2* M_PI - (old_steps - new_steps)) / dt; + }else if (!dir && old_steps < 0 && new_steps > 0){ + // overflow in negative direction from -PI --> PI + return (-2*M_PI + (new_steps - old_steps)) / dt; + } + return (new_steps-old_steps) / dt; +} + +void odomData_cb(const sensor_msgs::JointState::ConstPtr &left_motor_msg, + const sensor_msgs::JointState::ConstPtr &right_motor_msg) { + nav_msgs::Odometry odom_msg; + double yaw; + double x_speed; + double dt = (left_motor_msg->header.stamp - last_time).toSec(); + + // calculate andular velocities from angular diplacement in both joints + if(left_steps > -4 || right_steps > -4){ + if(dt != 0){ + left_angular = getAngularVel(left_steps, left_motor_msg->position[0],dir_left,dt); + right_angular = getAngularVel(right_steps, right_motor_msg->position[0],dir_right,dt); + } + } + if(left_angular > 0) + dir_left = true; + else + dir_left = false; + if (right_angular > 0) + dir_right = true; + else + dir_right = false; + right_steps = right_motor_msg->position[0]; + left_steps = left_motor_msg->position[0]; + // calculate robot's forward speed and yaw + x_speed = (WHEEL_RADIUS * + (left_angular + right_angular)) / 2; + yaw = getYaw(right_angular, left_angular); + + // move old point in 2D space to new predicted position and an angle + if(dt != 0){ + pos_x += (x_speed * cos(pos_th)) * dt; + pos_y += (x_speed * sin(pos_th)) * dt; + pos_th += yaw * dt; + } + + geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(pos_th); + + // create odom msg + odom_msg.header.frame_id = tf_prefix + odom_frame_id; + odom_msg.header.stamp = last_time; + odom_msg.pose.pose.position.x = pos_x; + odom_msg.pose.pose.position.y = pos_y; + odom_msg.pose.pose.orientation = odom_quat; + odom_msg.child_frame_id = tf_prefix + "/base_footprint"; + odom_msg.twist.twist.linear.x = x_speed; + odom_msg.twist.twist.angular.z = yaw; + // add covariance + double c =10e-4; + odom_msg.pose.covariance={c,0,0,0,0,0, + 0,c,0,0,0,0, + 0,0,c,0,0,0, + 0,0,0,c,0,0, + 0,0,0,0,c,0, + 0,0,0,0,0,c}; + odom_msg.twist.covariance={c,0,0,0,0,0, + 0,c,0,0,0,0, + 0,0,c,0,0,0, + 0,0,0,c,0,0, + 0,0,0,0,c,0, + 0,0,0,0,0,c}; + publisher.publish(odom_msg); + + last_time = left_motor_msg->header.stamp; +} + +int main(int argc, char **argv) { + ros::init(argc, argv, "odometryProvider"); + ros::NodeHandle n; + std::string frame_id_left_wheel="/base/joint1"; + std::string frame_id_right_wheel="/base/joint0"; + + // get parameters + std::string tf_prefix_path; + if (n.searchParam("tf_prefix", tf_prefix_path)) + { + n.getParam(tf_prefix_path, tf_prefix); + } + ros::param::get("~leftWheelTopic", odom_left_wheel); + ros::param::get("~rightWheelTopic", odom_right_wheel); + ros::param::get("~odomPublTopic", odom_publish_topic); + ros::param::get("~frameIDLeftWheel", frame_id_left_wheel); + ros::param::get("~frameIDRightWheel", frame_id_right_wheel); + ros::param::get("~frameIDodom", odom_frame_id); + + last_time = ros::Time::now(); + setWheelSpacing(frame_id_left_wheel,frame_id_right_wheel); + + // subscribers to motors' states and imu + message_filters::Subscriber<sensor_msgs::JointState> left_motor_sub( + n, odom_left_wheel, 1000); + message_filters::Subscriber<sensor_msgs::JointState> right_motor_sub( + n, odom_right_wheel, 1000); + + // sync messages using approximate alghorithm + constexpr int allowed_delay = 10; + typedef message_filters::sync_policies::ApproximateTime< + sensor_msgs::JointState, sensor_msgs::JointState> OdomSyncPolicy; + message_filters::Synchronizer<OdomSyncPolicy> odom_processor( + OdomSyncPolicy(allowed_delay), left_motor_sub, right_motor_sub); + odom_processor.registerCallback(odomData_cb); + + // publish fused message + publisher = n.advertise<nav_msgs::Odometry>(odom_publish_topic, 1000); + + ROS_INFO("DPL: OdomProvider initialized"); + + // runs event loop + ros::spin(); + + return 0; +} diff --git a/pool/shard007/C++/0092053_main.cpp b/pool/shard007/C++/0092053_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d63eac30b68019a3ccbd935cff0ba178f4ebb74f --- /dev/null +++ b/pool/shard007/C++/0092053_main.cpp @@ -0,0 +1,45 @@ +/* + Copyright 2017 John Selbie + 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 "stdafx.h" +#include "sudokuboard.h" + + +int main(int argc, char* argv[]) +{ + SudokuBoard board; + + if (argc < 2) + { + std::cout << "Usage: " << argv[0] << " filename" << std::endl; + } + else + { + std::cout << "Loading: " << argv[1] << std::endl; + bool loadresult = board.LoadFromFile(argv[1]); + + if (loadresult == false) + { + std::cout << "Failed to load board from file" << std::endl; + } + else + { + board.Solve(); + } + } + + return 0; +} + diff --git a/pool/shard007/C++/0092059_user.cpp b/pool/shard007/C++/0092059_user.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c97e6c0715848362a58f054c532a19041690264 --- /dev/null +++ b/pool/shard007/C++/0092059_user.cpp @@ -0,0 +1,72 @@ +#include "user.h" +/** + * create a user the old school way + * @brief User::User + * @param email + * @param pass + * @param role the users role + * @author Michael + */ +User::User( QString email, QString pass, QString role ) { + this->email = email; + this->pass = pass; + this->role = role; + this->insertString = email + "|" + pass + "|" + role; +} +/** + * create a user with the insert string that is stored in the file + * @brief User::User + * @param insertString + * @author Michael + */ +User::User( QString insertString ) { + this->insertString = insertString; + QStringList decode = insertString.split( "|" ); + this->email = decode.value( 0 ); + this->pass = decode.value( 1 ); + this->role = decode.value( 2 ); +} + +//generated getters and setters put user code above this --michael +QString User::toString(){ + return QString( "%1, %2, %3" ).arg( this->email, this->pass, this->role ); +} + +QString User::getEmail() const +{ + return email; +} + +void User::setEmail(const QString &value) +{ + email = value; +} +QString User::getPass() const +{ + return pass; +} + +void User::setPass(const QString &value) +{ + pass = value; +} +QString User::getRole() const +{ + return role; +} +QString User::getInsertString() const +{ + return insertString; +} + +void User::setInsertString(const QString &value) +{ + insertString = value; +} + +void User::setRole(const QString &value) +{ + role = value; +} + + diff --git a/pool/shard007/C++/0092062_Position.cpp b/pool/shard007/C++/0092062_Position.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d3b98b659e29d03e1a8e6db130fea8e908ad8bcb --- /dev/null +++ b/pool/shard007/C++/0092062_Position.cpp @@ -0,0 +1,143 @@ +/* + * Position.cpp + * + * Created on: 15/07/2014 + * Author: paco + * + * Copyright 2014 Francisco Martín + * + * This file is part of ATCSim. + * + * ATCSim is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ATCSim is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with ATCSim. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "Position.h" +#include <math.h> + +namespace atcsim{ + +Position::Position() { + + name = ""; + x = y = 0.0; + z = MAINTAIN_ALT; +} + +Position::Position(float _x, float _y) +{ + name = ""; + x = _x; + y = _y; + z = MAINTAIN_ALT; +} + +Position::Position(float _x, float _y, float _z) +{ + name = ""; + x = _x; + y = _y; + z = _z; +} + +Position::Position(std::string _name, float _x, float _y) +{ + name = check_name(_name); + x = _x; + y = _y; + z = MAINTAIN_ALT; +} + +Position::Position(std::string _name, float _x, float _y, float _z) +{ + name = check_name(_name); + x = _x; + y = _y; + z = _z; +} + +Position::~Position() { + +} + +std::string Position::check_name(std::string name) +{ + ushort max_length = 5; + std::string aux; + // Limit name to 5 characters + if(name.length() > max_length) + { + aux = name.substr(0, max_length); + } + // Fill name to 5 characters + else if(name.length() < max_length) + { + aux = name.substr(0, name.length()); + for(int i=name.length(); i<max_length; i++) + aux += "0"; + } + else + { + aux = name; + } + + return aux; +} + +float +Position::distance(Position pos) +{ + return sqrtf( ( (x - pos.get_x()) * (x - pos.get_x()) ) + + ( (y - pos.get_y()) * (y - pos.get_y()) ) + + ( (z - pos.get_z()) * (z - pos.get_z()) ) ); +} + +float +Position::distanceXY(Position pos) +{ + return sqrtf( ((x-pos.get_x())*(x-pos.get_x())) + ((y-pos.get_y())*(y-pos.get_y()))); +} + +float +Position::distX_EjeBody(Position pos1, Position pos2) +{ + float betta = atan2f(pos1.get_y()-y, pos1.get_x()-x); + + return cos(betta)*(pos2.get_x()-pos1.get_x()) + sin(betta)*(pos2.get_y()-pos1.get_y()); +} + +float +Position::get_angle(Position pos1, Position pos2) +{ + float u1, u2, v1, v2; + + u1 = pos1.get_x()-x; + u2 = pos1.get_y()-y; + v1 = pos2.get_x()-pos1.get_x(); + v2 = pos2.get_y()-pos1.get_y(); + + return acos((fabs(u1*v1+u2*v2)) / (sqrt(u1*u1+u2*u2)*sqrt(v1*v1+v2*v2))); +} + +void +Position::angles(Position pos, float &bearing, float &inclination) +{ + float distxy; + + distxy = sqrtf( ((x-pos.get_x())*(x-pos.get_x())) + ((y-pos.get_y())*(y-pos.get_y()))); + + bearing = atan2f(y-pos.get_y(), x-pos.get_x()); + inclination = atan2f(pos.get_z()-z, distxy); +} + +} // namespace atcsim diff --git a/pool/shard007/C++/0092068_CSPEC.cpp b/pool/shard007/C++/0092068_CSPEC.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d2b8194cd803afcd671f8072d1ba7c73a699d668 --- /dev/null +++ b/pool/shard007/C++/0092068_CSPEC.cpp @@ -0,0 +1,36 @@ +// Copyright (C) 2022 European Spallation Source, see LICENSE file +//===----------------------------------------------------------------------===// +/// +/// \file +/// +/// \brief CSPEC detector +/// +//===----------------------------------------------------------------------===// + +#include <common/detector/Detector.h> + +#include "CSPECBase.h" + +static struct Cspec::CSPECSettings LocalCSPECSettings; + +void SetCLIArguments(CLI::App __attribute__((unused)) & parser) { + parser + .add_option("--dumptofile", LocalCSPECSettings.FilePrefix, + "dump to specified file") + ->group("CSPEC"); + + parser + .add_option("-f, --file", LocalCSPECSettings.ConfigFile, + "CSPEC specific configuration (json) file") + ->group("CSPEC"); +} + +PopulateCLIParser PopulateParser{SetCLIArguments}; + +class CSPEC : public Cspec::CSPECBase { +public: + explicit CSPEC(BaseSettings Settings) + : Cspec::CSPECBase(std::move(Settings), LocalCSPECSettings) {} +}; + +DetectorFactory<CSPEC> Factory; diff --git a/pool/shard007/C++/0092073_deadmines.cpp b/pool/shard007/C++/0092073_deadmines.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b2238c89e82559d015819a089ab3b81cab7bf7ab --- /dev/null +++ b/pool/shard007/C++/0092073_deadmines.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/> + * Copyright (C) 2005-2012 MaNGOS <http://www.getmangos.com/> + * Copyright (C) 2008-2012 Trinity <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* ScriptData +SDName: Deadmines +SD%Complete: 0 +SDComment: Placeholder +SDCategory: Deadmines +EndScriptData */ + +#include "ScriptPCH.h" +#include "deadmines.h" +#include "Spell.h" + +/*##### +# item_Defias_Gunpowder +#####*/ + +class item_defias_gunpowder : public ItemScript +{ +public: + item_defias_gunpowder() : ItemScript("item_defias_gunpowder") { } + + bool OnUse(Player* player, Item* item, SpellCastTargets const& targets) + { + InstanceScript *pInstance = player->GetInstanceScript(); + + if (!pInstance) + { + player->GetSession()->SendNotification("Instance script not initialized"); + return true; + } + if (pInstance->GetData(EVENT_STATE)!= CANNON_NOT_USED) + return false; + if (targets.getGOTarget() && targets.getGOTarget()->GetTypeId() == TYPEID_GAMEOBJECT && + targets.getGOTarget()->GetEntry() == GO_DEFIAS_CANNON) + { + pInstance->SetData(EVENT_STATE, CANNON_GUNPOWDER_USED); + } + + player->DestroyItemCount(item->GetEntry(), 1, true); + return true; + } +}; + +void AddSC_deadmines() +{ + new item_defias_gunpowder(); +} \ No newline at end of file diff --git a/pool/shard007/C++/0092076_chessbox.cpp b/pool/shard007/C++/0092076_chessbox.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5fa128250d1be07e8750dd38f211a7b41d131465 --- /dev/null +++ b/pool/shard007/C++/0092076_chessbox.cpp @@ -0,0 +1,95 @@ +#include "chessbox.h" +#include <QPaintEvent> +#include <QDebug> +#include <QString> +#include <QPainter> +#include <QPen> + +chessBox::chessBox(QWidget *parent) : + QWidget(parent) +{ +} + +//===============================================// +//¹¦ÄÜ:½ÓÊÕÆåÅÌÐÅÏ¢ // +//²ÎÊý:c[SIZE][SIZE] ÆåÅÌÐÅÏ¢ // +//==============================================// +void chessBox::setChess(int c[SIZE][SIZE]) +{ + for(int j=0;j<SIZE;j++) + { + for(int i=0;i<SIZE;i++) + { + chess[j][i] = c[j][i]; + } + } +} + +//»æÍ¼Ê¼þ£¬»æÖÆÆåÅÌ£¬»æÖÆÂä×Ó +void chessBox::paintEvent(QPaintEvent *ev) +{ + //È·¶¨Íø¸ñ¿í¶È + if(this->width() <= this->height()) + { + w = this->width()/8; + } + if(this->width() > this->height()) + { + w = this->height()/8; + } + + //È·¶¨ÆðÊ¼×ø±ê + startX = this->width()/2 - (SIZE/2)*w; + startY = this->height()/2 - (SIZE/2)*w; + + QPainter p(this); + QPen pen; + pen.setColor(Qt::blue); + pen.setWidth(2); + p.setPen(pen); + + //»æÖÆÆåÅÌ + for(int j=0;j<SIZE;j++) + { + for(int i=0;i<SIZE;i++) + { + p.drawRect(startX+i*w, startY+j*w, w, w); + } + } + + //ÔÚÖ¸¶¨Î»ÖûæÖÆÆå×Ó + for(int j=0;j<SIZE;j++) + { + for(int i=0;i<SIZE;i++) + { + if(chess[i][j] == WHITE) + { + p.drawPixmap(startX+i*w, startY+j*w, w, w, + QPixmap(":/new/prefix1/0.png")); + } + if(chess[i][j] == BLACK) + { + p.drawPixmap(startX+i*w, startY+j*w, w, w, + QPixmap(":/new/prefix1/1.png")); + } + } + } +} + +//Êó±êµã»÷ʼþ +void chessBox::mousePressEvent(QMouseEvent *ev) +{ + //¸ù¾ÝÊó±êµã»÷×ø±ê¼ÆËãÍø¸ñ×ø±ê + int drawX = (ev->x()-startX)/w; + int drawY = (ev->y()-startY)/w; + int button = ev->button(); + //µã»÷×ø±êÔÚÆåÅÌÄÚ£¬²ÅËãÓÐЧ + if(ev->x()<startX || ev->x()>startX+w*SIZE || ev->y()<startY || ev->y()>startY+w*SIZE) + { + return; + } + if(button == Qt::LeftButton) + { + emit drawPos(drawX, drawY); + } +} diff --git a/pool/shard007/C++/0092081_LeapInterfaceUtility.cpp b/pool/shard007/C++/0092081_LeapInterfaceUtility.cpp new file mode 100644 index 0000000000000000000000000000000000000000..59137565973d518eca1e8743cba8721a426d3da3 --- /dev/null +++ b/pool/shard007/C++/0092081_LeapInterfaceUtility.cpp @@ -0,0 +1,238 @@ +#include "LeapMotionPrivatePCH.h" +#include "IHeadMountedDisplay.h" +#include "LeapGesture.h" + +DEFINE_LOG_CATEGORY(LeapPluginLog); +#define LEAP_TO_UE_SCALE 0.1f +#define UE_TO_LEAP_SCALE 10.f +#define LEAP_MOUNT_OFFSET 8.f //in cm (UE units) forming FVector(LEAP_MOUNT_OFFSET,0,0) forward vector + +//NB: localized variable for transforms +bool LeapShouldAdjustForFacing = false; +bool LeapShouldAdjustRotationForHMD = false; +bool LeapShouldAdjustPositionForHMD = false; +bool LeapShouldAdjustForMountOffset = true; + +FRotator CombineRotators(FRotator A, FRotator B) +{ + FQuat AQuat = FQuat(A); + FQuat BQuat = FQuat(B); + + return FRotator(BQuat*AQuat); +} + +FVector adjustForLeapFacing(FVector in) +{ + FRotator rotation = FRotator(90.f, 0.f, 180.f); + return FQuat(rotation).RotateVector(in); +} + +FVector adjustForHMD(FVector in) +{ + if (GEngine->HMDDevice.IsValid()) + { + FQuat orientationQuat; + FVector position; + GEngine->HMDDevice->GetCurrentOrientationAndPosition(orientationQuat, position); + FVector out = orientationQuat.RotateVector(in); + if (LeapShouldAdjustPositionForHMD) + { + if (LeapShouldAdjustForMountOffset) + position += orientationQuat.RotateVector(FVector(LEAP_MOUNT_OFFSET, 0, 0)); + out += position; + } + return out; + } + else + return in; + +} + +FVector adjustForHMDOrientation(FVector in) +{ + if (GEngine->HMDDevice.IsValid()) + { + FQuat orientationQuat; + FVector position; + GEngine->HMDDevice->GetCurrentOrientationAndPosition(orientationQuat, position); + FVector out = orientationQuat.RotateVector(in); + return out; + } + else + return in; + +} + +//Conversion - use find and replace to change behavior, no scaling version is typically used for orientations +FVector convertLeapToUE(Leap::Vector leapVector) +{ + //Convert Axis + FVector vect = FVector(-leapVector.z, leapVector.x, leapVector.y); + + //Hmd orientation adjustment + if (LeapShouldAdjustForFacing) + { + FRotator rotation = FRotator(90.f, 0.f, 180.f); + vect = FQuat(rotation).RotateVector(vect); + + if (LeapShouldAdjustRotationForHMD) + { + if (GEngine->HMDDevice.IsValid()) + { + FQuat orientationQuat; + FVector position; + GEngine->HMDDevice->GetCurrentOrientationAndPosition(orientationQuat, position); + vect = orientationQuat.RotateVector(vect); + } + } + } + + return vect; +} + +FVector convertAndScaleLeapToUE(Leap::Vector leapVector) +{ + //Scale from mm to cm (ue default) + FVector vect = FVector(-leapVector.z * LEAP_TO_UE_SCALE, leapVector.x * LEAP_TO_UE_SCALE, leapVector.y * LEAP_TO_UE_SCALE); + + //Front facing leap adjustments + if (LeapShouldAdjustForFacing) + { + vect = adjustForLeapFacing(vect); + if (LeapShouldAdjustRotationForHMD) + vect = adjustForHMD(vect); + } + return vect; +} + +FMatrix convertLeapBasisMatrix(Leap::Matrix leapMatrix) +{ + /* + Leap Basis depends on hand type with -z, x, y as general format. This then needs to be inverted to point correctly (x = forward), which yields the matrix below. + */ + FVector inX, inY, inZ, inW; + inX.Set(leapMatrix.zBasis.z, -leapMatrix.zBasis.x, -leapMatrix.zBasis.y); + inY.Set(-leapMatrix.xBasis.z, leapMatrix.xBasis.x, leapMatrix.xBasis.y); + inZ.Set(-leapMatrix.yBasis.z, leapMatrix.yBasis.x, leapMatrix.yBasis.y); + inW.Set(-leapMatrix.origin.z, leapMatrix.origin.x, leapMatrix.origin.y); + + if (LeapShouldAdjustForFacing) + { + inX = adjustForLeapFacing(inX); + inY = adjustForLeapFacing(inY); + inZ = adjustForLeapFacing(inZ); + inW = adjustForLeapFacing(inW); + + if (LeapShouldAdjustRotationForHMD){ + inX = adjustForHMDOrientation(inX); + inY = adjustForHMDOrientation(inY); + inZ = adjustForHMDOrientation(inZ); + inW = adjustForHMDOrientation(inW); + } + } + + + return (FMatrix(inX, inY, inZ, inW)); +} +FMatrix swapLeftHandRuleForRight(const FMatrix& ueMatrix) +{ + FMatrix matrix = ueMatrix; + //Convenience method to swap the axis correctly, already in UE format to swap Y instead of leap Z + FVector inverseVector = -matrix.GetUnitAxis(EAxis::Y); + matrix.SetAxes(NULL, &inverseVector, NULL, NULL); + return matrix; +} + +Leap::Vector convertUEToLeap(FVector ueVector) +{ + return Leap::Vector(ueVector.Y, ueVector.Z, -ueVector.X); +} + +Leap::Vector convertAndScaleUEToLeap(FVector ueVector) +{ + return Leap::Vector(ueVector.Y * UE_TO_LEAP_SCALE, ueVector.Z * UE_TO_LEAP_SCALE, -ueVector.X * UE_TO_LEAP_SCALE); +} + +float scaleLeapToUE(float leapFloat) +{ + return leapFloat * LEAP_TO_UE_SCALE; //mm->cm +} + +float scaleUEToLeap(float ueFloat) +{ + return ueFloat * UE_TO_LEAP_SCALE; //mm->cm +} + +void LeapSetShouldAdjustForFacing(bool shouldRotate) +{ + LeapShouldAdjustForFacing = shouldRotate; +} + +void LeapSetShouldAdjustForHMD(bool shouldRotate, bool shouldOffset) +{ + LeapShouldAdjustRotationForHMD = shouldRotate; + LeapShouldAdjustPositionForHMD = shouldOffset; +} + +void LeapSetShouldAdjustForMountOffset(bool shouldAddOffset) +{ + LeapShouldAdjustForMountOffset = shouldAddOffset; +} + +LeapBasicDirection basicDirection(FVector direction) +{ + float x = FMath::Abs(direction.X); + float y = FMath::Abs(direction.Y); + float z = FMath::Abs(direction.Z); + + //is basic in x? + if (x >= y && x >= z) + { + if (direction.X < -0.5) + return LeapBasicDirection::DIRECTION_TOWARD; + else if (direction.X > 0.5) + return LeapBasicDirection::DIRECTION_AWAY; + } + //is basic in y? + else if (y >= x && y >= z) + { + if (direction.Y < -0.5) + return LeapBasicDirection::DIRECTION_LEFT; + else if (direction.Y > 0.5) + return LeapBasicDirection::DIRECTION_RIGHT; + } + //is basic in z? + else if (z >= x && z >= y) + { + if (direction.Z < -0.5) + return LeapBasicDirection::DIRECTION_DOWN; + else if (direction.Z > 0.5) + return LeapBasicDirection::DIRECTION_UP; + } + + //If we haven't returned by now, the direction is none + return LeapBasicDirection::DIRECTION_NONE; +} + +//Utility function used to debug address allocation - helped find the cdcdcdcd allocation error +void UtilityDebugAddress(void* pointer) +{ + const void * address = static_cast<const void*>(pointer); + std::stringstream ss; + ss << address; + std::string name = ss.str(); + FString string(name.c_str()); + + UE_LOG(LeapPluginLog, Warning, TEXT("Address: %s"), *string); +} + +//Utility function to handle uncaught GC pointer releases (which will typically pass null checks) +//This is hacky, but guarantees certain GC releases will be caught, make a pull request if you know a better way to handle these cases +bool UtilityPointerIsValid(void* pointer) +{ +#if PLATFORM_32BITS + return (pointer != nullptr && pointer != (void*)0xdddddddd); +#else + return (pointer != nullptr && pointer != (void*)0xdddddddddddddddd); +#endif +} diff --git a/pool/shard007/C++/0092083_userinfo.cpp b/pool/shard007/C++/0092083_userinfo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..559fa4d4dbf0ac1bbb0cefd00ada4956429685bf --- /dev/null +++ b/pool/shard007/C++/0092083_userinfo.cpp @@ -0,0 +1,36 @@ +#include "userinfo.h" + +namespace nicolive { + +UserInfo::UserInfo(QString userID, QObject* parent) : HttpGetter(parent) +{ + this->userID = userID; +} + +void UserInfo::get() +{ + // make request + QNetworkRequest rq; + rq.setUrl(QUrl("http://api.ce.nicovideo.jp/api/v1/user.info?user_id=" + userID)); + + requestGet(rq); +} + +void UserInfo::gotReply(QNetworkReply* reply) +{ + StrAbstractor userinfo(QString(reply->readAll())); + + QString status = userinfo.midStr("status=\"", "\">"); + + if (status != "ok") { + const QString& code = userinfo.midStr("<code>", "</code>"); + const QString& description = userinfo.midStr("<description>", "</description>"); + emit error(code, description); + return; + } + + const QString& username = userinfo.midStr("<nickname>", "</nickname>"); + emit got(username); +} + +} diff --git a/pool/shard007/C++/0092085_ElementFactory.cpp b/pool/shard007/C++/0092085_ElementFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1174abfff91949ab6a2c027ee9ec46d0e7978c5 --- /dev/null +++ b/pool/shard007/C++/0092085_ElementFactory.cpp @@ -0,0 +1,105 @@ +/* + Copyright (C) 2007,2008 Richard Quirk + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ +#include <vector> +#include "ElementFactory.h" +#include "HtmlAnchorElement.h" +#include "HtmlImageElement.h" +#include "HtmlMetaElement.h" +#include "HtmlBodyElement.h" +#include "HtmlBlockElement.h" +#include "HtmlPreElement.h" +#include "HtmlOptionElement.h" +#include "HtmlFormElement.h" +#include "HtmlInputElement.h" +#include "HtmlTextAreaElement.h" +#include "HtmlElement.h" +#include "HtmlConstants.h" + + +HtmlElement * ElementFactory::create(const std::string & elementType) +{ + if (elementType == HtmlConstants::A_TAG) + { + return new HtmlAnchorElement(elementType); + } + else if (elementType == HtmlConstants::META_TAG) + { + return new HtmlMetaElement(elementType); + } + else if (elementType == HtmlConstants::IMG_TAG) + { + return new HtmlImageElement(elementType); + } + else if (elementType == HtmlConstants::BODY_TAG) + { + return new HtmlBodyElement(elementType); + } + else if (elementType == HtmlConstants::P_TAG or elementType == HtmlConstants::DIV_TAG) + { + return new HtmlBlockElement(elementType); + } + else if (elementType == HtmlConstants::PRE_TAG) + { + return new HtmlPreElement(elementType); + } + else if (elementType == HtmlConstants::OPTION_TAG) + { + return new HtmlOptionElement(elementType); + } + else if (elementType == HtmlConstants::FORM_TAG) + { + return new HtmlFormElement(elementType); + } + else if (elementType == HtmlConstants::INPUT_TAG) + { + return new HtmlInputElement(elementType); + } + else if (elementType == HtmlConstants::SELECT_TAG) + { + return new HtmlInputElement(elementType); + } + else if (elementType == HtmlConstants::TEXTAREA_TAG) + { + return new HtmlTextAreaElement(elementType); + } + /* + else if (elementType == HtmlConstants::UL_TAG or elementType == HtmlConstants::OL_TAG or elementType == HtmlConstants::LI_TAG) + { + // lists have a pricipal box, then inline item boxes. + return new HtmlListElement(elementType); + } + */ + + return new HtmlElement(elementType); +} + +HtmlElement * ElementFactory::create(const std::string & elementType, + const AttributeVector & attrs) +{ + HtmlElement * element(create(elementType)); + AttributeVector::const_iterator it(attrs.begin()); + for (; it != attrs.end(); ++it) { + Attribute * attr(*it); + element->setAttribute(attr->name, attr->value); + } + return element; +} + +void ElementFactory::remove(HtmlElement * element) +{ + delete element; +} diff --git a/pool/shard007/C++/0092091_saslsessionfeature.cpp b/pool/shard007/C++/0092091_saslsessionfeature.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d694ab04c7a650dc62cb15253fe9fe0273f4324c --- /dev/null +++ b/pool/shard007/C++/0092091_saslsessionfeature.cpp @@ -0,0 +1,75 @@ +#include "saslsessionfeature.h" + +#include <definitions/namespaces.h> +#include <definitions/xmppstanzahandlerorders.h> +#include <utils/xmpperror.h> +#include <utils/stanza.h> +#include <utils/logger.h> + +SASLSessionFeature::SASLSessionFeature(IXmppStream *AXmppStream) : QObject(AXmppStream->instance()) +{ + FXmppStream = AXmppStream; +} + +SASLSessionFeature::~SASLSessionFeature() +{ + FXmppStream->removeXmppStanzaHandler(XSHO_XMPP_FEATURE,this); + emit featureDestroyed(); +} + +bool SASLSessionFeature::xmppStanzaIn(IXmppStream *AXmppStream, Stanza &AStanza, int AOrder) +{ + if (AXmppStream==FXmppStream && AOrder==XSHO_XMPP_FEATURE && AStanza.id()=="session") + { + if (AStanza.type() == "result") + { + LOG_STRM_INFO(FXmppStream->streamJid(),"Session started"); + deleteLater(); + emit finished(false); + } + else + { + XmppStanzaError err(AStanza); + LOG_STRM_INFO(FXmppStream->streamJid(),QString("Failed to start session: %1").arg(err.condition())); + emit error(err); + } + return true; + } + return false; +} + +bool SASLSessionFeature::xmppStanzaOut(IXmppStream *AXmppStream, Stanza &AStanza, int AOrder) +{ + Q_UNUSED(AXmppStream); Q_UNUSED(AStanza); Q_UNUSED(AOrder); + return false; +} + +QString SASLSessionFeature::featureNS() const +{ + return NS_FEATURE_SESSION; +} + +IXmppStream *SASLSessionFeature::xmppStream() const +{ + return FXmppStream; +} + +bool SASLSessionFeature::start(const QDomElement &AElem) +{ + if (AElem.tagName() == "session") + { + Stanza session("iq"); + session.setType("set").setId("session"); + session.addElement("session",NS_FEATURE_SESSION); + FXmppStream->insertXmppStanzaHandler(XSHO_XMPP_FEATURE,this); + FXmppStream->sendStanza(session); + LOG_STRM_INFO(FXmppStream->streamJid(),"Session start request sent"); + return true; + } + else + { + LOG_STRM_WARNING(FXmppStream->streamJid(),QString("Failed to start session: Invalid element=%1").arg(AElem.tagName())); + } + deleteLater(); + return false; +} diff --git a/pool/shard007/C++/0092093_Slider.cpp b/pool/shard007/C++/0092093_Slider.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c635534848e70112e826cd1a61a481b170946244 --- /dev/null +++ b/pool/shard007/C++/0092093_Slider.cpp @@ -0,0 +1,110 @@ +/* + * Slider.cpp + * + * Created on: 26.03.2012 + * Author: michi + */ + +#include "Slider.h" +#include "../../lib/kaba/kaba.h" + +Slider::Slider() +{ + value_min = 0; + value_max = 0; + factor = 1; + panel = nullptr; + event_handler_id[0] = -1; + event_handler_id[1] = -1; +} + + +Slider::Slider(hui::Panel *_panel, const string & _id_slider, const string & _id_edit, float _v_min, float _v_max, float _factor, const hui::Callback &_func, float _value) +{ + panel = _panel; + id_slider = _id_slider; + id_edit = _id_edit; + value_min = _v_min; + value_max = _v_max; + factor = _factor; + func = _func; + + event_handler_id[0] = panel->event(id_slider, [=]{ on_slide(); }); + event_handler_id[1] = panel->event(id_edit, [=]{ on_edit(); }); + + set(_value); +} + + + +Slider::Slider(hui::Panel *_panel, const string & _id_slider, const string & _id_edit, float _v_min, float _v_max, float _factor, kaba::Function *_func, float _value) +{ + panel = _panel; + id_slider = _id_slider; + id_edit = _id_edit; + value_min = _v_min; + value_max = _v_max; + factor = _factor; + auto *ff = (hui::kaba_member_callback*)_func->address; + func = [=]{ ff(panel); }; + + event_handler_id[0] = panel->event(id_slider, [=]{ on_slide(); }); + event_handler_id[1] = panel->event(id_edit, [=]{ on_edit(); }); + + set(_value); +} + + +Slider::~Slider() +{ + if (panel){ + panel->remove_event_handler(event_handler_id[0]); + panel->remove_event_handler(event_handler_id[1]); + } +} + +void Slider::__init_ext__(hui::Panel *_panel, const string &_id_slider, const string &_id_edit, float _v_min, float _v_max, float _factor, kaba::Function *_func, float _value) +{ + new(this) Slider(_panel, _id_slider, _id_edit, _v_min, _v_max, _factor, _func, _value); +} + +void Slider::__delete__() +{ + this->Slider::~Slider(); +} + +void Slider::set(float value) +{ + panel->set_float(id_slider, (value - value_min) / (value_max - value_min)); + panel->set_float(id_edit, value * factor); +} + + + +float Slider::get() +{ + return panel->get_float(id_edit) / factor; +} + + +void Slider::enable(bool enabled) +{ + panel->enable(id_slider, enabled); + panel->enable(id_edit, enabled); +} + + +void Slider::on_slide() +{ + float value = value_min + panel->get_float(id_slider) * (value_max - value_min); + panel->set_float(id_edit, value * factor); + func(); +} + +void Slider::on_edit() +{ + float value = panel->get_float(id_edit) / factor; + panel->set_float(id_slider, (value - value_min) / (value_max - value_min)); + func(); +} + diff --git a/pool/shard007/C++/0092102_test_cxx.cpp b/pool/shard007/C++/0092102_test_cxx.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a3735a6e1578e1965929ae135be69fc782aec67 --- /dev/null +++ b/pool/shard007/C++/0092102_test_cxx.cpp @@ -0,0 +1,63 @@ +/** + * Just a small test file to ensure that Sylvan can compile in C++ + */ + +#include <assert.h> +#include <sylvan.h> +#include <sylvan_obj.hpp> + +#include "test_assert.h" + +using namespace sylvan; + +TASK_0(int, runtest) +{ + Bdd one = Bdd::bddOne(); + Bdd zero = Bdd::bddZero(); + + test_assert(one != zero); + test_assert(one == !zero); + + Bdd v1 = Bdd::bddVar(1); + Bdd v2 = Bdd::bddVar(2); + + Bdd t = v1 + v2; + Bdd u = v1; + u += v2; + + test_assert(t == u); + + BddMap map; + map.put(2, t); + + test_assert(v2.Compose(map) == (v1 + v2)); + test_assert((t * v2) == v2); + + return 0; +} + +void test6() +{ + BddMap m1; + BddMap m2(m1); // this triggers an assertion +} + +int main() +{ + // Standard Lace initialization with 1 worker + lace_start(1, 0); + + // Simple Sylvan initialization, also initialize BDD support + sylvan_set_sizes(1LL<<16, 1LL<<16, 1LL<<16, 1LL<<16); + sylvan_init_package(); + sylvan_init_bdd(); + + test6(); + + int res = RUN(runtest); + + sylvan_quit(); + lace_stop(); + + return res; +} diff --git a/pool/shard007/C++/0092106_ODi_FontFaceDecls.cpp b/pool/shard007/C++/0092106_ODi_FontFaceDecls.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ed167dc0b496d9f9e496549da584fb1016efc1e1 --- /dev/null +++ b/pool/shard007/C++/0092106_ODi_FontFaceDecls.cpp @@ -0,0 +1,91 @@ +/* AbiSource + * + * Copyright (C) 2005 INdT + * Author: Daniel d'Andrada T. de Carvalho <daniel.carvalho@indt.org.br> + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301 USA. + */ + +// Class definition include +#include "ODi_FontFaceDecls.h" + +// Internal includes +#include "ODi_ListenerStateAction.h" + +// AbiWord includes +#include <ut_misc.h> + + +/** + * Constructor + */ +ODi_FontFaceDecls::ODi_FontFaceDecls(ODi_ElementStack& rElementStack) + : ODi_ListenerState("FontFaceDecls", rElementStack) +{ +} + + +/** + * + */ +void ODi_FontFaceDecls::startElement (const gchar* pName, + const gchar** ppAtts, + ODi_ListenerStateAction& /*rAction*/) +{ + if (!strcmp(pName, "style:font-face")) { + const gchar* pStyleName; + const gchar* pFontFamily; + std::string fontFamily; + + pStyleName = UT_getAttribute("style:name", ppAtts); + UT_ASSERT(pStyleName); + + pFontFamily = UT_getAttribute("svg:font-family", ppAtts); + UT_ASSERT_HARMLESS(pFontFamily); + + fontFamily = pFontFamily; + + if (pFontFamily && (pFontFamily[0] == '\'') && (pFontFamily[strlen(pFontFamily)-1] == '\'')) { + // e.g.: Turns a "'Times New Roman'" into a "Times New Roman". + // OpenOffice.org sometimes adds those extra "'" surrounding the + // font family name if it's composed by more than one word. + m_fontFamilies[pStyleName] = + fontFamily.substr(1, fontFamily.length()-2).c_str(); + } else { + m_fontFamilies[pStyleName] = pFontFamily; + } + } +} + + +/** + * + */ +void ODi_FontFaceDecls::endElement (const gchar* pName, + ODi_ListenerStateAction& rAction) { + if (!strcmp(pName, "office:font-face-decls")) { + rAction.popState(); + } +} + + +/** + * Returns the font family of a font face given its style name. + */ +const std::string & ODi_FontFaceDecls::getFontFamily( + const std::string& rStyleName) { + return m_fontFamilies[rStyleName]; +} diff --git a/pool/shard007/C++/0092108_task_cifar100.cpp b/pool/shard007/C++/0092108_task_cifar100.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0850af621debcd9b9fa4d11e50fe3634d467eb4 --- /dev/null +++ b/pool/shard007/C++/0092108_task_cifar100.cpp @@ -0,0 +1,209 @@ +#include "core/logger.h" +#include "task_cifar100.h" +#include "core/algorithm.h" + +using namespace nano; + +static const strings_t tlabels = +{ + "apple", + "aquarium_fish", + "baby", + "bear", + "beaver", + "bed", + "bee", + "beetle", + "bicycle", + "bottle", + "bowl", + "boy", + "bridge", + "bus", + "butterfly", + "camel", + "can", + "castle", + "caterpillar", + "cattle", + "chair", + "chimpanzee", + "clock", + "cloud", + "cockroach", + "couch", + "crab", + "crocodile", + "cup", + "dinosaur", + "dolphin", + "elephant", + "flatfish", + "forest", + "fox", + "girl", + "hamster", + "house", + "kangaroo", + "keyboard", + "lamp", + "lawn_mower", + "leopard", + "lion", + "lizard", + "lobster", + "man", + "maple_tree", + "motorcycle", + "mountain", + "mouse", + "mushroom", + "oak_tree", + "orange", + "orchid", + "otter", + "palm_tree", + "pear", + "pickup_truck", + "pine_tree", + "plain", + "plate", + "poppy", + "porcupine", + "possum", + "rabbit", + "raccoon", + "ray", + "road", + "rocket", + "rose", + "sea", + "seal", + "shark", + "shrew", + "skunk", + "skyscraper", + "snail", + "snake", + "spider", + "squirrel", + "streetcar", + "sunflower", + "sweet_pepper", + "table", + "tank", + "telephone", + "television", + "tiger", + "tractor", + "train", + "trout", + "tulip", + "turtle", + "wardrobe", + "whale", + "willow_tree", + "wolf", + "woman", + "worm" +}; + +cifar100_task_t::cifar100_task_t() : + mem_vision_task_t(make_dims(3, 32, 32), make_dims(100, 1, 1), 10), + m_dir(string_t(std::getenv("HOME")) + "/experiments/databases/cifar100") +{ +} + +void cifar100_task_t::from_json(const json_t& json) +{ + nano::from_json(json, "dir", m_dir, "folds", m_folds); + reconfig(make_dims(3, 32, 32), make_dims(100, 1, 1), m_folds); +} + +void cifar100_task_t::to_json(json_t& json) const +{ + nano::to_json(json, "dir", m_dir, "folds", m_folds); +} + +bool cifar100_task_t::populate() +{ + const auto bfile = m_dir + "/cifar-100-binary.tar.gz"; + + const auto train_bfile = "train.bin"; + const size_t n_train_samples = 50000; + + const auto test_bfile = "test.bin"; + const size_t n_test_samples = 10000; + + const auto op = [&] (const string_t& filename, istream_t& stream) + { + if (nano::ends_with(filename, train_bfile)) + { + return load_binary(filename, stream, protocol::train, n_train_samples); + } + else if (nano::ends_with(filename, test_bfile)) + { + return load_binary(filename, stream, protocol::test, n_test_samples); + } + else + { + return true; + } + }; + const auto error_op = [&] (const string_t& message) + { + log_error() << "CIFAR-100: " << message; + }; + + log_info() << "CIFAR-100: loading file <" << bfile << "> ..."; + + return nano::load_archive(bfile, op, error_op); +} + +bool cifar100_task_t::load_binary(const string_t& filename, istream_t& stream, const protocol p, const size_t count) +{ + log_info() << "CIFAR-100: loading file <" << filename << "> ..."; + + const auto chunk_begin = n_chunks(); + const auto sample_begin = size(); + + const auto irows = std::get<1>(idims()); + const auto icols = std::get<2>(idims()); + const auto buffer_size = irows * icols * 3; + + std::vector<char> buffer(static_cast<size_t>(buffer_size)); + char label[2]; + + // generate samples + std::vector<tensor_size_t> ilabels; + while ( stream.read(label, 2) == 2 && // coarse & fine labels! + stream.read(buffer.data(), buffer_size) == buffer_size && + n_chunks() < chunk_begin + count) + { + const tensor_size_t ilabel = label[1]; + if (ilabel < 0 || ilabel >= nano::size(odims())) + { + log_error() << "CIFAR-100: invalid label!"; + return false; + } + + image_t image; + image.load_rgb(buffer.data(), irows, icols, irows * icols); + add_chunk(image, image.hash()); + + ilabels.push_back(ilabel); + } + if (ilabels.size() != count) + { + log_error() << "CIFAR-100: invalid number of samples!"; + return false; + } + + // generate folds + add_samples(p, ilabels, tlabels); + + // OK + log_info() << "CIFAR-100: loaded " << (n_chunks() - chunk_begin) << " samples."; + return n_chunks() == chunk_begin + count && + size() == sample_begin + count * m_folds; +} diff --git a/pool/shard007/C++/0092110_password_field_prediction_unittest.cc b/pool/shard007/C++/0092110_password_field_prediction_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..651ba7cbdf63ab8b7bfc137dcb2ceb6415f0c222 --- /dev/null +++ b/pool/shard007/C++/0092110_password_field_prediction_unittest.cc @@ -0,0 +1,241 @@ +// Copyright 2018 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 "components/password_manager/core/browser/form_parsing/password_field_prediction.h" + +#include <vector> + +#include "base/cxx17_backports.h" +#include "base/strings/utf_string_conversions.h" +#include "base/test/scoped_feature_list.h" +#include "components/autofill/core/browser/form_structure.h" +#include "components/autofill/core/common/form_data.h" +#include "components/autofill/core/common/unique_ids.h" +#include "components/password_manager/core/common/password_manager_features.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using autofill::ACCOUNT_CREATION_PASSWORD; +using autofill::AutofillField; +using autofill::CONFIRMATION_PASSWORD; +using autofill::CREDIT_CARD_VERIFICATION_CODE; +using autofill::EMAIL_ADDRESS; +using autofill::FormData; +using autofill::FormFieldData; +using autofill::FormStructure; +using autofill::NEW_PASSWORD; +using autofill::NO_SERVER_DATA; +using autofill::PASSWORD; +using autofill::ServerFieldType; +using autofill::SINGLE_USERNAME; +using autofill::UNKNOWN_TYPE; +using autofill::USERNAME; +using autofill::USERNAME_AND_EMAIL_ADDRESS; +using base::ASCIIToUTF16; + +using FieldPrediction = autofill::AutofillQueryResponse::FormSuggestion:: + FieldSuggestion::FieldPrediction; + +namespace password_manager { + +namespace { + +// The boolean parameter determines the feature state of +// `kSecondaryServerFieldPredictions`. +class FormPredictionsTest : public ::testing::TestWithParam<bool> { + public: + FormPredictionsTest() { + feature_list_.InitWithFeatureState( + features::kSecondaryServerFieldPredictions, + AreSecondaryPredictionsEnabled()); + } + + bool AreSecondaryPredictionsEnabled() const { return GetParam(); } + + private: + base::test::ScopedFeatureList feature_list_; +}; + +TEST_P(FormPredictionsTest, ConvertToFormPredictions) { + struct TestField { + std::string name; + std::string form_control_type; + ServerFieldType input_type; + ServerFieldType expected_type; + bool may_use_prefilled_placeholder; + std::vector<ServerFieldType> additional_types; + } test_fields[] = { + {"full_name", "text", UNKNOWN_TYPE, UNKNOWN_TYPE, false}, + // Password Manager is interested only in credential related types. + {"Email", "email", EMAIL_ADDRESS, EMAIL_ADDRESS, false}, + {"username", "text", USERNAME, USERNAME, true}, + {"Password", "password", PASSWORD, PASSWORD, false}, + {"confirm_password", "password", CONFIRMATION_PASSWORD, + CONFIRMATION_PASSWORD, true}, + // username in |additional_types| takes precedence if the feature is + // enabled. + {"email", + "text", + EMAIL_ADDRESS, + AreSecondaryPredictionsEnabled() ? USERNAME : EMAIL_ADDRESS, + false, + {USERNAME}}, + // cvc in |additional_types| takes precedence if the feature is enabled. + {"cvc", + "password", + PASSWORD, + AreSecondaryPredictionsEnabled() ? CREDIT_CARD_VERIFICATION_CODE + : PASSWORD, + false, + {CREDIT_CARD_VERIFICATION_CODE}}, + // non-password, non-cvc types in |additional_types| are ignored. + {"email", "text", UNKNOWN_TYPE, UNKNOWN_TYPE, false, {EMAIL_ADDRESS}}, + }; + + FormData form_data; + for (size_t i = 0; i < base::size(test_fields); ++i) { + FormFieldData field; + field.unique_renderer_id = autofill::FieldRendererId(i + 1000); + field.name = ASCIIToUTF16(test_fields[i].name); + field.form_control_type = test_fields[i].form_control_type; + form_data.fields.push_back(field); + } + + FormStructure form_structure(form_data); + // Set server predictions and create expected votes. + for (size_t i = 0; i < base::size(test_fields); ++i) { + AutofillField* field = form_structure.field(i); + + std::vector<FieldPrediction> predictions; + FieldPrediction prediction; + prediction.set_type(test_fields[i].input_type); + predictions.push_back(prediction); + + for (ServerFieldType type : test_fields[i].additional_types) { + FieldPrediction additional_prediction; + additional_prediction.set_type(type); + predictions.push_back(additional_prediction); + } + field->set_server_predictions(predictions); + field->set_may_use_prefilled_placeholder( + test_fields[i].may_use_prefilled_placeholder); + } + + constexpr int driver_id = 1000; + FormPredictions actual_predictions = + ConvertToFormPredictions(driver_id, form_structure); + + // Check whether actual predictions are equal to expected ones. + EXPECT_EQ(driver_id, actual_predictions.driver_id); + EXPECT_EQ(form_structure.form_signature(), actual_predictions.form_signature); + EXPECT_EQ(base::size(test_fields), actual_predictions.fields.size()); + + for (size_t i = 0; i < base::size(test_fields); ++i) { + const PasswordFieldPrediction& actual_prediction = + actual_predictions.fields[i]; + EXPECT_EQ(test_fields[i].expected_type, actual_prediction.type); + EXPECT_EQ(test_fields[i].may_use_prefilled_placeholder, + actual_prediction.may_use_prefilled_placeholder); + EXPECT_EQ(form_structure.field(i)->GetFieldSignature(), + actual_prediction.signature); + } +} + +TEST(FormPredictionsTest, ConvertToFormPredictions_SynthesiseConfirmation) { + struct TestField { + std::string name; + std::string form_control_type; + ServerFieldType input_type; + ServerFieldType expected_type; + }; + const std::vector<TestField> kTestForms[] = { + { + {"username", "text", USERNAME, USERNAME}, + {"new password", "password", ACCOUNT_CREATION_PASSWORD, + ACCOUNT_CREATION_PASSWORD}, + // Same name and type means same signature. As a second new-password + // field with this signature, the next field should be re-classified + // to confirmation password. + {"new password", "password", ACCOUNT_CREATION_PASSWORD, + CONFIRMATION_PASSWORD}, + }, + { + {"username", "text", USERNAME, USERNAME}, + {"new password duplicate", "password", ACCOUNT_CREATION_PASSWORD, + ACCOUNT_CREATION_PASSWORD}, + // An explicit confirmation password above should override the + // 2-new-passwords heuristic. + {"new password duplicate", "password", ACCOUNT_CREATION_PASSWORD, + ACCOUNT_CREATION_PASSWORD}, + {"confirm_password", "password", CONFIRMATION_PASSWORD, + CONFIRMATION_PASSWORD}, + }, + }; + + for (const std::vector<TestField>& test_form : kTestForms) { + FormData form_data; + for (size_t i = 0; i < test_form.size(); ++i) { + FormFieldData field; + field.unique_renderer_id = autofill::FieldRendererId(i + 1000); + field.name = ASCIIToUTF16(test_form[i].name); + field.form_control_type = test_form[i].form_control_type; + form_data.fields.push_back(field); + } + + FormStructure form_structure(form_data); + // Set server predictions and create expected votes. + for (size_t i = 0; i < test_form.size(); ++i) { + AutofillField* field = form_structure.field(i); + FieldPrediction prediction; + prediction.set_type(test_form[i].input_type); + field->set_server_predictions({prediction}); + } + + FormPredictions actual_predictions = + ConvertToFormPredictions(0 /*driver_id*/, form_structure); + + for (size_t i = 0; i < form_data.fields.size(); ++i) { + SCOPED_TRACE(testing::Message() + << "field description: name=" << test_form[i].name + << ", form control type=" << test_form[i].form_control_type + << ", input type=" << test_form[i].input_type + << ", expected type=" << test_form[i].expected_type + << ", synthesised FormFieldData=" << form_data.fields[i]); + EXPECT_EQ(test_form[i].expected_type, actual_predictions.fields[i].type); + } + } +} + +TEST(FormPredictionsTest, DeriveFromServerFieldType) { + struct TestCase { + const char* name; + // Input. + ServerFieldType server_type; + CredentialFieldType expected_result; + } test_cases[] = { + {"No prediction", NO_SERVER_DATA, CredentialFieldType::kNone}, + {"Irrelevant type", EMAIL_ADDRESS, CredentialFieldType::kNone}, + {"Username", USERNAME, CredentialFieldType::kUsername}, + {"Username/Email", USERNAME_AND_EMAIL_ADDRESS, + CredentialFieldType::kUsername}, + {"Single Username", SINGLE_USERNAME, + CredentialFieldType::kSingleUsername}, + {"Password", PASSWORD, CredentialFieldType::kCurrentPassword}, + {"New password", NEW_PASSWORD, CredentialFieldType::kNewPassword}, + {"Account creation password", ACCOUNT_CREATION_PASSWORD, + CredentialFieldType::kNewPassword}, + {"Confirmation password", CONFIRMATION_PASSWORD, + CredentialFieldType::kConfirmationPassword}, + }; + + for (const TestCase& test_case : test_cases) { + SCOPED_TRACE(test_case.name); + EXPECT_EQ(test_case.expected_result, + DeriveFromServerFieldType(test_case.server_type)); + } +} +INSTANTIATE_TEST_SUITE_P(All, FormPredictionsTest, testing::Bool()); +} // namespace + +} // namespace password_manager diff --git a/pool/shard007/C++/0092117_dup_ps.cpp b/pool/shard007/C++/0092117_dup_ps.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6d21a7496ad159f519b62260d67ba9d3d06ad0b0 --- /dev/null +++ b/pool/shard007/C++/0092117_dup_ps.cpp @@ -0,0 +1,162 @@ +// NeL - MMORPG Framework <http://dev.ryzom.com/projects/nel/> +// Copyright (C) 2010 Winch Gate Property Limited +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <http://www.gnu.org/licenses/>. + + +#include "std_afx.h" + +#include "nel/3d/ps_located.h" +#include "nel/3d/particle_system.h" + + +#include "nel/misc/stream.h" +#include "nel/misc/mem_stream.h" + +#include "dup_ps.h" + +#include <memory> + +using namespace NL3D; + +//======================================================================= + + + +/** This can duplicate any serializable type by using a serialization policy (polymorphic, non polymorphic ..) + * The serialization policy must have a method to serial a pointer on the object (see example below) + * NB : of course this is slow (but convenient) way of performing a copy + * TODO maybe this could be used elsewhere ? + */ +template <class TSerializePolicy, typename T> +static T *DupSerializable(const T *in) throw(NLMISC::EStream) +{ + NLMISC::CMemStream ms; + nlassert(!ms.isReading()); + T *nonConstIn = const_cast<T *>(in); + TSerializePolicy::serial(nonConstIn, ms); + std::vector<uint8> datas(ms.length()); + std::copy(ms.buffer(), ms.buffer() + ms.length(), datas.begin()); + ms.resetPtrTable(); + ms.invert(); + ms.fill(&datas[0], (uint32)datas.size()); + nlassert(ms.isReading()); + T *newObj = NULL; + TSerializePolicy::serial(newObj, ms); + return newObj; +} + +/** A policy to duplicate a non-polymorphic type + */ +struct CDupObjPolicy +{ + template <typename T> + static void serial(T *&obj, NLMISC::IStream &dest) throw(NLMISC::EStream) + { + dest.serialPtr(obj); + /*if (dest.isReading()) + { + std::auto_ptr<T> newObj(new T); + newObj->serialPtr(dest); + delete obj; + obj = newObj.release(); + } + else + { + obj->serial(dest); + }*/ + } +}; + +/** A policy to duplicate a polymorphic type + */ +struct CDupPolymorphicObjPolicy +{ + template <typename T> + static void serial(T *&obj, NLMISC::IStream &dest) throw(NLMISC::EStream) + { + dest.serialPolyPtr(obj); + } +}; + + + +//======================================================================= +///////////////////////////////////////// +// temp until there is a clone method // +///////////////////////////////////////// +NL3D::CParticleSystemProcess *DupPSLocated(const CParticleSystemProcess *in) +{ + if (!in) return NULL; + try + { + // if the located doesn't belon to a system, copy it direclty + if (in->getOwner() == NULL) + { + return DupSerializable<CDupPolymorphicObjPolicy>(in); + } + else + { + uint index = in->getOwner()->getIndexOf(*in); + /** Duplicate the system, and detach. + * We can't duplicate the object direclty (it may be referencing other objects in the system, so these objects will be copied too...) + */ + std::auto_ptr<CParticleSystem> newPS(DupSerializable<CDupObjPolicy>(in->getOwner())); + // scene pointer is not serialised, but 'detach' may need the scene to be specified + newPS->setScene(in->getOwner()->getScene()); + return newPS->detach(index); + } + } + catch (NLMISC::EStream &e) + { + nlwarning (e.what()); + return NULL; + } +} + +//======================================================================= +///////////////////////////////////////// +// temp until there is a clone method // +///////////////////////////////////////// +NL3D::CPSLocatedBindable *DupPSLocatedBindable(CPSLocatedBindable *in) +{ + if (!in) return NULL; + try + { + // if no owner, can copy the object directy + if (in->getOwner() == NULL) + { + return DupSerializable<CDupPolymorphicObjPolicy>(in); + } + else + { + CParticleSystem *srcPS = in->getOwner()->getOwner(); + std::auto_ptr<CParticleSystem> newPS(DupSerializable<CDupObjPolicy>(srcPS)); + // scene pointer is not serialised, but 'detach' may need the scene to be specified + newPS->setScene(in->getOwner()->getOwner()->getScene()); + // + uint index = srcPS->getIndexOf(*(in->getOwner())); + uint subIndex = in->getOwner()->getIndexOf(in); + // + newPS->setScene(in->getOwner()->getScene()); // 'unbind' require the scene to be attached + CPSLocated *loc = NLMISC::safe_cast<CPSLocated *>(newPS->getProcess(index)); + return loc->unbind(subIndex); + } + } + catch (NLMISC::EStream &e) + { + nlwarning (e.what()); + return NULL; + } +} diff --git a/pool/shard007/C++/0092118_cast_receiver_session_delegate.cc b/pool/shard007/C++/0092118_cast_receiver_session_delegate.cc new file mode 100644 index 0000000000000000000000000000000000000000..9936b36be2ca299d5d2d70240f6b5c32816b4b03 --- /dev/null +++ b/pool/shard007/C++/0092118_cast_receiver_session_delegate.cc @@ -0,0 +1,103 @@ +// 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. + +#include "chrome/renderer/media/cast_receiver_session_delegate.h" + +#include "base/synchronization/waitable_event.h" +#include "base/values.h" + +CastReceiverSessionDelegate::CastReceiverSessionDelegate() + : weak_factory_(this) { +} +CastReceiverSessionDelegate::~CastReceiverSessionDelegate() {} + +void CastReceiverSessionDelegate::LogRawEvents( + const std::vector<media::cast::PacketEvent>& packet_events, + const std::vector<media::cast::FrameEvent>& frame_events) { + NOTREACHED(); +} + +void CastReceiverSessionDelegate::Start( + const media::cast::FrameReceiverConfig& audio_config, + const media::cast::FrameReceiverConfig& video_config, + const net::IPEndPoint& local_endpoint, + const net::IPEndPoint& remote_endpoint, + scoped_ptr<base::DictionaryValue> options, + const media::VideoCaptureFormat& format, + const ErrorCallback& error_callback) { + format_ = format; + DCHECK(io_task_runner_->BelongsToCurrentThread()); + CastSessionDelegateBase::StartUDP(local_endpoint, + remote_endpoint, + options.Pass(), + error_callback); + cast_receiver_ = media::cast::CastReceiver::Create(cast_environment_, + audio_config, + video_config, + cast_transport_.get()); + on_audio_decoded_cb_ = base::Bind( + &CastReceiverSessionDelegate::OnDecodedAudioFrame, + weak_factory_.GetWeakPtr()); + on_video_decoded_cb_ = base::Bind( + &CastReceiverSessionDelegate::OnDecodedVideoFrame, + weak_factory_.GetWeakPtr()); +} + +void CastReceiverSessionDelegate::ReceivePacket( + scoped_ptr<media::cast::Packet> packet) { + cast_receiver_->ReceivePacket(packet.Pass()); +} + +void CastReceiverSessionDelegate::StartAudio( + scoped_refptr<CastReceiverAudioValve> audio_valve) { + DCHECK(io_task_runner_->BelongsToCurrentThread()); + audio_valve_ = audio_valve; + cast_receiver_->RequestDecodedAudioFrame(on_audio_decoded_cb_); +} + +void CastReceiverSessionDelegate::OnDecodedAudioFrame( + scoped_ptr<media::AudioBus> audio_bus, + const base::TimeTicks& playout_time, + bool is_continous) { + DCHECK(io_task_runner_->BelongsToCurrentThread()); + if (!audio_valve_) + return; + + // We're on the IO thread, which doesn't allow blocking + // operations. Since we don't know what the Capture callback + // will do exactly, we need to jump to a different thread. + // Let's re-use the audio decoder thread. + base::TimeTicks now = cast_environment_->Clock()->NowTicks(); + cast_environment_->PostTask( + media::cast::CastEnvironment::AUDIO, + FROM_HERE, + base::Bind(&CastReceiverAudioValve::Capture, + audio_valve_, + base::Owned(audio_bus.release()), + (playout_time - now).InMilliseconds(), + 1.0, + false)); + cast_receiver_->RequestDecodedAudioFrame(on_audio_decoded_cb_); +} + +void CastReceiverSessionDelegate::StartVideo( + content::VideoCaptureDeliverFrameCB video_callback) { + DCHECK(io_task_runner_->BelongsToCurrentThread()); + frame_callback_ = video_callback; + cast_receiver_->RequestDecodedVideoFrame(on_video_decoded_cb_); +} + +void CastReceiverSessionDelegate::StopVideo() { + frame_callback_ = content::VideoCaptureDeliverFrameCB(); +} + +void CastReceiverSessionDelegate::OnDecodedVideoFrame( + const scoped_refptr<media::VideoFrame>& video_frame, + const base::TimeTicks& playout_time, + bool is_continous) { + if (frame_callback_.is_null()) + return; + frame_callback_.Run(video_frame, playout_time); + cast_receiver_->RequestDecodedVideoFrame(on_video_decoded_cb_); +} diff --git a/pool/shard007/C++/0092129_YieldDump.cc b/pool/shard007/C++/0092129_YieldDump.cc new file mode 100644 index 0000000000000000000000000000000000000000..54f712e6f853cd89bb6b9f2a6ad18f3ffcddfec7 --- /dev/null +++ b/pool/shard007/C++/0092129_YieldDump.cc @@ -0,0 +1,119 @@ +#include <set> +#include <utility> + +#include "TString.h" + +#include "YieldDump.h" + +ClassImp(YieldDump) + +//-------------------------------------------------------------------- +void +YieldDump::SimpleExecute(sqlite3* conn, const char* query) +{ + int rc; + sqlite3_stmt *stmt; + + Message(eInfo, "About to execute:\n%s", query); + sqlite3_prepare_v2(conn, query, -1, &stmt, NULL); + rc = sqlite3_step(stmt); + Message(eInfo, "Return code: %i", rc); + + if (rc != SQLITE_OK and rc != SQLITE_DONE) + Message(eError, "Error from connection:\n%s", sqlite3_errmsg(conn)); + + rc = sqlite3_finalize(stmt); + Message(eInfo, "Return code: %i", rc); + +} + +//-------------------------------------------------------------------- +void +YieldDump::DumpYieldFiles(const char* out_file, Int_t NumXBins, Double_t *XBins) +{ + std::vector<std::pair<FileType, std::string>> types_files = { + std::make_pair(kBackground, "background"), + std::make_pair(kSignal, "signal"), + std::make_pair(kData, "data") + }; + + std::string delim = ","; + + sqlite3 *conn; + if(sqlite3_open(out_file, &conn) != SQLITE_OK) { + Message(eError, "Can't open database in %s", out_file); + sqlite3_close(conn); + exit(50); + } + + // Create table with all the uncertainties + + SimpleExecute(conn, R"SQL( +CREATE TABLE IF NOT EXISTS yields ( +region VARCHAR(64), +process VARCHAR(64), +bin INT, +contents DOUBLE, +stat_unc DOUBLE, +type VARCHAR(32), +PRIMARY KEY (region, process, bin) +) +)SQL"); + + int rc; + + for (auto iTypeFile = types_files.begin(); iTypeFile != types_files.end(); ++iTypeFile) { + + // Get the histogram + auto processes = ReturnTreeNames(iTypeFile->first); + + for (unsigned int iCut = 0; iCut != fRegionCuts.size(); ++iCut) { + + SetDefaultCut(fRegionCuts[iCut]); + SetDataWeight(fDataWeights[iCut]); + SetMCWeight(fMCWeights[iCut]); + + for (auto iProcess = processes.begin(); iProcess != processes.end(); ++iProcess) { + + Message(eInfo, "Getting histograms from %s for %s region.", + iProcess->Data(), fRegionCuts[iCut].GetName()); + + auto proc_hist = GetHist(NumXBins, XBins, iTypeFile->first, *iProcess, kLimitName); + + // Get the contents of each histogram to dump into file + for (int iBin = 1; iBin < NumXBins + 1; iBin++) { + + // Dump into sqlite3 database + sqlite3_stmt *yield_stmt; + sqlite3_prepare_v2(conn, "INSERT INTO yields VALUES(?, ?, ?, ?, ?, ?)", -1, &yield_stmt, NULL); + sqlite3_bind_text(yield_stmt, 1, fRegionCuts[iCut].GetName(), -1, NULL); + sqlite3_bind_text(yield_stmt, 2, iProcess->Data(), -1, NULL); + sqlite3_bind_int(yield_stmt, 3, iBin); + sqlite3_bind_double(yield_stmt, 4, proc_hist->GetBinContent(iBin)); + sqlite3_bind_double(yield_stmt, 5, proc_hist->GetBinError(iBin)); + sqlite3_bind_text(yield_stmt, 6, iTypeFile->second.data(), -1, NULL); + + rc = sqlite3_step(yield_stmt); + if (rc != SQLITE_OK and rc != SQLITE_DONE) + Message(eError, "Error from connection:\n%s", sqlite3_errmsg(conn)); + + sqlite3_finalize(yield_stmt); + + } + + delete proc_hist; + } + } + } + + sqlite3_close(conn); +} + +//-------------------------------------------------------------------- +void +YieldDump::DumpYieldFiles(const char* out_file, Int_t NumXBins, Double_t MinX, Double_t MaxX) +{ + Double_t XBins[NumXBins+1]; + ConvertToArray(NumXBins, MinX, MaxX, XBins); + DumpYieldFiles(out_file, NumXBins, XBins); +} diff --git a/pool/shard007/C++/0092131_string64unit.cpp b/pool/shard007/C++/0092131_string64unit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7a70b939cd34f1813697017843a722f7aeaae6d7 --- /dev/null +++ b/pool/shard007/C++/0092131_string64unit.cpp @@ -0,0 +1,101 @@ +#include "string64unit.h" +#include <algorithm> +#include <random> +#include <string64.h> +#include <string> + +struct spaces_t { + char const *spaced; + char const *not_spaced; +}; + +static std::vector<spaces_t> spacetest = { + { " AABBCCDDEEFF11223344556677 ", "AABBCCDDEEFF11223344556677" }, + { "AA\tBBCCDDEEFF1122334455\t6677", "AABBCCDDEEFF11223344556677" }, + { " AA BB CC DD EE FF 11 22 33 44 55 66 77 ", "AABBCCDDEEFF11223344556677" }, + { "\t\t\tAABBCCDDEEFF112\r23344556677\t\t", "AABBCCDDEEFF11223344556677" }, + { "AABBCCDDEEFF11223344556677\r\n", "AABBCCDDEEFF11223344556677" }, + { "AABBCCDDEEFF11223344556677\n", "AABBCCDDEEFF11223344556677" }, + { "AABBCCDDEEFF11223344556677\n\r", "AABBCCDDEEFF11223344556677" }, +}; + +void string64_unit::squash() { + for (auto & i : spacetest) { + std::string xstr(i.spaced); + ict::squash(xstr); + IT_ASSERT(xstr == i.not_spaced); + } +} + +void string64_unit::string64() { + { + ict::string64 a; + IT_ASSERT(a.empty()); + ict::string64 b = "24"; + IT_ASSERT(!b.empty()); + + ict::string64 c(b); + IT_ASSERT(!c.empty()); + IT_ASSERT(c == b); + IT_ASSERT(b == c); + + ict::string64 d("hello"); + IT_ASSERT(d == "hello"); + IT_ASSERT(d[0] == 'h'); + IT_ASSERT(d[1] == 'e'); + IT_ASSERT(d[2] == 'l'); + IT_ASSERT(d[3] == 'l'); + IT_ASSERT(d[4] == 'o'); + IT_ASSERT(d[5] == '\0'); + IT_ASSERT(d[6] == '\0'); + IT_ASSERT(d[7] == '\0'); + + IT_ASSERT(d != "goodbye"); + + IT_ASSERT(d.value == 478560413032); + uint64_t value = d.value; + IT_ASSERT(value == 478560413032); + c = d; + IT_ASSERT(c == d); + IT_ASSERT(c != a); + } + { + ict::string64 a = ""; + IT_ASSERT(a.empty()); + + try { + a = "way to long"; + } catch (std::exception &e) { + IT_ASSERT(std::string(e.what()).find( + "way to long is to long for a string64") == + std::string::npos); + } + } + + { + ict::string64 a = "field"; + ict::string64 b = a; + + IT_ASSERT(a == b); + } +} + +void string64_unit::string64_compare() { + std::vector<ict::string64> v = { "a", "b", "c", "foo", "goo", "alpha", "beta", "wow", "wowo", "good", "bad" }; + auto sorted = v; + std::sort(sorted.begin(), sorted.end()); + + std::random_device rd; + std::mt19937 g(rd()); + std::shuffle(v.begin(), v.end(), g); + + auto sorted2 = v; + std::sort(sorted2.begin(), sorted2.end()); + IT_ASSERT(sorted == sorted2); +} + +int main() { + string64_unit test; + ict::unit_test<string64_unit> ut(&test); + return ut.run(); +} diff --git a/pool/shard007/C++/0092136_INETUtils.cc b/pool/shard007/C++/0092136_INETUtils.cc new file mode 100644 index 0000000000000000000000000000000000000000..929986446fd71cfe0bf23144b2883b68ce9ae5a6 --- /dev/null +++ b/pool/shard007/C++/0092136_INETUtils.cc @@ -0,0 +1,118 @@ +// +// Copyright (C) 2005 Andras Varga +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program; if not, see <http://www.gnu.org/licenses/>. +// + +#include "inet/common/INETUtils.h" + +namespace inet { + +namespace utils { + +std::string ltostr(long i) +{ + std::ostringstream os; + os << i; + return os.str(); +} + +std::string dtostr(double d) +{ + std::ostringstream os; + os << d; + return os.str(); +} + +double atod(const char *s) +{ + char *e; + double d = ::strtod(s, &e); + if (*e) + throw cRuntimeError("Invalid cast: '%s' cannot be interpreted as a double", s); + return d; +} + +unsigned long atoul(const char *s) +{ + char *e; + unsigned long d = ::strtoul(s, &e, 10); + if (*e) + throw cRuntimeError("Invalid cast: '%s' cannot be interpreted as an unsigned long", s); + return d; +} + +std::string stripnonalnum(const char *s) +{ + std::string result; + for ( ; *s; s++) + if (isalnum(*s)) + result += *s; + + return result; +} + +#define BUFLEN 1024 + +std::string stringf(const char *fmt, ...) +{ + char buf[BUFLEN]; + va_list va; + va_start(va, fmt); + vsnprintf(buf, BUFLEN, fmt, va); + buf[BUFLEN - 1] = '\0'; + va_end(va); + return buf; +} + +std::string vstringf(const char *fmt, va_list& args) +{ + char buf[BUFLEN]; + vsnprintf(buf, BUFLEN, fmt, args); + buf[BUFLEN - 1] = '\0'; + return buf; +} + +#undef BUFLEN + +cObject *createOneIfClassIsKnown(const char *className, const char *defaultNamespace) +{ + std::string ns = defaultNamespace; + do { + std::string::size_type found = ns.rfind("::"); + if (found == std::string::npos) + found = 0; + ns.erase(found); + std::string cn = found ? ns + "::" + className : className; + cObject *ret = cObjectFactory::createOneIfClassIsKnown(cn.c_str()); + if (ret) + return ret; + } while (!ns.empty()); + return nullptr; +} + +cObject *createOne(const char *className, const char *defaultNamespace) +{ + cObject *ret = createOneIfClassIsKnown(className, defaultNamespace); + if (!ret) + throw cRuntimeError("Class \"%s\" not found -- perhaps its code was not linked in, " + "or the class wasn't registered with Register_Class(), or in the case of " + "modules and channels, with Define_Module()/Define_Channel()", className); + return ret; +} + +} // namespace utils + +} // namespace inet + diff --git a/pool/shard007/C++/0092156_apps_grid_context_menu.cc b/pool/shard007/C++/0092156_apps_grid_context_menu.cc new file mode 100644 index 0000000000000000000000000000000000000000..efce0222d65be84de0ca96bd68cc2cb08ba03b4b --- /dev/null +++ b/pool/shard007/C++/0092156_apps_grid_context_menu.cc @@ -0,0 +1,102 @@ +// Copyright (c) 2021 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 "ash/app_list/views/apps_grid_context_menu.h" + +#include "ash/app_list/app_list_model_provider.h" +#include "ash/app_list/model/app_list_model.h" +#include "ash/constants/ash_features.h" +#include "ash/public/cpp/app_list/app_list_model_delegate.h" +#include "ash/resources/vector_icons/vector_icons.h" +#include "ash/strings/grit/ash_strings.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/base/models/simple_menu_model.h" +#include "ui/views/controls/menu/menu_model_adapter.h" +#include "ui/views/controls/menu/menu_runner.h" + +namespace ash { + +AppsGridContextMenu::AppsGridContextMenu() = default; + +AppsGridContextMenu::~AppsGridContextMenu() = default; + +bool AppsGridContextMenu::IsMenuShowing() const { + return menu_runner_ && menu_runner_->IsRunning(); +} + +void AppsGridContextMenu::Cancel() { + if (IsMenuShowing()) + menu_runner_->Cancel(); +} + +void AppsGridContextMenu::ExecuteCommand(int command_id, int event_flags) { + switch (command_id) { + case AppsGridCommandId::kReorderByNameAlphabetical: + AppListModelProvider::Get()->model()->delegate()->RequestAppListSort( + AppListSortOrder::kNameAlphabetical); + break; + case AppsGridCommandId::kReorderByColor: + AppListModelProvider::Get()->model()->delegate()->RequestAppListSort( + AppListSortOrder::kColor); + break; + default: + NOTREACHED(); + } +} + +void AppsGridContextMenu::ShowContextMenuForViewImpl( + views::View* source, + const gfx::Point& point, + ui::MenuSourceType source_type) { + if (!features::IsLauncherAppSortEnabled()) + return; + + // Build the menu model and save it to `context_menu_model_`. + BuildMenuModel(); + menu_model_adapter_ = std::make_unique<views::MenuModelAdapter>( + context_menu_model_.get(), + base::BindRepeating(&AppsGridContextMenu::OnMenuClosed, + base::Unretained(this))); + root_menu_item_view_ = menu_model_adapter_->CreateMenu(); + + int run_types = views::MenuRunner::USE_ASH_SYS_UI_LAYOUT | + views::MenuRunner::CONTEXT_MENU | + views::MenuRunner::FIXED_ANCHOR; + if (source_type == ui::MENU_SOURCE_TOUCH && owner_touch_dragging_) + run_types |= views::MenuRunner::SEND_GESTURE_EVENTS_TO_OWNER; + + menu_runner_ = + std::make_unique<views::MenuRunner>(root_menu_item_view_, run_types); + menu_runner_->RunMenuAt( + source->GetWidget(), nullptr, gfx::Rect(point, gfx::Size()), + views::MenuAnchorPosition::kBubbleBottomRight, source_type); +} + +void AppsGridContextMenu::BuildMenuModel() { + context_menu_model_ = std::make_unique<ui::SimpleMenuModel>(this); + + context_menu_model_->AddTitle(l10n_util::GetStringUTF16( + IDS_ASH_LAUNCHER_APPS_GRID_CONTEXT_MENU_REORDER_TITLE)); + context_menu_model_->AddItemWithIcon( + AppsGridCommandId::kReorderByNameAlphabetical, + l10n_util::GetStringUTF16( + IDS_ASH_LAUNCHER_APPS_GRID_CONTEXT_MENU_REORDER_BY_NAME), + ui::ImageModel::FromVectorIcon(kSortAlphabeticalIcon, + ui::kColorAshSystemUIMenuIcon)); + context_menu_model_->AddItemWithIcon( + AppsGridCommandId::kReorderByColor, + l10n_util::GetStringUTF16( + IDS_ASH_LAUNCHER_APPS_GRID_CONTEXT_MENU_REORDER_BY_COLOR), + ui::ImageModel::FromVectorIcon(kSortColorIcon, + ui::kColorAshSystemUIMenuIcon)); +} + +void AppsGridContextMenu::OnMenuClosed() { + menu_runner_.reset(); + context_menu_model_.reset(); + root_menu_item_view_ = nullptr; + menu_model_adapter_.reset(); +} + +} // namespace ash diff --git a/pool/shard007/C++/0092169_s3log.cpp b/pool/shard007/C++/0092169_s3log.cpp new file mode 100644 index 0000000000000000000000000000000000000000..500830bf44d60bd97b7be3fc85da20f6cd909534 --- /dev/null +++ b/pool/shard007/C++/0092169_s3log.cpp @@ -0,0 +1,98 @@ +#include <arpa/inet.h> +#include <errno.h> +#include <fcntl.h> +#include <netinet/in.h> +#include <sys/socket.h> +#include <sys/stat.h> +#include <sys/types.h> +#include <sys/un.h> +#include <unistd.h> +#include <cstdarg> +#include <cstdio> +#include <cstring> +#include <memory> +#include <string> + +#include "s3conf.h" +#include "s3log.h" +#include "s3macros.h" +#include "s3utils.h" + +#define MAX_MESSAGE_LINE_LENGTH 1024 + +#ifndef S3_STANDALONE +extern "C" { +void write_log(const char* fmt, ...) __attribute__((format(printf, 1, 2))); +} +#endif + +void _LogMessage(const char* fmt, va_list args) { + char buf[MAX_MESSAGE_LINE_LENGTH]; + vsnprintf(buf, sizeof(buf), fmt, args); +#ifdef S3_STANDALONE + fprintf(stderr, "%s", buf); +#else + write_log("%s", buf); +#endif +} + +void _send_to_remote(const char* fmt, va_list args) { + char buf[MAX_MESSAGE_LINE_LENGTH]; + size_t len = vsnprintf(buf, sizeof(buf), fmt, args); + sendto(s3ext_logsock_udp, buf, len, 0, (struct sockaddr*)&s3ext_logserveraddr, + sizeof(struct sockaddr_in)); +} + +void LogMessage(LOGLEVEL loglevel, const char* fmt, ...) { + if (loglevel > s3ext_loglevel) return; + va_list args; + va_start(args, fmt); + switch (s3ext_logtype) { + case INTERNAL_LOG: + _LogMessage(fmt, args); + break; + case STDERR_LOG: + vfprintf(stderr, fmt, args); + break; + case REMOTE_LOG: // `socat UDP-RECV:[port] STDOUT` to listen + _send_to_remote(fmt, args); + break; + default: + break; + } + va_end(args); +} + +static bool loginited = false; + +void InitRemoteLog() { + if (loginited) { + return; + } + + s3ext_logsock_udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + CHECK_OR_DIE_MSG(s3ext_logsock_udp != -1, "Failed to create socket: %s", strerror(errno)); + + memset(&s3ext_logserveraddr, 0, sizeof(struct sockaddr_in)); + s3ext_logserveraddr.sin_family = AF_INET; + s3ext_logserveraddr.sin_port = htons(s3ext_logserverport); + inet_aton(s3ext_logserverhost.c_str(), &s3ext_logserveraddr.sin_addr); + + loginited = true; +} + +LOGTYPE getLogType(const char* v) { + if (!v) return STDERR_LOG; + if (strcmp(v, "REMOTE") == 0) return REMOTE_LOG; + if (strcmp(v, "INTERNAL") == 0) return INTERNAL_LOG; + return STDERR_LOG; +} + +LOGLEVEL getLogLevel(const char* v) { + if (!v) return EXT_FATAL; + if (strcmp(v, "DEBUG") == 0) return EXT_DEBUG; + if (strcmp(v, "WARNING") == 0) return EXT_WARNING; + if (strcmp(v, "INFO") == 0) return EXT_INFO; + if (strcmp(v, "ERROR") == 0) return EXT_ERROR; + return EXT_FATAL; +} diff --git a/pool/shard007/C++/0092184_Random.cpp b/pool/shard007/C++/0092184_Random.cpp new file mode 100644 index 0000000000000000000000000000000000000000..66c1d1b8af8f072c038b10f16376b199d284a5a2 --- /dev/null +++ b/pool/shard007/C++/0092184_Random.cpp @@ -0,0 +1,174 @@ +#include "stdafx.h" + + +#include <stdlib.h> + +#include "Random.h" + +#ifndef NULL +#define NULL 0 +#endif + + + /* static const int mdig = 32; */ +#define MDIG 32 + + /* static const int one = 1; */ +#define ONE 1 + + static const int m1 = (ONE << (MDIG-2)) + ((ONE << (MDIG-2) )-ONE); + static const int m2 = ONE << MDIG/2; + + /* For mdig = 32 : m1 = 2147483647, m2 = 65536 + For mdig = 64 : m1 = 9223372036854775807, m2 = 4294967296 + */ + + /* move to initialize() because */ + /* compiler could not resolve as */ + /* a constant. */ + + static /*const*/ double dm1; /* = 1.0 / (double) m1; */ + + +/* private methods (defined below, but not in Random.h */ + +static void initialize(Random R, int seed); + +Random new_Random_seed(int seed) +{ + Random R = (Random) malloc(sizeof(Random_struct)); + + initialize(R, seed); + R->left = 0.0; + R->right = 1.0; + R->width = 1.0; + R->haveRange = 0 /*false*/; + + return R; +} + +Random new_Random(int seed, double left, double right) +{ + Random R = (Random) malloc(sizeof(Random_struct)); + + initialize(R, seed); + R->left = left; + R->right = right; + R->width = right - left; + R->haveRange = 1; /* true */ + + return R; +} + +void Random_delete(Random R) +{ + free(R); +} + + + +/* Returns the next random number in the sequence. */ + +double Random_nextDouble(Random R) +{ + int k; + + int I = R->i; + int J = R->j; + int *m = R->m; + + k = m[I] - m[J]; + if (k < 0) k += m1; + R->m[J] = k; + + if (I == 0) + I = 16; + else I--; + R->i = I; + + if (J == 0) + J = 16 ; + else J--; + R->j = J; + + if (R->haveRange) + return R->left + dm1 * (double) k * R->width; + else + return dm1 * (double) k; + +} + + + + +/*-------------------------------------------------------------------- + PRIVATE METHODS + ----------------------------------------------------------------- */ + +static void initialize(Random R, int seed) +{ + + int jseed, k0, k1, j0, j1, iloop; + + dm1 = 1.0 / (double) m1; + + R->seed = seed; + + if (seed < 0 ) seed = -seed; /* seed = abs(seed) */ + jseed = (seed < m1 ? seed : m1); /* jseed = min(seed, m1) */ + if (jseed % 2 == 0) --jseed; + k0 = 9069 % m2; + k1 = 9069 / m2; + j0 = jseed % m2; + j1 = jseed / m2; + for (iloop = 0; iloop < 17; ++iloop) + { + jseed = j0 * k0; + j1 = (jseed / m2 + j0 * k1 + j1 * k0) % (m2 / 2); + j0 = jseed % m2; + R->m[iloop] = j0 + m2 * j1; + } + R->i = 4; + R->j = 16; + +} + +double *RandomVector(int N, Random R) +{ + int i; + double *x = (double *) malloc(sizeof(double)*N); + + for (i=0; i<N; i++) + x[i] = Random_nextDouble(R); + + return x; +} + + +double **RandomMatrix(int M, int N, Random R) +{ + int i; + int j; + + /* allocate matrix */ + + double **A = (double **) malloc(sizeof(double*)*M); + + if (A == NULL) return NULL; + + for (i=0; i<M; i++) + { + A[i] = (double *) malloc(sizeof(double)*N); + if (A[i] == NULL) + { + free(A); + return NULL; + } + for (j=0; j<N; j++) + A[i][j] = Random_nextDouble(R); + } + return A; +} + + + diff --git a/pool/shard007/C++/0092188_ZenMain.cpp b/pool/shard007/C++/0092188_ZenMain.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c764a15698b2a08bf5176e1758af5f20470125e0 --- /dev/null +++ b/pool/shard007/C++/0092188_ZenMain.cpp @@ -0,0 +1,87 @@ +#include "stdafx.h" +#include "ZenAPI.h" +#include "ZenChess.h" +#include "Mainfrm.h" +CMainFrame* pFrame; + + + +BOOL CZenChessApp::InitInstance() +{ + pFrame = new CMainFrame; + m_pMainWnd = pFrame; + pFrame->LoadFrame(IDR_ZENCHESS, + WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL, + NULL); + pFrame->ShowWindow(SW_SHOW); + pFrame->UpdateWindow(); + return true; +} + +void ZenMain(CZenChessApp &theApp) +{ + pFrame->Set1(); +} + +void OnZenMessage(CString &msg) +{ + if(msg[0]==':') + { + switch(msg[1]) + { + case 'C': + ///AfxMessageBox(msg.Mid(2)); + + + break; + case 'G': + pFrame->MovePiece(msg[2]-'A',msg[3]-'A',msg[4]-'A',msg[5]-'A'); + pFrame->SetTurn(true); + break; + case 'S': + pFrame->SetTurn(true); + break; + case 'X': + + break; + case 'M': + + break; + + } + + } + else + { + pFrame->SetTurn(false); + int Me; + CString x; + x = msg.Mid(1); + Me = atoi(x); + if(Me==1) + { + pFrame->SetTurn(true); + pFrame->Set1(); + } + else if(Me==2) + { + pFrame->Set2(); + pFrame->SetTurn(false); + x = "S"; + ZSendChannel(x); + } + + } +} + +void OnZenAddUser(CString & user) +{ +} + +void OnZenRemoveUser(CString & user) +{ +} + +void OnZenClearUser() +{ +} diff --git a/pool/shard007/C++/0092195_editaddressdialog.cpp b/pool/shard007/C++/0092195_editaddressdialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b297e5156454acf4bfac9ef3f82800d34dc35822 --- /dev/null +++ b/pool/shard007/C++/0092195_editaddressdialog.cpp @@ -0,0 +1,136 @@ +#include "editaddressdialog.h" +#include "ui_editaddressdialog.h" +#include "addresstablemodel.h" +#include "guiutil.h" + +#include <QDataWidgetMapper> +#include <QMessageBox> + +EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : + QDialog(parent), + ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) +{ + ui->setupUi(this); + + GUIUtil::setupAddressWidget(ui->addressEdit, this); + + switch(mode) + { + case NewReceivingAddress: + setWindowTitle(tr("New receiving address")); + ui->addressEdit->setEnabled(false); + break; + case NewSendingAddress: + setWindowTitle(tr("New sending address")); + break; + case EditReceivingAddress: + setWindowTitle(tr("Edit receiving address")); + ui->addressEdit->setEnabled(false); + break; + case EditSendingAddress: + setWindowTitle(tr("Edit sending address")); + break; + } + + mapper = new QDataWidgetMapper(this); + mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); +} + +EditAddressDialog::~EditAddressDialog() +{ + delete ui; +} + +void EditAddressDialog::setModel(AddressTableModel *model) +{ + this->model = model; + if(!model) + return; + + mapper->setModel(model); + mapper->addMapping(ui->labelEdit, AddressTableModel::Label); + mapper->addMapping(ui->addressEdit, AddressTableModel::Address); +} + +void EditAddressDialog::loadRow(int row) +{ + mapper->setCurrentIndex(row); +} + +bool EditAddressDialog::saveCurrentRow() +{ + if(!model) + return false; + + switch(mode) + { + case NewReceivingAddress: + case NewSendingAddress: + address = model->addRow( + mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, + ui->labelEdit->text(), + ui->addressEdit->text()); + break; + case EditReceivingAddress: + case EditSendingAddress: + if(mapper->submit()) + { + address = ui->addressEdit->text(); + } + break; + } + return !address.isEmpty(); +} + +void EditAddressDialog::accept() +{ + if(!model) + return; + + if(!saveCurrentRow()) + { + switch(model->getEditStatus()) + { + case AddressTableModel::OK: + // Failed with unknown reason. Just reject. + break; + case AddressTableModel::NO_CHANGES: + // No changes were made during edit operation. Just reject. + break; + case AddressTableModel::INVALID_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is not a valid LVGcoin address.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::DUPLICATE_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::WALLET_UNLOCK_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("Could not unlock wallet."), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::KEY_GENERATION_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("New key generation failed."), + QMessageBox::Ok, QMessageBox::Ok); + break; + + } + return; + } + QDialog::accept(); +} + +QString EditAddressDialog::getAddress() const +{ + return address; +} + +void EditAddressDialog::setAddress(const QString &address) +{ + this->address = address; + ui->addressEdit->setText(address); +} diff --git a/pool/shard007/C++/0092197_main.cpp b/pool/shard007/C++/0092197_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a16c8c369021eae480f6c497d60ac842dd546ebc --- /dev/null +++ b/pool/shard007/C++/0092197_main.cpp @@ -0,0 +1,28 @@ +#include <QApplication> +#include <QDir> +#include <QStyle> +#include <QDesktopWidget> +#include <SDL.h> + +#include "mainwindow.h" + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + QDir dir(QCoreApplication::applicationDirPath()); + QDir::setCurrent(dir.absolutePath()); + + if (SDL_Init(SDL_INIT_VIDEO) != 0) { + + return -1; + } + + Launcher::MainWindow window; + window.setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, window.size(), qApp->desktop()->availableGeometry())); + window.setFixedSize(750,350); + window.show(); + + int result = app.exec(); + return result; +} diff --git a/pool/shard007/C++/0092204_CWE401_Memory_Leak__struct_twoIntsStruct_malloc_72a.cpp b/pool/shard007/C++/0092204_CWE401_Memory_Leak__struct_twoIntsStruct_malloc_72a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2304ee665d4a546ff52d3a8aa7dbb9579b1268ae --- /dev/null +++ b/pool/shard007/C++/0092204_CWE401_Memory_Leak__struct_twoIntsStruct_malloc_72a.cpp @@ -0,0 +1,134 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE401_Memory_Leak__struct_twoIntsStruct_malloc_72a.cpp +Label Definition File: CWE401_Memory_Leak.c.label.xml +Template File: sources-sinks-72a.tmpl.cpp +*/ +/* + * @description + * CWE: 401 Memory Leak + * BadSource: malloc Allocate data using malloc() + * GoodSource: Allocate data on the stack + * Sinks: + * GoodSink: call free() on data + * BadSink : no deallocation of data + * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files + * + * */ + +#include "std_testcase.h" +#include <vector> + +#include <wchar.h> + +using namespace std; + +namespace CWE401_Memory_Leak__struct_twoIntsStruct_malloc_72 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink(vector<struct _twoIntsStruct *> dataVector); + +void bad() +{ + struct _twoIntsStruct * data; + vector<struct _twoIntsStruct *> dataVector; + data = NULL; + /* POTENTIAL FLAW: Allocate memory on the heap */ + data = (struct _twoIntsStruct *)malloc(100*sizeof(struct _twoIntsStruct)); + if (data == NULL) {exit(-1);} + /* Initialize and make use of data */ + data[0].intOne = 0; + data[0].intTwo = 0; + printStructLine((twoIntsStruct *)&data[0]); + /* Put data in a vector */ + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + badSink(dataVector); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(vector<struct _twoIntsStruct *> dataVector); + +static void goodG2B() +{ + struct _twoIntsStruct * data; + vector<struct _twoIntsStruct *> dataVector; + data = NULL; + /* FIX: Use memory allocated on the stack with ALLOCA */ + data = (struct _twoIntsStruct *)ALLOCA(100*sizeof(struct _twoIntsStruct)); + /* Initialize and make use of data */ + data[0].intOne = 0; + data[0].intTwo = 0; + printStructLine((twoIntsStruct *)&data[0]); + /* Put data in a vector */ + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + goodG2BSink(dataVector); +} + +/* goodB2G uses the BadSource with the GoodSink */ +void goodB2GSink(vector<struct _twoIntsStruct *> dataVector); + +static void goodB2G() +{ + struct _twoIntsStruct * data; + vector<struct _twoIntsStruct *> dataVector; + data = NULL; + /* POTENTIAL FLAW: Allocate memory on the heap */ + data = (struct _twoIntsStruct *)malloc(100*sizeof(struct _twoIntsStruct)); + if (data == NULL) {exit(-1);} + /* Initialize and make use of data */ + data[0].intOne = 0; + data[0].intTwo = 0; + printStructLine((twoIntsStruct *)&data[0]); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + goodB2GSink(dataVector); +} + +void good() +{ + goodG2B(); + goodB2G(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +using namespace CWE401_Memory_Leak__struct_twoIntsStruct_malloc_72; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard007/C++/0092206_scan_results.cpp b/pool/shard007/C++/0092206_scan_results.cpp new file mode 100644 index 0000000000000000000000000000000000000000..242aac3b56938f18dbe4a393d95afd4876a3bfdc --- /dev/null +++ b/pool/shard007/C++/0092206_scan_results.cpp @@ -0,0 +1,110 @@ +// Copyright 2011 The Kyua Authors. +// 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. + +#include "drivers/scan_results.hpp" + +#include "engine/filters.hpp" +#include "model/context.hpp" +#include "model/test_case.hpp" +#include "model/test_program.hpp" +#include "store/read_backend.hpp" +#include "store/read_transaction.hpp" +#include "utils/defs.hpp" + +namespace fs = utils::fs; + + +/// Pure abstract destructor. +drivers::scan_results::base_hooks::~base_hooks(void) +{ +} + + +/// Callback executed before any operation is performed. +void +drivers::scan_results::base_hooks::begin(void) +{ +} + + +/// Callback executed after all operations are performed. +/// +/// \param unused_r A structure with all results computed by this driver. Note +/// that this is also returned by the drive operation. +void +drivers::scan_results::base_hooks::end(const result& UTILS_UNUSED_PARAM(r)) +{ +} + + +/// Executes the operation. +/// +/// \param store_path The path to the database store. +/// \param raw_filters The test case filters as provided by the user. +/// \param hooks The hooks for this execution. +/// +/// \returns A structure with all results computed by this driver. +drivers::scan_results::result +drivers::scan_results::drive(const fs::path& store_path, + const std::set< engine::test_filter >& raw_filters, + base_hooks& hooks) +{ + engine::filters_state filters(raw_filters); + + store::read_backend db = store::read_backend::open_ro(store_path); + store::read_transaction tx = db.start_read(); + + hooks.begin(); + + const model::context context = tx.get_context(); + hooks.got_context(context); + + store::results_iterator iter = tx.get_results(); + while (iter) { + // TODO(jmmv): We should be filtering at the test case level for + // efficiency, but that means we would need to execute more than one + // query on the database and our current interfaces don't support that. + // + // Reuse engine::filters_state for the time being because it is simpler + // and we get tracking of unmatched filters "for free". + const model::test_program_ptr test_program = iter.test_program(); + if (filters.match_test_program(test_program->relative_path())) { + const model::test_case& test_case = test_program->find( + iter.test_case_name()); + if (filters.match_test_case(test_program->relative_path(), + test_case.name())) { + hooks.got_result(iter); + } + } + ++iter; + } + + result r(filters.unused()); + hooks.end(r); + return r; +} diff --git a/pool/shard007/C++/0092209_drilldownlistitem.cpp b/pool/shard007/C++/0092209_drilldownlistitem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..953dd168390f4d0ef1595dfd5abb3bbeb5080aa8 --- /dev/null +++ b/pool/shard007/C++/0092209_drilldownlistitem.cpp @@ -0,0 +1,71 @@ +/*************************************************************************** +** +** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (directui@nokia.com) +** +** This file is part of libmeegotouch. +** +** If you have questions regarding the use of this file, please contact +** Nokia at directui@nokia.com. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation +** and appearing in the file LICENSE.LGPL included in the packaging +** of this file. +** +****************************************************************************/ + +#include "drilldownlistitem.h" + +#include <QGraphicsGridLayout> + +#include <MApplication> +#include <MImageWidget> +#include <MLabel> + +DrillDownListItem::DrillDownListItem(QGraphicsItem *parent) + : MBasicListItem(MBasicListItem::SingleTitle, parent) +{ + +} + +DrillDownListItem::~DrillDownListItem() +{ + +} + +QGraphicsLayout *DrillDownListItem::createLayout() +{ + QGraphicsGridLayout *layout = new QGraphicsGridLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->setSpacing(0); + + layout->addItem(titleLabelWidget(), 0, 0, Qt::AlignLeft | Qt::AlignVCenter); + + imageWidget()->setStyleName("CommonDrillDownIcon"); + layout->addItem(imageWidget(), 0, 1, Qt::AlignCenter); + + if (MApplication::instance()->objectName() == "widgetsgallery") { + setStyleName("CommonBasicListItem"); + titleLabelWidget()->setStyleName("CommonSingleTitle"); + imageWidget()->setImage("icon-m-common-drilldown-arrow"); + } else { + setStyleName("CommonBasicListItemInverted"); + titleLabelWidget()->setStyleName("CommonSingleTitleInverted"); + imageWidget()->setImage("icon-m-common-drilldown-arrow-inverse"); + } + + return layout; +} + +void DrillDownListItem::setImageWidget(MImageWidget *imageWidget) +{ + MBasicListItem::setImageWidget(imageWidget); +} + +MImageWidget *DrillDownListItem::imageWidget() +{ + return MBasicListItem::imageWidget(); +} diff --git a/pool/shard007/C++/0092219_JNIXBMCAudioManagerOnAudioFocusChangeListener.cpp b/pool/shard007/C++/0092219_JNIXBMCAudioManagerOnAudioFocusChangeListener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f1f2d27af403a1ebba2e7cb632b753d73c142184 --- /dev/null +++ b/pool/shard007/C++/0092219_JNIXBMCAudioManagerOnAudioFocusChangeListener.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2016 Christian Browet + * This file is part of Kodi - https://kodi.tv + * + * SPDX-License-Identifier: GPL-2.0-or-later + * See LICENSES/README.md for more information. + */ + +#include "JNIXBMCAudioManagerOnAudioFocusChangeListener.h" +#include <androidjni/jutils-details.hpp> + +#include <androidjni/Context.h> +#include "CompileInfo.h" +#include "XBMCApp.h" + +using namespace jni; + +static std::string s_className = std::string(CCompileInfo::GetClass()) + "/interfaces/XBMCAudioManagerOnAudioFocusChangeListener"; + +CJNIXBMCAudioManagerOnAudioFocusChangeListener::CJNIXBMCAudioManagerOnAudioFocusChangeListener() + : CJNIBase(s_className) +{ + m_object = new_object(CJNIContext::getClassLoader().loadClass(GetDotClassName(s_className))); + m_object.setGlobal(); + + add_instance(m_object, this); +} + +CJNIXBMCAudioManagerOnAudioFocusChangeListener::CJNIXBMCAudioManagerOnAudioFocusChangeListener(const CJNIXBMCAudioManagerOnAudioFocusChangeListener& other) + : CJNIBase(other) +{ + add_instance(m_object, this); +} + +CJNIXBMCAudioManagerOnAudioFocusChangeListener::~CJNIXBMCAudioManagerOnAudioFocusChangeListener() +{ + remove_instance(this); +} + +void CJNIXBMCAudioManagerOnAudioFocusChangeListener::RegisterNatives(JNIEnv* env) +{ + jclass cClass = env->FindClass(s_className.c_str()); + if(cClass) + { + JNINativeMethod methods[] = + { + {"_onAudioFocusChange", "(I)V", (void*)&CJNIXBMCAudioManagerOnAudioFocusChangeListener::_onAudioFocusChange}, + }; + + env->RegisterNatives(cClass, methods, sizeof(methods)/sizeof(methods[0])); + } +} + +void CJNIXBMCAudioManagerOnAudioFocusChangeListener::_onAudioFocusChange(JNIEnv *env, jobject thiz, jint focusChange) +{ + (void)env; + + CJNIXBMCAudioManagerOnAudioFocusChangeListener *inst = find_instance(thiz); + if (inst) + inst->onAudioFocusChange(focusChange); +} + +void CJNIXBMCAudioManagerOnAudioFocusChangeListener::onAudioFocusChange(int focusChange) +{ + if(CXBMCApp::get()) + CXBMCApp::get()->onAudioFocusChange(focusChange); +} diff --git a/pool/shard007/C++/0092225_main.cpp b/pool/shard007/C++/0092225_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bfe2842f15aa2d803ba393cf5a3dff3974b29027 --- /dev/null +++ b/pool/shard007/C++/0092225_main.cpp @@ -0,0 +1,153 @@ +// +// Copyright (c) 2012, University of Erlangen-Nuremberg +// Copyright (c) 2012, Siemens AG +// 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. +// +// 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 "hipacc.hpp" + +#include <iostream> +#include <hipacc_helper.hpp> + + +#define SIZE_X 5 +#define SIZE_Y 5 +#define WIDTH 4032 +#define HEIGHT 3024 +#define IMAGE "../../common/img/fuerte_ship.jpg" + + +using namespace hipacc; +using namespace hipacc::math; + + +class Erode : public Kernel<uchar4> { + private: + Accessor<uchar4> ∈ + Domain &dom; + + public: + Erode(IterationSpace<uchar4> &iter, Accessor<uchar4> &in, Domain &dom) + : Kernel(iter), in(in), dom(dom) { + add_accessor(&in); + } + + void kernel() { + output() = reduce(dom, Reduce::MIN, [&] () -> uchar4 { + return in(dom); + }); + } +}; + + +// forward declaration of reference implementation +void erode_filter(uchar4 *in, uchar4 *out, int size_x, int size_y, + int width, int height); + + +/************************************************************************* + * Main function * + *************************************************************************/ +int main(int argc, const char **argv) { + const int width = WIDTH; + const int height = HEIGHT; + const int size_x = SIZE_X; + const int size_y = SIZE_Y; + const int offset_x = size_x >> 1; + const int offset_y = size_y >> 1; + float timing = 0; + + // host memory for image of width x height pixels + uchar4 *input = (uchar4*)load_data<uchar>(width, height, 4, IMAGE); + uchar4 *ref_out = new uchar4[width*height]; + + std::cout << "Calculating Hipacc erode filter ..." << std::endl; + + //************************************************************************// + + // input and output image of width x height pixels + Image<uchar4> in(width, height, input); + Image<uchar4> out(width, height); + + // define Domain for erode filter + Domain dom(size_x, size_y); + + BoundaryCondition<uchar4> bound(in, dom, Boundary::CLAMP); + Accessor<uchar4> acc(bound); + + IterationSpace<uchar4> iter(out); + Erode filter(iter, acc, dom); + + filter.execute(); + timing = hipacc_last_kernel_timing(); + + // get pointer to result data + uchar4 *output = out.data(); + + //************************************************************************// + + std::cout << "Hipacc: " << timing << " ms, " + << (width*height/timing)/1000 << " Mpixel/s" << std::endl; + + std::cout << "Calculating reference ..." << std::endl; + double start = time_ms(); + erode_filter(input, ref_out, size_x, size_y, width, height); + double end = time_ms(); + std::cout << "Reference: " << end-start << " ms, " + << (width*height/(end-start))/1000 << " Mpixel/s" << std::endl; + + compare_results((uchar*)output, (uchar*)ref_out, width*4, height, offset_x*4, offset_y); + + save_data(width, height, 4, (uchar*)input, "input.jpg"); + save_data(width, height, 4, (uchar*)output, "output.jpg"); + show_data(width, height, 4, (uchar*)output, "output.jpg"); + + // free memory + delete[] input; + delete[] ref_out; + + return EXIT_SUCCESS; +} + + +// erode filter reference +void erode_filter(uchar4 *in, uchar4 *out, int size_x, int size_y, + int width, int height) { + int anchor_x = size_x >> 1; + int anchor_y = size_y >> 1; + int upper_x = width - anchor_x; + int upper_y = height - anchor_y; + + for (int y=anchor_y; y<upper_y; ++y) { + for (int x=anchor_x; x<upper_x; ++x) { + uchar4 val = {255, 255, 255, 255}; + + for (int yf = -anchor_y; yf<=anchor_y; ++yf) { + for (int xf = -anchor_x; xf<=anchor_x; ++xf) { + val = min(val, in[(y + yf)*width + x + xf]); + } + } + out[y*width + x] = val; + } + } +} diff --git a/pool/shard007/C++/0092229_Worker.cpp b/pool/shard007/C++/0092229_Worker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..00389db9f479083f5c38cc9af20a1c0905ce4be3 --- /dev/null +++ b/pool/shard007/C++/0092229_Worker.cpp @@ -0,0 +1,142 @@ +/* + * Copyright (C) 2008, 2010 Apple Inc. All Rights Reserved. + * Copyright (C) 2009 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: + * 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. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" + +#include "core/workers/Worker.h" + +#include "core/dom/Document.h" +#include "core/dom/EventListener.h" +#include "core/dom/EventNames.h" +#include "core/dom/ExceptionCode.h" +#include "core/dom/MessageEvent.h" +#include "core/inspector/InspectorInstrumentation.h" +#include "core/loader/FrameLoader.h" +#include "core/loader/cache/CachedResourceLoader.h" +#include "core/page/DOMWindow.h" +#include "core/page/Frame.h" +#include "core/page/UseCounter.h" +#include "core/workers/WorkerContextProxy.h" +#include "core/workers/WorkerScriptLoader.h" +#include "core/workers/WorkerThread.h" +#include "wtf/MainThread.h" + +namespace WebCore { + +inline Worker::Worker(ScriptExecutionContext* context) + : AbstractWorker(context) + , m_contextProxy(WorkerContextProxy::create(this)) +{ + ScriptWrappable::init(this); +} + +PassRefPtr<Worker> Worker::create(ScriptExecutionContext* context, const String& url, ExceptionCode& ec) +{ + ASSERT(isMainThread()); + UseCounter::count(static_cast<Document*>(context)->domWindow(), UseCounter::WorkerStart); + + RefPtr<Worker> worker = adoptRef(new Worker(context)); + + worker->suspendIfNeeded(); + + KURL scriptURL = worker->resolveURL(url, ec); + if (scriptURL.isEmpty()) + return 0; + + // The worker context does not exist while loading, so we must ensure that the worker object is not collected, nor are its event listeners. + worker->setPendingActivity(worker.get()); + + worker->m_scriptLoader = WorkerScriptLoader::create(); + worker->m_scriptLoader->loadAsynchronously(context, scriptURL, DenyCrossOriginRequests, worker.get()); + + return worker.release(); +} + +Worker::~Worker() +{ + ASSERT(isMainThread()); + ASSERT(scriptExecutionContext()); // The context is protected by worker context proxy, so it cannot be destroyed while a Worker exists. + m_contextProxy->workerObjectDestroyed(); +} + +const AtomicString& Worker::interfaceName() const +{ + return eventNames().interfaceForWorker; +} + +void Worker::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionCode& ec) +{ + // Disentangle the port in preparation for sending it to the remote context. + OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, ec); + if (ec) + return; + m_contextProxy->postMessageToWorkerContext(message, channels.release()); +} + +void Worker::terminate() +{ + m_contextProxy->terminateWorkerContext(); +} + +bool Worker::canSuspend() const +{ + // FIXME: It is not currently possible to suspend a worker, so pages with workers can not go into page cache. + return false; +} + +void Worker::stop() +{ + terminate(); +} + +bool Worker::hasPendingActivity() const +{ + return m_contextProxy->hasPendingActivity() || ActiveDOMObject::hasPendingActivity(); +} + +void Worker::didReceiveResponse(unsigned long identifier, const ResourceResponse&) +{ + InspectorInstrumentation::didReceiveScriptResponse(scriptExecutionContext(), identifier); +} + +void Worker::notifyFinished() +{ + if (m_scriptLoader->failed()) + dispatchEvent(Event::create(eventNames().errorEvent, false, true)); + else { + WorkerThreadStartMode startMode = DontPauseWorkerContextOnStart; + if (InspectorInstrumentation::shouldPauseDedicatedWorkerOnStart(scriptExecutionContext())) + startMode = PauseWorkerContextOnStart; + m_contextProxy->startWorkerContext(m_scriptLoader->url(), scriptExecutionContext()->userAgent(m_scriptLoader->url()), m_scriptLoader->script(), startMode); + InspectorInstrumentation::scriptImported(scriptExecutionContext(), m_scriptLoader->identifier(), m_scriptLoader->script()); + } + m_scriptLoader = nullptr; + + unsetPendingActivity(this); +} + +} // namespace WebCore diff --git a/pool/shard007/C++/0092234_exception.cpp b/pool/shard007/C++/0092234_exception.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e0d6c6eb67bb8c1d5828a9a6d8af9760d025acdb --- /dev/null +++ b/pool/shard007/C++/0092234_exception.cpp @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2013 Uwe B. Meding <uwe@uwemeding.com> + * + * This file is part of UM/ISO + * This PCA software is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Isomorphism is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with UM/ISO. If not, see <http://www.gnu.org/licenses/>. + */ +#include <stdio.h> +#include <ctype.h> +#include <errno.h> +#include <string.h> +#include <stdlib.h> +#include <stdarg.h> +#include "compare.h" + +/** + * throwError -- returns to a save place for program resumtion + * + * This function works with the printf formatting rules to create + * messages that are passed back from the system. + * + * @param imEnv is the environment + * @param format is the format spec we use the message + */ +void throwError(IMEnv * imEnv, const char *format, ...) { + static char buffer[BUFSIZ]; + char *buf = buffer; + va_list argp; + + va_start(argp, format); + + char *p, + *bp, + *ta; + + bp = buf; + p = (char *) format; + while (*p) { + if (*p != '%') { + *bp++ = *p++; + } else { + char spec[BUFSIZ]; + char *ps, + *beginspec; + + beginspec = spec; + + beginspec = ps = spec; + + *ps++ = *p++; + while (1) + if ((isdigit(*p) || (*p == '-') || (*p == '.') + || (*p == 'l'))) + *ps++ = *p++; + else + break; + + *ps++ = *p; + *ps = '\0'; + + switch (*p) { + case 'q': + if ((errno > 0) && (errno <= sys_nerr)) { + (void) (strcpy(bp, sys_errlist[errno])); + bp += strlen(bp); + } else { + (void) (sprintf(bp, "(unknown errno %d)", errno)); + bp += strlen(bp); + } + break; + case 'd': + case 'o': + case 'x': + case 'u': + case 'c': + (void) sprintf(bp, beginspec, va_arg(argp, int)); + + bp += strlen(bp); + break; + + case ' ': + { + int len = atoi(beginspec + 1); + + bp[len] = '\0'; + while (len--) + bp[len] = ' '; + bp += strlen(bp); + } + break; + + case '%': + (void) sprintf(bp, "%%"); + bp += strlen(bp); + break; + + case 's': + ta = va_arg(argp, char *); + + (void) sprintf(bp, beginspec, ta ? ta : "(null)"); + bp += strlen(bp); + break; + + case 'e': + case 'f': + case 'g': + (void) sprintf(bp, beginspec, va_arg(argp, double)); + + bp += strlen(bp); + break; + + default: + (void) sprintf(bp, beginspec, 0); + + bp += strlen(bp); + break; + } + + ++p; + } + } + *bp = 0; + + va_end(argp); + + /* + * Jump to whereever we catch the errors. we are using the + * ability of longjmp to return a parameter to pass back + * a message to the catch location. + */ + throw buffer; +} diff --git a/pool/shard007/C++/0092235_raise.cpp b/pool/shard007/C++/0092235_raise.cpp new file mode 100644 index 0000000000000000000000000000000000000000..15f748cd09a2f38476f8458d2e0635e2e6fa3600 --- /dev/null +++ b/pool/shard007/C++/0092235_raise.cpp @@ -0,0 +1,26 @@ +//===-- Linux implementation of signal ------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "src/signal/raise.h" +#include "src/signal/linux/signal.h" + +#include "src/__support/common.h" + +namespace __llvm_libc { + +int LLVM_LIBC_ENTRYPOINT(raise)(int sig) { + __llvm_libc::Sigset sigset; + __llvm_libc::block_all_signals(sigset); + long pid = __llvm_libc::syscall(SYS_getpid); + long tid = __llvm_libc::syscall(SYS_gettid); + int ret = __llvm_libc::syscall(SYS_tgkill, pid, tid, sig); + __llvm_libc::restore_signals(sigset); + return ret; +} + +} // namespace __llvm_libc diff --git a/pool/shard007/C++/0092241_SkDisplayMath.cpp b/pool/shard007/C++/0092241_SkDisplayMath.cpp new file mode 100644 index 0000000000000000000000000000000000000000..66bd1f831b7d5cf697e2bcc6d111a2b343de225e --- /dev/null +++ b/pool/shard007/C++/0092241_SkDisplayMath.cpp @@ -0,0 +1,248 @@ +/* libs/graphics/animator/SkDisplayMath.cpp +** +** Copyright 2006, The Android Open Source Project +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +*/ + +#include "SkDisplayMath.h" + +enum SkDisplayMath_Properties { + SK_PROPERTY(E), + SK_PROPERTY(LN10), + SK_PROPERTY(LN2), + SK_PROPERTY(LOG10E), + SK_PROPERTY(LOG2E), + SK_PROPERTY(PI), + SK_PROPERTY(SQRT1_2), + SK_PROPERTY(SQRT2) +}; + +const SkScalar SkDisplayMath::gConstants[] = { +#ifdef SK_SCALAR_IS_FLOAT + 2.718281828f, // E + 2.302585093f, // LN10 + 0.693147181f, // LN2 + 0.434294482f, // LOG10E + 1.442695041f, // LOG2E + 3.141592654f, // PI + 0.707106781f, // SQRT1_2 + 1.414213562f // SQRT2 +#else + 0x2B7E1, // E + 0x24D76, // LN10 + 0xB172, // LN2 + 0x6F2E, // LOG10E + 0x17154, // LOG2E + 0x3243F, // PI + 0xB505, // SQRT1_2 + 0x16A0A // SQRT2 +#endif +}; + +enum SkDisplayMath_Functions { + SK_FUNCTION(abs), + SK_FUNCTION(acos), + SK_FUNCTION(asin), + SK_FUNCTION(atan), + SK_FUNCTION(atan2), + SK_FUNCTION(ceil), + SK_FUNCTION(cos), + SK_FUNCTION(exp), + SK_FUNCTION(floor), + SK_FUNCTION(log), + SK_FUNCTION(max), + SK_FUNCTION(min), + SK_FUNCTION(pow), + SK_FUNCTION(random), + SK_FUNCTION(round), + SK_FUNCTION(sin), + SK_FUNCTION(sqrt), + SK_FUNCTION(tan) +}; + +const SkFunctionParamType SkDisplayMath::fFunctionParameters[] = { + (SkFunctionParamType) SkType_Float, // abs + (SkFunctionParamType) 0, + (SkFunctionParamType) SkType_Float, // acos + (SkFunctionParamType) 0, + (SkFunctionParamType) SkType_Float, // asin + (SkFunctionParamType) 0, + (SkFunctionParamType) SkType_Float, // atan + (SkFunctionParamType) 0, + (SkFunctionParamType) SkType_Float, // atan2 + (SkFunctionParamType) SkType_Float, + (SkFunctionParamType) 0, + (SkFunctionParamType) SkType_Float, // ceil + (SkFunctionParamType) 0, + (SkFunctionParamType) SkType_Float, // cos + (SkFunctionParamType) 0, + (SkFunctionParamType) SkType_Float, // exp + (SkFunctionParamType) 0, + (SkFunctionParamType) SkType_Float, // floor + (SkFunctionParamType) 0, + (SkFunctionParamType) SkType_Float, // log + (SkFunctionParamType) 0, + (SkFunctionParamType) SkType_Array, // max + (SkFunctionParamType) 0, + (SkFunctionParamType) SkType_Array, // min + (SkFunctionParamType) 0, + (SkFunctionParamType) SkType_Float, // pow + (SkFunctionParamType) SkType_Float, + (SkFunctionParamType) 0, + (SkFunctionParamType) SkType_Float, // random + (SkFunctionParamType) 0, + (SkFunctionParamType) SkType_Float, // round + (SkFunctionParamType) 0, + (SkFunctionParamType) SkType_Float, // sin + (SkFunctionParamType) 0, + (SkFunctionParamType) SkType_Float, // sqrt + (SkFunctionParamType) 0, + (SkFunctionParamType) SkType_Float, // tan + (SkFunctionParamType) 0 +}; + +#if SK_USE_CONDENSED_INFO == 0 + +const SkMemberInfo SkDisplayMath::fInfo[] = { + SK_MEMBER_PROPERTY(E, Float), + SK_MEMBER_PROPERTY(LN10, Float), + SK_MEMBER_PROPERTY(LN2, Float), + SK_MEMBER_PROPERTY(LOG10E, Float), + SK_MEMBER_PROPERTY(LOG2E, Float), + SK_MEMBER_PROPERTY(PI, Float), + SK_MEMBER_PROPERTY(SQRT1_2, Float), + SK_MEMBER_PROPERTY(SQRT2, Float), + SK_MEMBER_FUNCTION(abs, Float), + SK_MEMBER_FUNCTION(acos, Float), + SK_MEMBER_FUNCTION(asin, Float), + SK_MEMBER_FUNCTION(atan, Float), + SK_MEMBER_FUNCTION(atan2, Float), + SK_MEMBER_FUNCTION(ceil, Float), + SK_MEMBER_FUNCTION(cos, Float), + SK_MEMBER_FUNCTION(exp, Float), + SK_MEMBER_FUNCTION(floor, Float), + SK_MEMBER_FUNCTION(log, Float), + SK_MEMBER_FUNCTION(max, Float), + SK_MEMBER_FUNCTION(min, Float), + SK_MEMBER_FUNCTION(pow, Float), + SK_MEMBER_FUNCTION(random, Float), + SK_MEMBER_FUNCTION(round, Float), + SK_MEMBER_FUNCTION(sin, Float), + SK_MEMBER_FUNCTION(sqrt, Float), + SK_MEMBER_FUNCTION(tan, Float) +}; + +#endif + +DEFINE_GET_MEMBER(SkDisplayMath); + +void SkDisplayMath::executeFunction(SkDisplayable* target, int index, + SkTDArray<SkScriptValue>& parameters, SkDisplayTypes type, + SkScriptValue* scriptValue) { + if (scriptValue == NULL) + return; + SkASSERT(target == this); + SkScriptValue* array = parameters.begin(); + SkScriptValue* end = parameters.end(); + SkScalar input = parameters[0].fOperand.fScalar; + SkScalar scalarResult; + switch (index) { + case SK_FUNCTION(abs): + scalarResult = SkScalarAbs(input); + break; + case SK_FUNCTION(acos): + scalarResult = SkScalarACos(input); + break; + case SK_FUNCTION(asin): + scalarResult = SkScalarASin(input); + break; + case SK_FUNCTION(atan): + scalarResult = SkScalarATan2(input, SK_Scalar1); + break; + case SK_FUNCTION(atan2): + scalarResult = SkScalarATan2(input, parameters[1].fOperand.fScalar); + break; + case SK_FUNCTION(ceil): + scalarResult = SkIntToScalar(SkScalarCeil(input)); + break; + case SK_FUNCTION(cos): + scalarResult = SkScalarCos(input); + break; + case SK_FUNCTION(exp): + scalarResult = SkScalarExp(input); + break; + case SK_FUNCTION(floor): + scalarResult = SkIntToScalar(SkScalarFloor(input)); + break; + case SK_FUNCTION(log): + scalarResult = SkScalarLog(input); + break; + case SK_FUNCTION(max): + scalarResult = -SK_ScalarMax; + while (array < end) { + scalarResult = SkMaxScalar(scalarResult, array->fOperand.fScalar); + array++; + } + break; + case SK_FUNCTION(min): + scalarResult = SK_ScalarMax; + while (array < end) { + scalarResult = SkMinScalar(scalarResult, array->fOperand.fScalar); + array++; + } + break; + case SK_FUNCTION(pow): + // not the greatest -- but use x^y = e^(y * ln(x)) + scalarResult = SkScalarLog(input); + scalarResult = SkScalarMul(parameters[1].fOperand.fScalar, scalarResult); + scalarResult = SkScalarExp(scalarResult); + break; + case SK_FUNCTION(random): + scalarResult = fRandom.nextUScalar1(); + break; + case SK_FUNCTION(round): + scalarResult = SkIntToScalar(SkScalarRound(input)); + break; + case SK_FUNCTION(sin): + scalarResult = SkScalarSin(input); + break; + case SK_FUNCTION(sqrt): { + SkASSERT(parameters.count() == 1); + SkASSERT(type == SkType_Float); + scalarResult = SkScalarSqrt(input); + } break; + case SK_FUNCTION(tan): + scalarResult = SkScalarTan(input); + break; + default: + SkASSERT(0); + scalarResult = SK_ScalarNaN; + } + scriptValue->fOperand.fScalar = scalarResult; + scriptValue->fType = SkType_Float; +} + +const SkFunctionParamType* SkDisplayMath::getFunctionsParameters() { + return fFunctionParameters; +} + +bool SkDisplayMath::getProperty(int index, SkScriptValue* value) const { + if ((unsigned)index < SK_ARRAY_COUNT(gConstants)) { + value->fOperand.fScalar = gConstants[index]; + value->fType = SkType_Float; + return true; + } + SkASSERT(0); + return false; +} diff --git a/pool/shard007/C++/0092243_Model.cpp b/pool/shard007/C++/0092243_Model.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a7071a5718c813029f6640cf36351f9d9f00a7b0 --- /dev/null +++ b/pool/shard007/C++/0092243_Model.cpp @@ -0,0 +1,132 @@ +// +// MountainSea.cpp +// MP2_Flight_Simulator +// +// Created by XuYiwen on 3/2/16. +// Copyright © 2016 evx. All rights reserved. +// + +#include "Model.hpp" + +int +MountainSea::seed(float x, float y){ + static int a = 1588635695, b = 1117695901; + int xi = *(int *)&x; + int yi = *(int *)&y; + return ((xi * a) % b) - ((yi * b) % a); +} + +void +MountainSea::mountain(float x0, float y0, float z0, + float x1, float y1, float z1, + float x2, float y2, float z2, float s){ + float x01,y01,z01,x12,y12,z12,x20,y20,z20; + + if (s < polysize) { + x01 = x1 - x0; + y01 = y1 - y0; + z01 = z1 - z0; + + x12 = x2 - x1; + y12 = y2 - y1; + z12 = z2 - z1; + + x20 = x0 - x2; + y20 = y0 - y2; + z20 = z0 - z2; + + float nx = y01*(-z20) - (-y20)*z01; + float ny = z01*(-x20) - (-z20)*x01; + float nz = x01*(-y20) - (-x20)*y01; + + float den = sqrt(nx*nx + ny*ny + nz*nz); + + if (den > 0.0) { + nx /= den; + ny /= den; + nz /= den; + } + + glNormal3f(nx,ny,nz); + glBegin(GL_TRIANGLES); + glVertex3f(x0,y0,z0); + glVertex3f(x1,y1,z1); + glVertex3f(x2,y2,z2); + glEnd(); + + return; + } + + x01 = 0.5*(x0 + x1); + y01 = 0.5*(y0 + y1); + z01 = 0.5*(z0 + z1); + + x12 = 0.5*(x1 + x2); + y12 = 0.5*(y1 + y2); + z12 = 0.5*(z1 + z2); + + x20 = 0.5*(x2 + x0); + y20 = 0.5*(y2 + y0); + z20 = 0.5*(z2 + z0); + + s *= 0.5; + + srand(seed(x01,y01)); + z01 += 0.3*s*(2.0*((float)rand()/(float)RAND_MAX) - 1.0); + srand(seed(x12,y12)); + z12 += 0.3*s*(2.0*((float)rand()/(float)RAND_MAX) - 1.0); + srand(seed(x20,y20)); + z20 += 0.3*s*(2.0*((float)rand()/(float)RAND_MAX) - 1.0); + + mountain(x0,y0,z0,x01,y01,z01,x20,y20,z20,s); + mountain(x1,y1,z1,x12,y12,z12,x01,y01,z01,s); + mountain(x2,y2,z2,x20,y20,z20,x12,y12,z12,s); + mountain(x01,y01,z01,x12,y12,z12,x20,y20,z20,s); +} +void +MountainSea::drawAll(){ + drawLight(); + drawMountain(); + drawSea(); +} + +void +MountainSea::drawMountain(){ + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, tanamb); + glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, tandiff); + glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, tanspec); + glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 10.0); + + mountain(0.0,0.0,0.0, 1.0,0.0,0.0, 0.0,1.0,0.0, 1.0); + mountain(1.0,1.0,0.0, 0.0,1.0,0.0, 1.0,0.0,0.0, 1.0); +} + +void +MountainSea::drawSea(){ + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, seaamb); + glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, seadiff); + glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, seaspec); + glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 10.0); + + glNormal3f(0.0,0.0,1.0); + glBegin(GL_QUADS); + glVertex3f(0.0,0.0,sealevel); + glVertex3f(1.0,0.0,sealevel); + glVertex3f(1.0,1.0,sealevel); + glVertex3f(0.0,1.0,sealevel); + glEnd(); +} + +void +MountainSea::drawLight(){ + glEnable(GL_LIGHTING); + glEnable(GL_LIGHT0); + + glLightfv(GL_LIGHT0, GL_POSITION, lpos); + glLightfv(GL_LIGHT0, GL_AMBIENT, white); + glLightfv(GL_LIGHT0, GL_DIFFUSE, white); + glLightfv(GL_LIGHT0, GL_SPECULAR, white); + + glClearColor (0.5, 0.5, 1.0, 0.0); + glEnable(GL_DEPTH_TEST); +} \ No newline at end of file diff --git a/pool/shard007/C++/0092250_GUIToolBar.cpp b/pool/shard007/C++/0092250_GUIToolBar.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d86ee1140ffe888b7bde6cbb6ca91fcda11d5887 --- /dev/null +++ b/pool/shard007/C++/0092250_GUIToolBar.cpp @@ -0,0 +1,112 @@ +#include "stdafx.h" +#include "GUIButton.h" +#include "GUIElement.h" +#include "GUIToolBar.h" +#include "Texture.h" + +using namespace irr; +using namespace System; + +namespace IrrlichtLime { +namespace GUI { + +GUIToolBar^ GUIToolBar::Wrap(gui::IGUIToolBar* ref) +{ + if (ref == nullptr) + return nullptr; + + return gcnew GUIToolBar(ref); +} + +GUIToolBar::GUIToolBar(gui::IGUIToolBar* ref) + : GUIElement(ref) +{ + LIME_ASSERT(ref != nullptr); + m_GUIToolBar = ref; +} + +GUIButton^ GUIToolBar::AddButton(int id, String^ text, String^ toolTipText, Video::Texture^ img, Video::Texture^ pressedImg, + bool isPushButton, bool useAlphaChannel) +{ + gui::IGUIButton* b = m_GUIToolBar->addButton( + id, + LIME_SAFESTRINGTOSTRINGW_C_STR(text), + LIME_SAFESTRINGTOSTRINGW_C_STR(toolTipText), + LIME_SAFEREF(img, m_Texture), + LIME_SAFEREF(pressedImg, m_Texture), + isPushButton, + useAlphaChannel); + + return GUIButton::Wrap(b); +} + +GUIButton^ GUIToolBar::AddButton(int id, String^ text, String^ toolTipText, Video::Texture^ img, Video::Texture^ pressedImg, + bool isPushButton) +{ + gui::IGUIButton* b = m_GUIToolBar->addButton( + id, + LIME_SAFESTRINGTOSTRINGW_C_STR(text), + LIME_SAFESTRINGTOSTRINGW_C_STR(toolTipText), + LIME_SAFEREF(img, m_Texture), + LIME_SAFEREF(pressedImg, m_Texture), + isPushButton); + + return GUIButton::Wrap(b); +} + +GUIButton^ GUIToolBar::AddButton(int id, String^ text, String^ toolTipText, Video::Texture^ img, Video::Texture^ pressedImg) +{ + gui::IGUIButton* b = m_GUIToolBar->addButton( + id, + LIME_SAFESTRINGTOSTRINGW_C_STR(text), + LIME_SAFESTRINGTOSTRINGW_C_STR(toolTipText), + LIME_SAFEREF(img, m_Texture), + LIME_SAFEREF(pressedImg, m_Texture)); + + return GUIButton::Wrap(b); +} + +GUIButton^ GUIToolBar::AddButton(int id, String^ text, String^ toolTipText, Video::Texture^ img) +{ + gui::IGUIButton* b = m_GUIToolBar->addButton( + id, + LIME_SAFESTRINGTOSTRINGW_C_STR(text), + LIME_SAFESTRINGTOSTRINGW_C_STR(toolTipText), + LIME_SAFEREF(img, m_Texture)); + + return GUIButton::Wrap(b); +} + +GUIButton^ GUIToolBar::AddButton(int id, String^ text, String^ toolTipText) +{ + gui::IGUIButton* b = m_GUIToolBar->addButton( + id, + LIME_SAFESTRINGTOSTRINGW_C_STR(text), + LIME_SAFESTRINGTOSTRINGW_C_STR(toolTipText)); + + return GUIButton::Wrap(b); +} + +GUIButton^ GUIToolBar::AddButton(int id, String^ text) +{ + gui::IGUIButton* b = m_GUIToolBar->addButton( + id, + LIME_SAFESTRINGTOSTRINGW_C_STR(text)); + + return GUIButton::Wrap(b); +} + +GUIButton^ GUIToolBar::AddButton(int id) +{ + gui::IGUIButton* b = m_GUIToolBar->addButton(id); + return GUIButton::Wrap(b); +} + +GUIButton^ GUIToolBar::AddButton() +{ + gui::IGUIButton* b = m_GUIToolBar->addButton(); + return GUIButton::Wrap(b); +} + +} // end namespace GUI +} // end namespace IrrlichtLime \ No newline at end of file diff --git a/pool/shard007/C++/0092251_pbf_sensor.cc b/pool/shard007/C++/0092251_pbf_sensor.cc new file mode 100644 index 0000000000000000000000000000000000000000..98992f81ff35b185bcd968782bb001219c480514 --- /dev/null +++ b/pool/shard007/C++/0092251_pbf_sensor.cc @@ -0,0 +1,97 @@ +/****************************************************************************** + * Copyright 2017 The Apollo 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 "modules/perception/obstacle/fusion/probabilistic_fusion/pbf_sensor.h" + +#include <memory> + +namespace apollo { +namespace perception { + +size_t PbfSensor::s_max_cached_frame_number_ = 10; + +PbfSensor::PbfSensor(const std::string &sensor_id, const SensorType &type) + : sensor_id_(sensor_id), sensor_type_(type) {} + +PbfSensor::~PbfSensor() {} + +void PbfSensor::QueryLatestFrames(const double time_stamp, + std::vector<PbfSensorFramePtr> *frames) { + CHECK_NOTNULL(frames); + frames->clear(); + for (size_t i = 0; i < frames_.size(); ++i) { + if (frames_[i]->timestamp > latest_query_timestamp_ && + frames_[i]->timestamp <= time_stamp) { + frames->push_back(frames_[i]); + } + } + latest_query_timestamp_ = time_stamp; +} + +PbfSensorFramePtr PbfSensor::QueryLatestFrame(const double time_stamp) { + PbfSensorFramePtr latest_frame = nullptr; + for (size_t i = 0; i < frames_.size(); ++i) { + if (frames_[i]->timestamp > latest_query_timestamp_ && + frames_[i]->timestamp <= time_stamp) { + latest_frame = frames_[i]; + latest_query_timestamp_ = frames_[i]->timestamp; + } + } + return latest_frame; +} + +void PbfSensor::AddFrame(const SensorObjects &frame) { + // NOTE: keep empty frame for completeness + PbfSensorFramePtr pbf_frame(new PbfSensorFrame()); + pbf_frame->timestamp = frame.timestamp; + pbf_frame->sensor2world_pose = frame.sensor2world_pose; + pbf_frame->sensor_type = frame.sensor_type; + pbf_frame->sensor_id = GetSensorType(frame.sensor_type); + pbf_frame->seq_num = frame.seq_num; + + pbf_frame->objects.resize(frame.objects.size()); + for (size_t i = 0; i < frame.objects.size(); ++i) { + std::shared_ptr<PbfSensorObject> obj(new PbfSensorObject()); + obj->timestamp = frame.timestamp; + obj->sensor_type = frame.sensor_type; + obj->object->clone(*(frame.objects[i])); + obj->sensor_id = GetSensorType(frame.sensor_type); + pbf_frame->objects[i] = obj; + } + if (frames_.size() > s_max_cached_frame_number_) { + frames_.pop_front(); + } + frames_.push_back(pbf_frame); +} + +bool PbfSensor::GetPose(const double time_stamp, const double time_range, + Eigen::Matrix4d *pose) { + CHECK_NOTNULL(pose); + CHECK_GE(time_range, 0.0); + + for (auto rit = frames_.rbegin(); rit != frames_.rend(); ++rit) { + const double time_diff = time_stamp - (*rit)->timestamp; + if (fabs(time_diff) < time_range) { + *pose = (*rit)->sensor2world_pose; + return true; + } + } + AERROR << "Failed to find velodyne2world pose for timestamp: " << time_stamp; + return false; +} + +} // namespace perception +} // namespace apollo diff --git a/pool/shard007/C++/0092253_test_String.cpp b/pool/shard007/C++/0092253_test_String.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d9ade0b5d79e3d6a55206965302d964b53957705 --- /dev/null +++ b/pool/shard007/C++/0092253_test_String.cpp @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2011-2022, The DART development contributors + * All rights reserved. + * + * The list of contributors can be found at: + * https://github.com/dartsim/dart/blob/master/LICENSE + * + * This file is provided under the following "BSD-style" License: + * 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. + * 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 <dart/common/String.hpp> +#include <gtest/gtest.h> + +using namespace dart; + +//============================================================================== +TEST(StringTest, CaseConversions) +{ + EXPECT_EQ(common::toUpper("to UppEr"), "TO UPPER"); + EXPECT_EQ(common::toLower("to LowEr"), "to lower"); + + std::string str; + + str = "toUppEr"; + common::toUpperInPlace(str); + EXPECT_EQ(str, "TOUPPER"); + + str = "toLowEr"; + common::toLowerInPlace(str); + EXPECT_EQ(str, "tolower"); +} + +//============================================================================== +TEST(StringTest, Trim) +{ + EXPECT_EQ(common::trimLeft(" trim ThIs "), "trim ThIs "); + EXPECT_EQ(common::trimRight(" trim ThIs "), " trim ThIs"); + EXPECT_EQ(common::trim(" trim ThIs "), "trim ThIs"); + + EXPECT_EQ(common::trimLeft("\n trim ThIs ", " "), "\n trim ThIs "); + EXPECT_EQ(common::trimLeft("\n trim ThIs ", "\n"), " trim ThIs "); + EXPECT_EQ(common::trimRight(" trim ThIs \n", " "), " trim ThIs \n"); + EXPECT_EQ(common::trimRight(" trim ThIs \n", "\n"), " trim ThIs "); + EXPECT_EQ(common::trim("\n trim ThIs \n", " "), "\n trim ThIs \n"); + EXPECT_EQ(common::trim("\n trim ThIs \n", "\n"), " trim ThIs "); + + EXPECT_EQ(common::trimLeft("\n trim ThIs \n", " \n"), "trim ThIs \n"); + EXPECT_EQ(common::trimRight("\n trim ThIs \n", " \n"), "\n trim ThIs"); + EXPECT_EQ(common::trim("\n trim ThIs \n", " \n"), "trim ThIs"); +} + +//============================================================================== +TEST(StringTest, Split) +{ + ASSERT_EQ(common::split(" trim ThIs ").size(), 2); + EXPECT_EQ(common::split(" trim ThIs ")[0], "trim"); + EXPECT_EQ(common::split(" trim ThIs ")[1], "ThIs"); + + ASSERT_EQ(common::split("ThiSisaNApPle ", "a").size(), 2); + ASSERT_EQ(common::split("ThiSisaNApPle ", "a")[0], "ThiSis"); + ASSERT_EQ(common::split("ThiSisaNApPle ", "a")[1], "NApPle "); + + ASSERT_EQ(common::split("ThiSisaNApPle ", "A").size(), 2); + ASSERT_EQ(common::split("ThiSisaNApPle ", "A")[0], "ThiSisaN"); + ASSERT_EQ(common::split("ThiSisaNApPle ", "A")[1], "pPle "); +} diff --git a/pool/shard007/C++/0092267_BatteryDispatcher.cpp b/pool/shard007/C++/0092267_BatteryDispatcher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7a71753a2ceb9280b7d7cdde69a49963ec79f032 --- /dev/null +++ b/pool/shard007/C++/0092267_BatteryDispatcher.cpp @@ -0,0 +1,74 @@ +// 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 "config.h" +#include "modules/battery/BatteryDispatcher.h" + +#include "modules/battery/BatteryStatus.h" +#include "public/platform/Platform.h" + +namespace blink { + +namespace { + +double ensureTwoSignificantDigits(double level) +{ + // Convert battery level value which should be in [0, 1] to a value in [0, 1] + // with 2 digits of precision. This is to provide a consistent experience + // across platforms (e.g. on Mac and Android the battery changes are generally + // reported with 1% granularity). It also serves the purpose of reducing the + // possibility of fingerprinting and triggers less level change events on + // platforms where the granularity is high. + ASSERT(level >= 0 && level <= 1); + return round(level * 100) / 100.f; +} + +} // namespace + + +BatteryDispatcher& BatteryDispatcher::instance() +{ + DEFINE_STATIC_LOCAL(Persistent<BatteryDispatcher>, batteryDispatcher, (new BatteryDispatcher())); + return *batteryDispatcher; +} + +BatteryDispatcher::BatteryDispatcher() +{ +} + +BatteryDispatcher::~BatteryDispatcher() +{ +} + +DEFINE_TRACE(BatteryDispatcher) +{ + visitor->trace(m_batteryStatus); + PlatformEventDispatcher::trace(visitor); +} + +void BatteryDispatcher::updateBatteryStatus(const WebBatteryStatus& batteryStatus) +{ + m_batteryStatus = BatteryStatus::create( + batteryStatus.charging, batteryStatus.chargingTime, batteryStatus.dischargingTime, + ensureTwoSignificantDigits(batteryStatus.level)); + notifyControllers(); +} + +BatteryStatus* BatteryDispatcher::latestData() +{ + return m_batteryStatus.get(); +} + +void BatteryDispatcher::startListening() +{ + Platform::current()->startListening(WebPlatformEventBattery, this); +} + +void BatteryDispatcher::stopListening() +{ + Platform::current()->stopListening(WebPlatformEventBattery); + m_batteryStatus.clear(); +} + +} // namespace blink diff --git a/pool/shard007/C++/0092269_renderarea.cpp b/pool/shard007/C++/0092269_renderarea.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aba14db2ceae66e8eaa1d4d27981e5369f1ae60e --- /dev/null +++ b/pool/shard007/C++/0092269_renderarea.cpp @@ -0,0 +1,47 @@ +#include <QPainter> + +#include "renderarea.h" + +RenderArea::RenderArea(QWidget *parent) + : QWidget(parent) +{ + setBackgroundRole(QPalette::Base); + setAutoFillBackground(true); + + level = 0; + setMinimumHeight(30); + setMinimumWidth(200); +} + +void RenderArea::paintEvent(QPaintEvent * /* event */) +{ + QPainter painter(this); + + painter.setPen(Qt::black); + painter.drawRect(QRect(painter.viewport().left()+10, + painter.viewport().top()+10, + painter.viewport().right()-20, + painter.viewport().bottom()-20)); + if (level == 0) + return; + + painter.setPen(Qt::red); + + int pos = ((painter.viewport().right()-20)-(painter.viewport().left()+11))*level/100; + for (int i = 0; i < 10; ++i) { + int x1 = painter.viewport().left()+11; + int y1 = painter.viewport().top()+10+i; + int x2 = painter.viewport().left()+20+pos; + int y2 = painter.viewport().top()+10+i; + if (x2 < painter.viewport().left()+10) + x2 = painter.viewport().left()+10; + + painter.drawLine(QPoint(x1, y1),QPoint(x2, y2)); + } +} + +void RenderArea::setLevel(int value) +{ + level = value; + repaint(); +} diff --git a/pool/shard007/C++/0092275_main.cpp b/pool/shard007/C++/0092275_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..18062d91a98ee7ef7df4cef65672a061b3e1aa38 --- /dev/null +++ b/pool/shard007/C++/0092275_main.cpp @@ -0,0 +1,42 @@ +/*----------------------------------------*/ +// Test receiving messages from master +// +// This receives a message from master (command 0x01), +// which tells it to turn an LED on or off. +// +/*----------------------------------------*/ + +#include <stdint.h> + +#include "MultidropSlave.h" +#include "MultidropDataUart.h" + +#define NODE_ADDRESS 1 + +void responseHandler(uint8_t command, uint8_t *buff,uint8_t len); + +int main() { + uint8_t ledOn = 0; + + // Button on PB3 + DDRB &= ~(1 << PB3); + + // Setup serial + MultidropDataUart serial; + serial.begin(9600); + + // Slave node, with response handler + MultidropSlave slave(&serial); + slave.setAddress(NODE_ADDRESS); + slave.setResponseHandler(&responseHandler); + + // Wait around reading from the bus. Responses are handled automatically. + while(1) { + slave.read(); + } +} + +void responseHandler(uint8_t command, uint8_t *buff, uint8_t len) { + buff[0] = !!(PINB & (1<<PB3)); +} + diff --git a/pool/shard007/C++/0092286_glxwrapper.cc b/pool/shard007/C++/0092286_glxwrapper.cc new file mode 100644 index 0000000000000000000000000000000000000000..76f4e4718ce0a2168f5fc056ba5d5a0f9e194c65 --- /dev/null +++ b/pool/shard007/C++/0092286_glxwrapper.cc @@ -0,0 +1,321 @@ +/** @file gfx/glxwrapper.cc GlWindowInterface implementation using the + X11 GLX API. */ + +/////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2005-2007 University of Southern California +// Rob Peters <https://github.com/rjpcal/> +// +// created: Fri Nov 11 16:10:15 2005 +// +// -------------------------------------------------------------------- +// +// This file is part of GroovX. +// [https://github.com/rjpcal/groovx] +// +// GroovX is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// GroovX is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with GroovX; if not, write to the Free Software Foundation, +// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. +// +/////////////////////////////////////////////////////////////////////// + +#ifdef GVX_GL_PLATFORM_GLX + +#include "gfx/glxwrapper.h" + +#include "gfx/glxopts.h" + +#include "rutz/error.h" + +#include <memory> + +#include "rutz/debug.h" +GVX_DBG_REGISTER +#include "rutz/trace.h" + +namespace +{ + // For caching the latest subject of GlxWrapper::makeCurrent() + const GlxWrapper* currentGlxWrapper = nullptr; + + // Builds a formatted data array for constructing a GLX context. + class AttribList + { + private: + static constexpr int MAXSIZE = 1000; + + void push(int v) + { + GVX_ASSERT(next < MAXSIZE); + data[next++] = v; + } + + void cap() + { + data[next] = None; + } + + int data[MAXSIZE]; + int next; + + public: + /// Default constructor. + AttribList(const GlxOpts& opts) : next(0) + { + push( GLX_USE_GL ); + + if (opts.rgbaFlag) this->rgba(opts.rgbaRed, opts.rgbaGreen, opts.rgbaBlue, + opts.alphaFlag ? opts.alphaSize : -1); + + else this->colorIndex( opts.colorIndexSize ); + + if (opts.depthFlag) this->depthBuffer( opts.depthSize ); + + if (opts.doubleFlag) this->doubleBuffer(); + + if (opts.stencilFlag) this->stencilBuffer( opts.stencilSize ); + + if (opts.accumFlag) this->accum(opts.accumRed, opts.accumGreen, opts.accumBlue, + opts.alphaFlag ? opts.accumAlpha : -1); + + if (opts.auxNumber > 0) this->auxBuffers( opts.auxNumber ); + + if (opts.level != 0) this->level( opts.level ); + + if (opts.transparent) this->transparent(); + } + + /// Get the underlying data array to use to construct a GLXContext. + int* get() { cap(); return data; } + + /// Set RGBA-mode minimum bit-depths. + void rgba(int rbits, int gbits, int bbits, int abits = -1) + { + push( GLX_RGBA ); + push( GLX_RED_SIZE ); + push( rbits ); dbg_eval(3, rbits); + push( GLX_GREEN_SIZE ); + push( gbits ); dbg_eval(3, gbits); + push( GLX_BLUE_SIZE ); + push( bbits ); dbg_eval_nl(3, bbits); + if (abits > 0) + { + push( GLX_ALPHA_SIZE ); + push( abits ); dbg_eval_nl(3, abits); + } + } + + /// Specify the stacking level for this context. + void level(int lev) + { + push( GLX_LEVEL ); + push( lev ); + } + + /// Specify a minimum bit-depth for color-index mode. + void colorIndex(int bits) + { + push( GLX_BUFFER_SIZE ); + push( bits ); + } + + /// Specify a minimum bit-depth for the depth-buffer (i.e. z-buffer). + void depthBuffer(int bits) + { + push( GLX_DEPTH_SIZE ); + push( bits ); + } + + /// Request double-buffering mode. + void doubleBuffer() + { + push( GLX_DOUBLEBUFFER ); + } + + /// Specify a minimum bit-depth for the stencil buffer. + void stencilBuffer(int bits) + { + push( GLX_STENCIL_SIZE ); + push( bits ); + } + + /// Specify minimum bit-depths for the accum buffer. + void accum(int rbits, int gbits, int bbits, int abits = -1) + { + push( GLX_ACCUM_RED_SIZE ); + push( rbits ); + push( GLX_ACCUM_GREEN_SIZE ); + push( gbits ); + push( GLX_ACCUM_BLUE_SIZE ); + push( bbits ); + if (abits > 0) + { + push( GLX_ACCUM_ALPHA_SIZE ); + push( abits ); + } + } + + /// Request a number of aux buffers. + void auxBuffers(int n) + { + push( GLX_AUX_BUFFERS ); + push( n ); + } + + /// Request transparency if available. + void transparent() + { +#ifdef GLX_TRANSPARENT_TYPE_EXT + push( GLX_TRANSPARENT_TYPE_EXT ); + push( GLX_TRANSPARENT_INDEX_EXT ); +#endif + } + }; +} + +GlxWrapper::GlxWrapper(Display* dpy, GlxOpts& opts, GlxWrapper* share) : + itsDisplay(dpy), + itsVisInfo(nullptr), + itsContext(nullptr), + itsCurrentWin(0) +{ +GVX_TRACE("GlxWrapper::GlxWrapper"); + + int dummy; + if (!glXQueryExtension(dpy, &dummy, &dummy)) + { + throw rutz::error("GlxWrapper: X server has no OpenGL GLX extension", SRC_POS); + } + + AttribList attribs(opts); + + dbg_eval_nl(3, (void*)itsDisplay); + dbg_eval_nl(3, DefaultScreen(itsDisplay)); + + int errorBase = 0; + int eventBase = 0; + + if (False == glXQueryExtension(itsDisplay, &errorBase, &eventBase)) + { + throw rutz::error("no GLX extension on the X server", SRC_POS); + } + + itsVisInfo = glXChooseVisual(itsDisplay, + DefaultScreen(itsDisplay), + attribs.get()); + + // If we had requested single-buffering, then now try for + // double-buffering, since that can emulate single-buffering + if (itsVisInfo == nullptr) + { + attribs.doubleBuffer(); + itsVisInfo = glXChooseVisual(itsDisplay, + DefaultScreen(itsDisplay), + attribs.get()); + } + + // If we still didn't get a matching visual, then bail out + if (itsVisInfo == nullptr) + { + throw rutz::error("couldn't find a matching visual", SRC_POS); + } + + dbg_eval_nl(3, (void*)itsVisInfo->visualid); + dbg_eval_nl(3, itsVisInfo->depth); + dbg_eval_nl(3, itsVisInfo->bits_per_rgb); + + itsContext = glXCreateContext(itsDisplay, + itsVisInfo, + share ? share->itsContext : None, + opts.indirect ? GL_FALSE : GL_TRUE); + + dbg_eval_nl(3, itsContext); + + if (itsContext == nullptr) + { + throw rutz::error("could not create GL rendering context", SRC_POS); + } +} + +GlxWrapper::~GlxWrapper() +{ +GVX_TRACE("GlxWrapper::~GlxWrapper"); + + glXDestroyContext(itsDisplay, itsContext); + XFree(itsVisInfo); +} + +GlxWrapper* GlxWrapper::make(Display* dpy, GlxOpts& opts, GlxWrapper* share) +{ +GVX_TRACE("GlxWrapper::make"); + + // Create a new OpenGL rendering context. + GlxWrapper* glx = new GlxWrapper(dpy, opts, share); + + // Make sure we don't try to use a depth buffer with indirect rendering + if ( !glx->isDirect() && opts.depthFlag ) + { + delete glx; + opts.depthFlag = false; + return make(dpy, opts, share); + } + + opts.indirect = !glx->isDirect(); + + return glx; +} + +void GlxWrapper::makeCurrent() +{ +GVX_TRACE("GlxWrapper::makeCurrent"); + + GVX_ASSERT(itsCurrentWin != 0); + + if (currentGlxWrapper != this) + { + glXMakeCurrent(itsDisplay, itsCurrentWin, itsContext); + currentGlxWrapper = this; + } +} + +void GlxWrapper::onReshape(int /*width*/, int /*height*/) +{ + // nothing to do here +} + +bool GlxWrapper::isDoubleBuffered() const +{ +GVX_TRACE("GlxWrapper::isDoubleBuffered"); + + int dbl_flag; + + if (glXGetConfig(itsDisplay, itsVisInfo, GLX_DOUBLEBUFFER, &dbl_flag) != 0) + { + throw rutz::error("glXGetConfig failed", SRC_POS); + } + + return bool(dbl_flag); +} + +unsigned int GlxWrapper::bitsPerPixel() const +{ +GVX_TRACE("GlxWrapper::bitsPerPixel"); + return (unsigned int)(itsVisInfo->depth); +} + +void GlxWrapper::swapBuffers() const +{ + glXSwapBuffers(itsDisplay, itsCurrentWin); +} + +#endif // GVX_GL_PLATFORM_GLX diff --git a/pool/shard007/C++/0092297_actionarea.cc b/pool/shard007/C++/0092297_actionarea.cc new file mode 100644 index 0000000000000000000000000000000000000000..12e6359c0f3606c847eefaedbe972ccda277a2e4 --- /dev/null +++ b/pool/shard007/C++/0092297_actionarea.cc @@ -0,0 +1,81 @@ +// X-Plot -- a program for visualizing complex functions +// +// Copyright (C) 1996-2011 Martin Eskildsen. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see <http://www.gnu.org/licenses/>. +// +// Comments, suggestions, questions to: +// Martin Eskildsen +// eskild.opensource@gmail.com +// +// +// Programming by Martin Eskildsen, (then) student at the +// Technical University of Denmark. + +#include "actionarea.h" + +#define TIGHTNESS 20 + +Widget CreateActionArea(Widget parent, ActionAreaItem *actions, int num_actions) +{ + Widget action_area, widget; + int i; + + action_area = XtVaCreateWidget ("action_area", xmFormWidgetClass, parent, + XmNfractionBase, TIGHTNESS*num_actions - 1, + XmNleftOffset, 10, + XmNrightOffset, 10, + NULL); + + for (i = 0; i < num_actions; i++) { + widget = XtVaCreateManagedWidget (actions[i].label, + xmPushButtonWidgetClass, action_area, + XmNleftAttachment, i? XmATTACH_POSITION : XmATTACH_FORM, + XmNleftPosition, TIGHTNESS*i, + XmNtopAttachment, XmATTACH_FORM, + XmNbottomAttachment, XmATTACH_FORM, + XmNrightAttachment, + i != num_actions - 1 ? XmATTACH_POSITION : XmATTACH_FORM, + XmNrightPosition, TIGHTNESS * i + (TIGHTNESS - 1), + XmNshowAsDefault, i == 0, + XmNdefaultButtonShadowThickness, 1, + NULL); + if (actions[i].callback) + XtAddCallback (widget, XmNactivateCallback, + actions[i].callback, actions[i].data); + if (i == 0) { + /* Set the action_area's default button to the first widget + * created (or, make the index a parameter to the function + * or have it be part of the data structure). Also, set the + * pane window constraint for max and min heights so this + * particular pane in the PanedWindow is not resizable. + */ + Dimension height, h; + XtVaGetValues (action_area, XmNmarginHeight, &h, NULL); + XtVaGetValues (widget, XmNheight, &height, NULL); + height += 2 * h; + XtVaSetValues (action_area, + XmNdefaultButton, widget, + XmNpaneMaximum, height, + XmNpaneMinimum, height, + NULL); + } + } + + XtManageChild (action_area); + + return action_area; +} + +/* EOF */ diff --git a/pool/shard007/C++/0092309_cyberspace_neural_connector_output.cpp b/pool/shard007/C++/0092309_cyberspace_neural_connector_output.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7ad07458e9bee3e0fd1ab8589a79a086cc293603 --- /dev/null +++ b/pool/shard007/C++/0092309_cyberspace_neural_connector_output.cpp @@ -0,0 +1,76 @@ +/* + * cyberspace is 3D first person mmorpg game engine, with 2D minigame + * plugins, initially developed to be used on LAN as an additional + * game element for a cyberpunk LARPG. + * + * Copyright (C) 2008-2012 Claudio Felicioli + * mail: pangon@gmail.com + * + * cyberspace is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "cyberspace_neural_connector_output.h" + + + +void cyberspace_neural_connector_output(cyberspace_user_command* command) { + int memcpy_size_partial; + int memcpy_size_total; + + memcpy_size_total=sizeof(memcpy_size_total); + + memcpy_size_partial=sizeof(cyberspace_user_command); + memcpy(cyberspace_write_buffer+memcpy_size_total, command, memcpy_size_partial); + memcpy_size_total+=memcpy_size_partial; + + memcpy_size_partial=sizeof(memcpy_size_total); + memcpy(cyberspace_write_buffer, &memcpy_size_total, memcpy_size_partial); + + cyberspace_to_write=memcpy_size_total; + + if(SDLNet_TCP_Send(cyberspace_output_socket, cyberspace_write_buffer, cyberspace_to_write)<cyberspace_to_write) { + fprintf(stderr, "FATAL ERROR: SDLNet_TCP_Send: %s.\n", SDLNet_GetError()); + exit(EXIT_FAILURE); + } + +/* + cyberspace_written_total=0; + while(cyberspace_to_write>cyberspace_written_total) { +// printf("sending\n"); + SDL_Delay(100); + cyberspace_written_partial=send(cyberspace_output_socket_fd, cyberspace_write_buffer+cyberspace_written_total, cyberspace_to_write-cyberspace_written_total, 0); +// printf("sendt (%d)\n", cyberspace_written_partial); +// perror("perror: "); +// SDL_Delay(100); + if(cyberspace_written_partial==-1) { +// printf("error\n"); +// SDL_Delay(100); + perror("perror: "); + fprintf(stderr, "ERROR: (in connector_output) communication with server failed.\n"); + exit(EXIT_FAILURE); + } + if(cyberspace_written_partial==0) { +// printf("error\n"); +// SDL_Delay(100); + perror("perror: "); + fprintf(stderr, "ERROR: (in connector_output) communication with server failed.\n"); + exit(EXIT_FAILURE); + } +// printf("noerror\n"); + cyberspace_written_total+=cyberspace_written_partial; + } +*/ + } + diff --git a/pool/shard007/C++/0092311_mTradeDetail.cpp b/pool/shard007/C++/0092311_mTradeDetail.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5f47d21d9bf2570a426973e8fca2388d945c9539 --- /dev/null +++ b/pool/shard007/C++/0092311_mTradeDetail.cpp @@ -0,0 +1,99 @@ +#include "mTradeDetail.h" + +void inputRawData(VectorTradeDetail& stockstream,char* inFileName) +{ + std::ifstream fin; + fin.open(inFileName); + + std::string str; + std::getline(fin, str); // headline of table + + int comma=0; + std::string atp; + + while (std::getline(fin,str)) + { + //RawMaterial,row 0-48 + if (str.length()==0) continue; + mTradeDetail tp; + while (str.length()>0) + { + comma = str.find(","); + if (comma!=-1) + { + atp = str.substr(0, comma); + tp.RawMaterial.push_back(atp); + str.erase(0, comma + 1); + } + else + { + tp.RawMaterial.push_back(str); + str=""; + } + } + + //row 1 : Index + tp.Index=mTime::stringtoint(tp.RawMaterial[InputFormat::RowIndex]); + //row 2 : contemporary Price + tp.Price=mTime::stringtodouble(tp.RawMaterial[InputFormat::RowContempPrice]); + //row 5 : TotalTurnover + tp.TotalTurnover=mTime::stringtoint(tp.RawMaterial[InputFormat::RowTotalTurnover]); + //row 29: Time + tp.RawMaterial[InputFormat::RowTime][13]='0'; //set the last digit=0, making the step = 10s + tp.Time.transfer(tp.RawMaterial[29]); + + stockstream.push_back(tp); + } + + fin.close(); +} + +void mTradeDetail::printcout() +{ + std::cout<<Index<<" " + <<TotalTurnover<<" " + <<Time.toString()<<" " + <<Price<<std::endl; +} + +mStockState mTradeDetail::toStockState() const +{ + mStockState mss(Index,Time,Price, + mTime::stringtodouble(RawMaterial[InputFormat::RowClosingPrice]), + mTime::stringtodouble(RawMaterial[InputFormat::RowOpenPrice]) + ); + return mss; +} +mSonFundState mTradeDetail::toSonFundState() const +{ + mSonFundState msfs(Index,Time,Price, + mTime::stringtodouble(RawMaterial[InputFormat::RowClosingPrice]), + mTime::stringtodouble(RawMaterial[InputFormat::RowOpenPrice]) + ); + return msfs; +} +mETFState mTradeDetail::toETFState () const +{ + mETFState mes(Index,Time,Price, + mTime::stringtodouble(RawMaterial[InputFormat::RowClosingPrice]), + mTime::stringtodouble(RawMaterial[InputFormat::RowOpenPrice]) + ); + return mes; +} + + +std::ostream& operator << (std::ostream &osm, const mTradeDetail& mTD) +{ + osm<<mTD.Index<<" " + <<mTD.Price<<" " + <<mTD.TotalTurnover<<" " + <<mTD.Time.toString(mTime::StandardFormat); + return osm; +} + +void showVectorTradeDetailToCout(const VectorTradeDetail& stockstream) +{ + std::cout << std::endl; + for (auto i = stockstream.begin(); i != stockstream.end(); i++) + std::cout << (*i) << std::endl; +} diff --git a/pool/shard007/C++/0092318_texture-set-image.cpp b/pool/shard007/C++/0092318_texture-set-image.cpp new file mode 100644 index 0000000000000000000000000000000000000000..312e98b05b01bd6bf97aa73b5b0a375c803f4899 --- /dev/null +++ b/pool/shard007/C++/0092318_texture-set-image.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * 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. + * + */ + +// CLASS HEADER +#include "texture-set-image.h" + +// INTERNAL INCLUDES +#include <dali/internal/event/rendering/texture-set-impl.h> +#include <dali/internal/event/images/image-impl.h> + +namespace Dali +{ + + +void TextureSetImage( TextureSet textureSet, size_t index, Image image ) +{ + // Get implementation of the TextureSet to use. + Internal::TextureSet& internalTextureSet = GetImplementation( textureSet ); + + // Check for valid image. + if( image ) + { + // Get image impl and set in TextureSet. + Internal::ImagePtr imagePointer( &GetImplementation( image ) ); + internalTextureSet.SetImage( index, imagePointer ); + } + else + { + // No valid image, Remove texture at this index. + internalTextureSet.SetImage( index, NULL ); + } +} + +Image TextureGetImage( TextureSet textureSet, size_t index ) +{ + // Get implementation of the TextureSet to use. + Internal::TextureSet& internalTextureSet = GetImplementation( textureSet ); + + // Get a pointer to the image implementation. + Internal::Image* imagePointer = internalTextureSet.GetImage( index ); + + // Return a handle to the image. + return Dali::Image( imagePointer ); +} + + +} // namespace Dali diff --git a/pool/shard007/C++/0092322_OcclusionQueryOGL.cpp b/pool/shard007/C++/0092322_OcclusionQueryOGL.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b89604571a066c0a1c9f8482e32c3537c4545e07 --- /dev/null +++ b/pool/shard007/C++/0092322_OcclusionQueryOGL.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2006-2010 - Frictional Games + * + * This file is part of HPL1 Engine. + * + * HPL1 Engine is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * HPL1 Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with HPL1 Engine. If not, see <http://www.gnu.org/licenses/>. + */ +#include "impl/OcclusionQueryOGL.h" + +#include <GL/GLee.h> + + +namespace hpl { + + ////////////////////////////////////////////////////////////////////////// + // CONSTRUCTORS + ////////////////////////////////////////////////////////////////////////// + + //----------------------------------------------------------------------- + + cOcclusionQueryOGL::cOcclusionQueryOGL() + { + glGenQueriesARB(1, (GLuint *)&mlQueryId); + mlLastSampleCount =0; + } + + //----------------------------------------------------------------------- + + cOcclusionQueryOGL::~cOcclusionQueryOGL() + { + glDeleteQueriesARB(1, (GLuint *)&mlQueryId); + } + + //----------------------------------------------------------------------- + + ////////////////////////////////////////////////////////////////////////// + // PUBLIC METHODS + ////////////////////////////////////////////////////////////////////////// + + //----------------------------------------------------------------------- + + void cOcclusionQueryOGL::Begin() + { + glBeginQueryARB(GL_SAMPLES_PASSED_ARB,mlQueryId); + } + + void cOcclusionQueryOGL::End() + { + glEndQueryARB(GL_SAMPLES_PASSED_ARB); + } + + bool cOcclusionQueryOGL::FetchResults() + { + int lAvailable=0; + glGetQueryObjectivARB(mlQueryId,GL_QUERY_RESULT_AVAILABLE_ARB,(GLint *)&lAvailable); + if(lAvailable==0) return false; + + glGetQueryObjectivARB(mlQueryId,GL_QUERY_RESULT_ARB,(GLint *)&mlLastSampleCount); + return true; + } + + unsigned int cOcclusionQueryOGL::GetSampleCount() + { + return mlLastSampleCount; + } + + //----------------------------------------------------------------------- +} diff --git a/pool/shard007/C++/0092323_epoll-server.cpp b/pool/shard007/C++/0092323_epoll-server.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1ab597c4cbf3be8f4a5203fa5aad1004fbed42dc --- /dev/null +++ b/pool/shard007/C++/0092323_epoll-server.cpp @@ -0,0 +1,225 @@ +#include "epoll-utils.h" + + +void setnonblocking(int sock) +{ + int opts; + opts=fcntl(sock,F_GETFL); + + if(opts<0) + { + perror("fcntl(sock,GETFL)"); + exit(1); + } + + opts = opts | O_NONBLOCK; + + if(fcntl(sock,F_SETFL,opts)<0) + { + perror("fcntl(sock,SETFL,opts)"); + exit(1); + } +} + + + + +/* + 假如发送端流量大于接收端的流量 + (意思是epoll所在的程序读比转发的socket要快), + 由于是非阻塞的socket,那么send()函数虽然返回, + 但实际缓冲区的数据并未真正发给接收端, + 这样不断的读和发, + 当缓冲区满后会产生EAGAIN错误(参考man send),同时, + 不理会这次请求发送的数据.所以, + 需要封装socket_send()的函数用来处理这种情况, + 该函数会尽量将数据写完再返回,返回-1表示出错。 + 在socket_send()内部,当写缓冲已满(send()返回-1,且errno为EAGAIN), + 那么会等待后再重试.这种方式并不很完美, + 在理论上可能会长时间的阻塞在socket_send()内部, + 但暂没有更好的办法. + + */ + +ssize_t socket_send(int sockfd, const char* buffer, size_t buflen) +{ + ssize_t tmp; + size_t total = buflen; + const char *p = buffer; + + while(1) + { + tmp = send(sockfd, p, total, 0); + if(tmp < 0) + { + // 当send收到信号时,可以继续写,但这里返回-1. + if(errno == EINTR) + //return -1;zxd + continue; + + // 当socket是非阻塞时,如返回此错误,表示写缓冲队列已满, + // 在这里做延时后再重试. + if(errno == EAGAIN) + { + usleep(1000); + continue; + } + + return -1; + } + + if((size_t)tmp == total) + return buflen; + + total -= tmp; + p += tmp; + } + + return tmp; +} + + +void epoll_ctl_err_show() +{ + std::cout << "error at epoll_ctl" << std::endl; + if(EBADF == errno) + { + std::cout << "error at epoll_ctl, error is EBADF" << std::endl; + } + else if(EEXIST == errno) + { + std::cout << "error at epoll_ctl, error is EEXIST" << std::endl; + } + else if(EINVAL == errno) + { + std::cout << "error at epoll_ctl, error is EINVAL" << std::endl; + } + else if(ENOENT == errno) + { + std::cout << "error at epoll_ctl, error is ENOENT" << std::endl; + } + else if(ENOMEM == errno) + { + std::cout << "error at epoll_ctl, error is ENOMEM" << std::endl; + } + else if(ENOSPC == errno) + { + std::cout << "error at epoll_ctl, error is ENOSPC" << std::endl; + } + +} + +int main() +{ + int i, maxi, listenfd, connfd, sockfd, epfd, nfds; + ssize_t n; + char line[MAXLINE]; + socklen_t clilen; + + struct epoll_event ev,events[20]; //声明epoll_event结构体的变量, ev用于注册事件, events数组用于回传要处理的事件 + epfd=epoll_create(256); //生成用于处理accept的epoll专用的文件描述符, 指定生成描述符的最大范围为256 + + struct sockaddr_in clientaddr; + struct sockaddr_in serveraddr; + + listenfd = socket(AF_INET, SOCK_STREAM, 0); + + setnonblocking(listenfd); //把用于监听的socket设置为非阻塞方式 + + ev.data.fd=listenfd; //设置与要处理的事件相关的文件描述符 + ev.events=EPOLLIN | EPOLLET; //设置要处理的事件类型 + epoll_ctl(epfd,EPOLL_CTL_ADD,listenfd,&ev); //注册epoll事件 + + bzero(&serveraddr, sizeof(serveraddr)); + serveraddr.sin_family = AF_INET; + char *local_addr = (char*)"127.0.0.1"; + inet_aton(local_addr,&(serveraddr.sin_addr)); + serveraddr.sin_port=htons(SERV_PORT); //或者htons(SERV_PORT); + + bind(listenfd,(sockaddr *)&serveraddr, sizeof(serveraddr)); + + listen(listenfd, LISTENQ); + + maxi = 0; + + while(true) { + nfds=epoll_wait(epfd, events, 20, -1); //等待epoll事件的发生 + + + for(i=0;i<nfds;++i) //处理所发生的所有事件 + { + if(events[i].data.fd==listenfd) /**监听事件**/ + { + //循环accept + while((connfd = accept(listenfd,(sockaddr *)&clientaddr, &clilen)) > 0) + { + setnonblocking(connfd); //把客户端的socket设置为非阻塞方式 + + char *str = inet_ntoa(clientaddr.sin_addr); + std::cout<<"connect from "<<str<<std::endl; + + ev.data.fd=connfd; //设置用于读操作的文件描述符 + ev.events=EPOLLIN | EPOLLET; //设置用于注测的读操作事件 + epoll_ctl(epfd,EPOLL_CTL_ADD,connfd,&ev); //注册ev事件 + } + } + else if(events[i].events&EPOLLIN) /**读事件**/ + { + fprintf(stderr, "EPOLLIN: %d, fd: %d\n", maxi++, events[i].data.fd); + if ( (sockfd = events[i].data.fd) < 0) + { + continue; + } + memset(line, 0, MAXLINE); + n = 0; + int nread = 0; + while((nread= read(sockfd, line + n, MAXLINE)) > 0) + { + n += nread; + }//读到EAGAIN,说明读完了 + + if(nread == -1 && errno != EAGAIN) + { + epoll_ctl_err_show(); + std::cout<<"readline error"<<std::endl; + close(sockfd); //关闭一个文件描述符,那么它会从epoll集合中自动删除 + //描述符关闭后,后面的邋邋邋邋EPOLLOUT设置了,但不起作用了 + events[i].data.fd = -1; + } + + //这里要加上判断,nread为0时,说明客户端已经关闭 + //此时,需要关闭描述符,否则在/proc/id/fd下能看到描述符会一直存在 + char *str = inet_ntoa(clientaddr.sin_addr); + if(nread == 0) + { + close(sockfd); + std::cout << "close from " << str << std::endl; + continue; + } + + std::cout << "read from " << str << ": " << line << std::endl; + + ev.data.fd=sockfd; //设置用于写操作的文件描述符 + ev.events=EPOLLOUT | EPOLLET; //设置用于注测的写操作事件 + epoll_ctl(epfd,EPOLL_CTL_MOD,sockfd,&ev); //修改sockfd上要处理的事件为EPOLLOUT + } + else if(events[i].events & EPOLLOUT) /**写事件**/ + { + sockfd = events[i].data.fd; + //write(sockfd, line, n); orig + + int iRet = socket_send(sockfd, line, strlen(line) + 1); + if(iRet == -1 || iRet != strlen(line) + 1) + { + perror("write error!"); + }/*zxd*/ + + ev.data.fd=sockfd; //设置用于读操作的文件描述符 + ev.events=EPOLLIN | EPOLLET; //设置用于注册的读操作事件 + epoll_ctl(epfd, EPOLL_CTL_MOD, sockfd, &ev); //修改sockfd上要处理的事件为EPOLIN + } + } + } + + return 0; +} diff --git a/pool/shard007/C++/0092325_local_mapper_viewer.cpp b/pool/shard007/C++/0092325_local_mapper_viewer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9aec3fff341a7bc7189235d539036ce013b44843 --- /dev/null +++ b/pool/shard007/C++/0092325_local_mapper_viewer.cpp @@ -0,0 +1,70 @@ +#include "local_mapper_viewer.h" +#include "qevent.h" +#include <cstring> +#include "gl_helpers/opengl_primitives.h" + +namespace fps_mapper{ + using namespace std; + using namespace Eigen; + using namespace GLHelpers; + + LocalMapperViewer::LocalMapperViewer(LocalMapTrigger* t) { + _trigger = t; + _tracker = t->tracker(); + _trigger->setLocalMaps(&nodes); + _trigger->setLocalMapsRelations(&relations); + _modelTainted = true; + _local_map_trajectory = _trigger->nodes(); + } + + void LocalMapperViewer::draw(){ + if (!_tracker->currentModel() || !_tracker->referenceModel() ) + return; + + glPushAttrib(GL_COLOR); + glPushMatrix(); + glMultMatrix( _tracker->globalT() ); + + glPushMatrix(); + glScalef(0.2, 0.2, 0.2); + GLHelpers::drawReferenceSystem(); + glPopMatrix(); + + /// draw the current after applying the epsilon T from aligner + glPushMatrix(); + glMultMatrix(_tracker->aligner().T().inverse() ); + if (_tracker->currentModel()){ + glColor3f(0.3, 0.3, 0.8); + _tracker->currentModel()->draw(); + } + glPopMatrix(); + + glPushMatrix(); + glMultMatrix(_tracker->lastCamera()->offset()); + float pyrH = 0.1; + float pyrW = 0.05; + drawPyramidWireframe(/*pyrH = */ 0.1, /*pyrW = */ 0.05); + glPopMatrix(); + + /// draw the reference + if (_tracker->referenceModel()){ + glColor3f(0.5, 0.5, 0.5); + _tracker->referenceModel()->draw(); + } + + glPopMatrix(); + glPopAttrib(); + + TrajectoryViewer::draw(); + + glPushAttrib(GL_COLOR); + if (_local_map_trajectory) { + for (MapNodeList::iterator it = _local_map_trajectory->begin(); it!=_local_map_trajectory->end(); + it++) + (*it)->draw(); + } + glPopAttrib(); + } + +} + diff --git a/pool/shard007/C++/0092330_editor_application.cpp b/pool/shard007/C++/0092330_editor_application.cpp new file mode 100644 index 0000000000000000000000000000000000000000..263d89788cfa0cd8c76f97c323312a9831a3c443 --- /dev/null +++ b/pool/shard007/C++/0092330_editor_application.cpp @@ -0,0 +1,76 @@ +/* + * Platformer Game Engine by Wohlstand, a free platform for game making + * Copyright (c) 2014-2016 Vitaly Novichkov <admin@wohlnet.ru> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <QFileOpenEvent> +#include <common_features/logger.h> +#include "editor_application.h" + +PGE_OSXApplication::PGE_OSXApplication(int &argc, char **argv) + : QApplication(argc, argv) +{ + #ifdef Q_OS_MACX + m_connected = false; + #endif +} + +PGE_OSXApplication::~PGE_OSXApplication() +{} + +#ifdef Q_OS_MACX +void PGE_OSXApplication::setConnected() +{ + m_connected = true; +} + +bool PGE_OSXApplication::event(QEvent *event) +{ + if(event->type() == QEvent::FileOpen) + { + QFileOpenEvent *openEvent = static_cast<QFileOpenEvent *>(event); + if(openEvent) + { + if(m_connected) + { + QString file = openEvent->file(); + LogDebugQD("Opened file "+file + " (signal)"); + emit openFileRequested( file ); + } + else + { + QString file = openEvent->file(); + LogDebugQD("Opened file "+file + " (queue)"); + m_openFileRequests.enqueue(file); + } + } else { + LogWarningQD("Failed to process openEvent: pointer is null!"); + } + } + return QApplication::event(event); +} + +QStringList PGE_OSXApplication::getOpenFileChain() +{ + QStringList chain; + while(!m_openFileRequests.isEmpty()) + { + QString file = m_openFileRequests.dequeue(); + chain.push_back(file); + } + return chain; +} +#endif //Q_OS_MACX diff --git a/pool/shard007/C++/0092343_NotifyConditionVector.cpp b/pool/shard007/C++/0092343_NotifyConditionVector.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f834b88d7dc3e23c2a6891fbcd4c104ecb53edb4 --- /dev/null +++ b/pool/shard007/C++/0092343_NotifyConditionVector.cpp @@ -0,0 +1,171 @@ +/* +* +* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U +* +* This file is part of Orion Context Broker. +* +* Orion Context Broker is free software: you can redistribute it and/or +* modify it under the terms of the GNU Affero General Public License as +* published by the Free Software Foundation, either version 3 of the +* License, or (at your option) any later version. +* +* Orion Context Broker is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero +* General Public License for more details. +* +* You should have received a copy of the GNU Affero General Public License +* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/. +* +* For those usages not covered by this license please contact with +* iot_support at tid dot es +* +* Author: Ken Zangelin +*/ +#include <stdio.h> +#include <string> +#include <vector> + +#include "logMsg/logMsg.h" +#include "logMsg/traceLevels.h" + +#include "common/globals.h" +#include "common/tag.h" +#include "ngsi/NotifyConditionVector.h" + + + +/* **************************************************************************** +* +* NotifyConditionVector::render - +*/ +std::string NotifyConditionVector::render(Format format, const std::string& indent, bool comma) +{ + std::string out = ""; + std::string tag = "notifyConditions"; + + if (vec.size() == 0) + { + return ""; + } + + out += startTag(indent, tag, tag, format, true, true); + for (unsigned int ix = 0; ix < vec.size(); ++ix) + { + out += vec[ix]->render(format, indent + " ", ix != vec.size() - 1); + } + out += endTag(indent, tag, format, comma, true); + + return out; +} + + + +/* **************************************************************************** +* +* NotifyConditionVector::check - +*/ +std::string NotifyConditionVector::check +( + RequestType requestType, + Format format, + const std::string& indent, + const std::string& predetectedError, + int counter +) +{ + for (unsigned int ix = 0; ix < vec.size(); ++ix) + { + std::string res; + + if ((res = vec[ix]->check(requestType, format, indent, predetectedError, counter)) != "OK") + { + return res; + } + } + + return "OK"; +} + + + +/* **************************************************************************** +* +* NotifyConditionVector::present - +*/ +void NotifyConditionVector::present(const std::string& indent) +{ + LM_T(LmtPresent, ("%s%lu NotifyConditions", + indent.c_str(), + (uint64_t) vec.size())); + + for (unsigned int ix = 0; ix < vec.size(); ++ix) + { + vec[ix]->present(indent, ix); + } +} + + + +/* **************************************************************************** +* +* NotifyConditionVector::push_back - +*/ +void NotifyConditionVector::push_back(NotifyCondition* item) +{ + vec.push_back(item); +} + + + +/* **************************************************************************** +* +* NotifyConditionVector::get - +*/ +NotifyCondition* NotifyConditionVector::get(int ix) +{ + return vec[ix]; +} + + + +/* **************************************************************************** +* +* NotifyConditionVector::size - +*/ +unsigned int NotifyConditionVector::size(void) +{ + return vec.size(); +} + + + +/* **************************************************************************** +* +* NotifyConditionVector::release - +*/ +void NotifyConditionVector::release(void) +{ + for (unsigned int ix = 0; ix < vec.size(); ++ix) + { + vec[ix]->release(); + delete vec[ix]; + } + + vec.clear(); +} + + + +/* **************************************************************************** +* +* NotifyConditionVector::fill - +*/ +void NotifyConditionVector::fill(NotifyConditionVector& nv) +{ + for (unsigned int ncIx = 0; ncIx < nv.size(); ++ncIx) + { + NotifyCondition* ncP = new NotifyCondition(nv[ncIx]); + push_back(ncP); + } +} diff --git a/pool/shard007/C++/0092358_mergeLHEFile.cpp b/pool/shard007/C++/0092358_mergeLHEFile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e0f108e04bc318a052d2e85b360c3f8fc4dc7d6b --- /dev/null +++ b/pool/shard007/C++/0092358_mergeLHEFile.cpp @@ -0,0 +1,69 @@ +// g++ -Wall -o mergeLheFile mergeLheFile.cpp + +#include <iostream> +#include <fstream> + + + +int main(int argc, char** argv) +{ + if(argc != 3) + { + std::cout << ">>>splitLheFile.cpp::Usage: " << argv[0] << " initialFile.lhe fileToAdd.lhe" << std::endl; + return -1; + } + + char* initialFileName = argv[1]; + char* fileToAddName = argv[2]; + + std::cout << "initialFileName = " << initialFileName << std::endl; + std::cout << "fileToAddName = " << fileToAddName << std::endl; + + + + // open lhe file + std::ifstream initialFile(initialFileName, std::ios::in); + std::ifstream fileToAdd(fileToAddName, std::ios::in); + std::ofstream outFile("out.lhe", std::ios::out); + + std::string line; + std::string line2; + bool writeEvent = false; + int eventIt = 0; + + while(!initialFile.eof()) + { + getline(initialFile, line); + + if( line == "</LesHouchesEvents>" ) + { + while(!fileToAdd.eof()) + { + getline(fileToAdd, line2); + + // decide whether to skip event or not + if( line2 == "<event>" ) + { + ++eventIt; + writeEvent = true; + } + + + // write line to outFile + if(writeEvent == true) + outFile << line2 << std::endl; + + + // end of event + if( line2 == "</event>" ) + writeEvent = false; + } + } + + outFile << line << std::endl; + } + + + std::cout << "Added " << eventIt << " events from file " << fileToAddName << " to file " << initialFileName << std::endl; + return 0; +} diff --git a/pool/shard007/C++/0092370_conv2d_op.cc b/pool/shard007/C++/0092370_conv2d_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..0a37d3968c39d2c244bbd82161afddf6330e421d --- /dev/null +++ b/pool/shard007/C++/0092370_conv2d_op.cc @@ -0,0 +1,96 @@ +/* Copyright (c) 2018 PaddlePaddle 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 "paddle/fluid/inference/tensorrt/convert/op_converter.h" + +namespace paddle { +namespace inference { +namespace tensorrt { + +class Conv2dOpConverter : public OpConverter { + public: + void operator()(const framework::proto::OpDesc& op, + const framework::Scope& scope, bool test_mode) override { + LOG(INFO) + << "convert a fluid conv2d op to tensorrt conv layer without bias"; + + framework::OpDesc op_desc(op, nullptr); + PADDLE_ENFORCE_EQ(op_desc.Input("Input").size(), 1); + PADDLE_ENFORCE_EQ(op_desc.Input("Filter").size(), 1); // Y is a weight + PADDLE_ENFORCE_EQ(op_desc.Output("Output").size(), 1); + + auto* X = engine_->GetITensor(op_desc.Input("Input").front()); + // Declare weights + auto* Y_v = scope.FindVar(op_desc.Input("Filter").front()); + PADDLE_ENFORCE_NOT_NULL(Y_v); + auto* Y_t = Y_v->GetMutable<framework::LoDTensor>(); + + platform::CPUPlace cpu_place; + std::unique_ptr<framework::LoDTensor> weight_tensor( + new framework::LoDTensor()); + weight_tensor->Resize(Y_t->dims()); + TensorCopySync((*Y_t), cpu_place, weight_tensor.get()); + + auto* weight_data = + weight_tensor->mutable_data<float>(platform::CPUPlace()); + + PADDLE_ENFORCE_EQ(weight_tensor->dims().size(), 4UL); + const int n_output = weight_tensor->dims()[0]; + const int filter_h = weight_tensor->dims()[2]; + const int filter_w = weight_tensor->dims()[3]; + + const int groups = boost::get<int>(op_desc.GetAttr("groups")); + const std::vector<int> dilations = + boost::get<std::vector<int>>(op_desc.GetAttr("dilations")); + const std::vector<int> strides = + boost::get<std::vector<int>>(op_desc.GetAttr("strides")); + const std::vector<int> paddings = + boost::get<std::vector<int>>(op_desc.GetAttr("paddings")); + + nvinfer1::DimsHW nv_ksize(filter_h, filter_w); + nvinfer1::DimsHW nv_dilations(dilations[0], dilations[1]); + nvinfer1::DimsHW nv_strides(strides[0], strides[1]); + nvinfer1::DimsHW nv_paddings(paddings[0], paddings[1]); + + TensorRTEngine::Weight weight{nvinfer1::DataType::kFLOAT, + static_cast<void*>(weight_data), + weight_tensor->memory_size() / sizeof(float)}; + + TensorRTEngine::Weight bias{nvinfer1::DataType::kFLOAT, nullptr, 0}; + auto* layer = TRT_ENGINE_ADD_LAYER( + engine_, Convolution, *const_cast<nvinfer1::ITensor*>(X), n_output, + nv_ksize, weight.get(), bias.get()); + PADDLE_ENFORCE(layer != nullptr); + layer->setStride(nv_strides); + layer->setPadding(nv_paddings); + layer->setDilation(nv_dilations); + layer->setNbGroups(groups); + + auto output_name = op_desc.Output("Output").front(); + layer->setName(("conv2d (Output: " + output_name + ")").c_str()); + engine_->weight_map[op_desc.Input("Filter").front()] = + std::move(weight_tensor); + layer->getOutput(0)->setName(output_name.c_str()); + engine_->SetITensor(output_name, layer->getOutput(0)); + if (test_mode) { + engine_->DeclareOutput(output_name); + } + } +}; + +} // namespace tensorrt +} // namespace inference +} // namespace paddle + +REGISTER_TRT_OP_CONVERTER(conv2d, Conv2dOpConverter); diff --git a/pool/shard007/C++/0092371_sdd-hierarchy.cc b/pool/shard007/C++/0092371_sdd-hierarchy.cc new file mode 100644 index 0000000000000000000000000000000000000000..c54c5960ed8c25d0c14d3cd318652cc896e06a59 --- /dev/null +++ b/pool/shard007/C++/0092371_sdd-hierarchy.cc @@ -0,0 +1,174 @@ +#include <numeric> +#include <cstdlib> +#include <iostream> +#include <fstream> +#include <string> +#include <vector> +#include <map> +#include <iomanip> +#include <cmath> +#include <algorithm> + +#include "sdd/sdd.hh" +#include "sdd/tools/size.hh" +#include "sdd/tools/nodes.hh" + +using namespace std; + +struct conf + : public sdd::flat_set_default_configuration +{ + using Identifier = unsigned int; + using Values = sdd::values::flat_set<char>; +}; +using SDD = sdd::SDD<conf>; +using values_type = conf::Values; + +static const auto sublength = 35; + +SDD +build (const string& str){ + if (str.size() == sublength) + { + SDD result = sdd::one<conf>(); + for (size_t i = 0; i != str.size(); ++i) + result = SDD(i, { str[str.size() - i - 1] }, result); + return result; + } + else + { + SDD result = sdd::one<conf>(); + const auto subsize = str.size() / sublength; + for (size_t i = 0; i != sublength; ++i) + { + const auto substr = str.substr(subsize * (sublength - i - 1), sublength); + result = SDD(i, build (substr), result); + } + return result; + } +} + +int +main (int argc, const char** argv) +{ + const auto subsize = 1000; + size_t max_size = 1; + size_t max_name = 1; + map<string, size_t> counts; + vector<SDD> collections; + vector<SDD> subcollection; + subcollection.reserve(subsize); + + conf c; + c.final_cleanup = false; // don't cleanup memory on manager scope exit. + c.hom_cache_size = 2; + c.hom_unique_table_size = 2; +// c.sdd_intersection_cache_size = 16000000; +// c.sdd_sum_cache_size = 16000000; +// c.sdd_difference_cache_size = 16000000; + c.sdd_unique_table_size = 10000000; + auto manager = sdd::init<conf>(c); + + if (argc == 0) + { + cerr << "No arguments" << endl; + return 1; + } + + string line; + line.reserve(256); + + const size_t max_length = [&] + { + size_t length = 0; + for (size_t param = 1; param < argc; ++param) + { + const string filename = argv[param]; + max_name = max (max_name, filename.length()); + ifstream dict(filename); + if (dict.is_open()) + { + size_t count = 0; + while (std::getline(dict, line)) + { + count++; + length = length > line.size() ? length : line.size(); + } + counts [filename] = count; + max_size = max (max_size, count > 0 ? (size_t) log10 ((double) count) + 1 : 1); + } + else + { + cerr << "Warning, can't open " << filename << endl; + } + } + return length; + }(); + + cout << "Max word length is " << max_length << endl; + + size_t rounded_length = 1; + while (true) + { + if (rounded_length >= max_length) + break; + else + rounded_length *= sublength; + } + line.reserve(rounded_length + 1); + + + // Construct the SDD order: we need one level per letter. +// vector<unsigned int> v(max_length); +// iota(v.begin(), v.end(), 0); +// sdd::order_builder<conf> ob; +// const sdd::order<conf> order(sdd::order_builder<conf>(v.begin(), v.end())); + + for (size_t param = 1; param < argc; ++param) + { + string filename = argv[param]; + ifstream dict (filename); + if (dict.is_open()) + { + size_t count = 0; + size_t max = counts [filename]; + cout << setw(max_name + 5) << left << filename + << right << "\033[s" + << "\033[u" + << setw(max_size) << count << " / " << setw(max_size) << max + << flush; + while (getline(dict, line)) + { + count++; + line.insert(line.size(), rounded_length - line.size(), ' '); + subcollection.push_back (build (line)); + if (count % subsize == 0) + { + collections.emplace_back(sdd::sum<conf>(subcollection.cbegin(), subcollection.cend())); + subcollection.clear(); + cout << "\033[u" + << setw(max_size) << count << " / " << setw(max_size) << max + << flush; + } + } + collections.emplace_back(sdd::sum<conf>(subcollection.cbegin(), subcollection.cend())); + cout << "\033[u" + << setw(max_size) << count << " / " << setw(max_size) << max + << flush; + } + else + { + cerr << "Warning, can't open " << filename << endl; + } + dict.close(); + cout << endl; + } + const auto collection = sdd::sum<conf>(collections.cbegin(), collections.cend()); + cout << "# Words: " << collection.size() << endl; + cout << "# Nodes: " << sdd::tools::nodes(collection).first + << ", " << sdd::tools::nodes(collection).second + << endl; + cout << "Size: " << sdd::tools::size(collection) << " bytes" << endl; + + return 0; +} diff --git a/pool/shard007/C++/0092373_VCInitBlocks.cpp b/pool/shard007/C++/0092373_VCInitBlocks.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8b107842ee534944f0007fe481f772d154c0e6aa --- /dev/null +++ b/pool/shard007/C++/0092373_VCInitBlocks.cpp @@ -0,0 +1,88 @@ +// Copyright (c) 2010, John B. Rundle <rundle@cse.ucdavis.edu>, +// All rights reserved. +// +// Redistribution and use of this code or any derivative works are +// permitted provided that the following conditions are met: +// +// * Redistributions may not be sold, nor may they be used in a +// commercial product or activity. +// +// * Redistributions that are modified from the original source must +// include the complete source code, including the source code for all +// components used by a binary built from the modified +// sources. However, as a special exception, the source code +// distributed need not include anything that is normally distributed +// (in either source or binary form) with the major components +// (compiler, kernel, and so on) of the operating system on which the +// executable runs, unless that component itself accompanies the +// executable. +// +// * Redistributions 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. +// +// 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 "VCInitBlocks.h" +#include "SimError.h" + +void VCInitBlocks::initDesc(const SimFramework *_sim) const { + const VCSimulation *sim = static_cast<const VCSimulation*>(_sim); + + sim->console() << "# Initializing blocks." << std::endl; +} + +/*! + Set up the dry run for parallel systems by partitioning + the blocks and creating MPI related data types. + */ +void VCInitBlocks::dryRun(SimFramework *_sim) { + VCSimulation *sim = static_cast<VCSimulation*>(_sim); + sim->partitionBlocks(); +} + +/*! + Initialize the simulation by partitioning the model, allocating the necessary memory, + setting value pointers and creating the needed MPI data types. + */ +void VCInitBlocks::init(SimFramework *_sim) { + VCSimulation *sim = static_cast<VCSimulation*>(_sim); + int i; + BlockList::iterator bit; + + assertThrow(sim->numGlobalBlocks() > 0, "Simulation must include at least 1 block."); + + sim->partitionBlocks(); + + // Initialize simulation arrays and classes + sim->setupArrays(sim->numGlobalBlocks(), + sim->numLocalBlocks(), + // use compressed array for Barnes Hut style Greens function calculations + sim->getGreensCalcMethod()==GREENS_CALC_BARNES_HUT, + // transposed array for faster sweep calculations + sim->useTransposedMatrix()); + + // Set the block pointers to the storage arrays + for (i=0,bit=sim->begin();bit!=sim->end();++bit,++i) + bit->setStatePtrs(sim->getShearStressPtr(i), + sim->getNormalStressPtr(i), + sim->getFShearStressPtr(i), + sim->getFNormalStressPtr(i), + sim->getUpdateFieldPtr(i)); + + // Set the starting year of the simulation + sim->setYear(sim->getSimStart()); + + // Determine neighbors of blocks + sim->determineBlockNeighbors(); +} diff --git a/pool/shard007/C++/0092375_gpu_allocator_retry_test.cc b/pool/shard007/C++/0092375_gpu_allocator_retry_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..777f578277651ef9116e0d8552ff18313ba49999 --- /dev/null +++ b/pool/shard007/C++/0092375_gpu_allocator_retry_test.cc @@ -0,0 +1,194 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "tensorflow/core/common_runtime/allocator_retry.h" + +#include <vector> +#include "tensorflow/core/lib/core/notification.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/test.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +class FakeAllocator { + public: + FakeAllocator(size_t cap, int millis_to_wait) + : memory_capacity_(cap), millis_to_wait_(millis_to_wait) {} + + // Allocate just keeps track of the number of outstanding allocations, + // not their sizes. Assume a constant size for each. + void* AllocateRaw(size_t alignment, size_t num_bytes) { + return retry_.AllocateRaw( + [this](size_t a, size_t nb, bool v) { + mutex_lock l(mu_); + if (memory_capacity_ > 0) { + --memory_capacity_; + return good_ptr_; + } else { + return static_cast<void*>(nullptr); + } + }, + millis_to_wait_, alignment, num_bytes); + } + + void DeallocateRaw(void* ptr) { + mutex_lock l(mu_); + ++memory_capacity_; + retry_.NotifyDealloc(); + } + + private: + AllocatorRetry retry_; + void* good_ptr_ = reinterpret_cast<void*>(0xdeadbeef); + mutex mu_; + size_t memory_capacity_ GUARDED_BY(mu_); + int millis_to_wait_; +}; + +class GPUAllocatorRetryTest : public ::testing::Test { + protected: + GPUAllocatorRetryTest() {} + + void LaunchConsumerThreads(int num_consumers, int cap_needed) { + consumer_count_.resize(num_consumers, 0); + for (int i = 0; i < num_consumers; ++i) { + consumers_.push_back(Env::Default()->StartThread( + ThreadOptions(), "anon_thread", [this, i, cap_needed]() { + do { + void* ptr = nullptr; + for (int j = 0; j < cap_needed; ++j) { + ptr = alloc_->AllocateRaw(16, 1); + if (ptr == nullptr) { + mutex_lock l(mu_); + has_failed_ = true; + return; + } + } + // Failures are more likely to occur if each consumer + // delays for a while before returning the memory. + Env::Default()->SleepForMicroseconds(500); + ++consumer_count_[i]; + for (int j = 0; j < cap_needed; ++j) { + alloc_->DeallocateRaw(ptr); + } + } while (!notifier_.HasBeenNotified()); + })); + } + } + + // Wait up to wait_micros microseconds for has_failed_ to equal expected, + // then terminate all threads. + void JoinConsumerThreads(bool expected, int wait_micros) { + while (wait_micros > 0) { + { + mutex_lock l(mu_); + if (has_failed_ == expected) break; + } + int interval_micros = std::min(1000, wait_micros); + Env::Default()->SleepForMicroseconds(interval_micros); + wait_micros -= interval_micros; + } + notifier_.Notify(); + for (auto c : consumers_) { + // Blocks until thread terminates. + delete c; + } + } + + std::unique_ptr<FakeAllocator> alloc_; + std::vector<Thread*> consumers_; + std::vector<int> consumer_count_; + Notification notifier_; + mutex mu_; + bool has_failed_ GUARDED_BY(mu_) = false; + int count_ GUARDED_BY(mu_) = 0; +}; + +// Verifies correct retrying when memory is slightly overcommitted but +// we allow retry. +TEST_F(GPUAllocatorRetryTest, RetrySuccess) { + // Support up to 2 allocations simultaneously, waits up to 10 msec for + // a chance to alloc. + alloc_.reset(new FakeAllocator(2, 10000)); + // Launch 3 consumers, each of whom needs 1 unit at a time. + LaunchConsumerThreads(3, 1); + // This should be enough time for each consumer to be satisfied many times. + Env::Default()->SleepForMicroseconds(50000); + JoinConsumerThreads(false, 0); + for (int i = 0; i < 3; ++i) { + LOG(INFO) << "Consumer " << i << " is " << consumer_count_[i]; + } + { + mutex_lock l(mu_); + EXPECT_FALSE(has_failed_); + } + EXPECT_GT(consumer_count_[0], 0); + EXPECT_GT(consumer_count_[1], 0); + EXPECT_GT(consumer_count_[2], 0); +} + +// Verifies OutOfMemory failure when memory is slightly overcommitted +// and retry is not allowed. Note that this test will fail, i.e. no +// memory alloc failure will be detected, if it is run in a context that +// does not permit real multi-threaded execution. +TEST_F(GPUAllocatorRetryTest, NoRetryFail) { + // Support up to 2 allocations simultaneously, waits up to 0 msec for + // a chance to alloc. + alloc_.reset(new FakeAllocator(2, 0)); + // Launch 3 consumers, each of whom needs 1 unit at a time. + LaunchConsumerThreads(3, 1); + Env::Default()->SleepForMicroseconds(50000); + // Will wait up to 10 seconds for proper race condition to occur, resulting + // in failure. + JoinConsumerThreads(true, 10000000); + for (int i = 0; i < 3; ++i) { + LOG(INFO) << "Consumer " << i << " is " << consumer_count_[i]; + } + { + mutex_lock l(mu_); + EXPECT_TRUE(has_failed_); + } +} + +// Verifies OutOfMemory failure when retry is allowed but memory capacity +// is too low even for retry. +TEST_F(GPUAllocatorRetryTest, RetryInsufficientFail) { + // Support up to 2 allocations simultaneously, waits up to 10 msec for + // a chance to alloc. + alloc_.reset(new FakeAllocator(2, 10000)); + // Launch 3 consumers, each of whom needs 2 units at a time. We expect + // deadlock where 2 consumers each hold 1 unit, and timeout trying to + // get the second. + LaunchConsumerThreads(3, 2); + Env::Default()->SleepForMicroseconds(50000); + // Will wait up to 10 seconds for proper race condition to occur, resulting + // in failure. + JoinConsumerThreads(true, 10000000); + for (int i = 0; i < 3; ++i) { + LOG(INFO) << "Consumer " << i << " is " << consumer_count_[i]; + } + { + mutex_lock l(mu_); + EXPECT_TRUE(has_failed_); + } +} + +} // namespace +} // namespace tensorflow diff --git a/pool/shard007/C++/0092384_aes_kw_openssl.cc b/pool/shard007/C++/0092384_aes_kw_openssl.cc new file mode 100644 index 0000000000000000000000000000000000000000..247ba0058aeb82b396c7b2bed2180ea59ca9ed38 --- /dev/null +++ b/pool/shard007/C++/0092384_aes_kw_openssl.cc @@ -0,0 +1,92 @@ +// 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 <vector> +#include <openssl/evp.h> + +#include "base/logging.h" +#include "base/numerics/safe_math.h" +#include "base/stl_util.h" +#include "content/child/webcrypto/crypto_data.h" +#include "content/child/webcrypto/openssl/aes_algorithm_openssl.h" +#include "content/child/webcrypto/openssl/key_openssl.h" +#include "content/child/webcrypto/openssl/util_openssl.h" +#include "content/child/webcrypto/status.h" +#include "crypto/openssl_util.h" +#include "crypto/scoped_openssl_types.h" + +namespace content { + +namespace webcrypto { + +namespace { + +const EVP_AEAD* GetAesKwAlgorithmFromKeySize(unsigned int key_size_bytes) { + switch (key_size_bytes) { + case 16: + return EVP_aead_aes_128_key_wrap(); + case 32: + return EVP_aead_aes_256_key_wrap(); + default: + return NULL; + } +} + +Status AesKwEncryptDecrypt(EncryptOrDecrypt mode, + const blink::WebCryptoAlgorithm& algorithm, + const blink::WebCryptoKey& key, + const CryptoData& data, + std::vector<uint8_t>* buffer) { + // These length checks are done so the returned error matches that of NSS + // implementation. Other than giving a more specific error, these are not + // required. + if ((mode == ENCRYPT && data.byte_length() < 16) || + (mode == DECRYPT && data.byte_length() < 24)) { + return Status::ErrorDataTooSmall(); + } + if (data.byte_length() % 8) + return Status::ErrorInvalidAesKwDataLength(); + + const std::vector<uint8_t>& raw_key = + SymKeyOpenSsl::Cast(key)->raw_key_data(); + + return AeadEncryptDecrypt(mode, raw_key, data, + 8, // tag_length_bytes + CryptoData(), // iv + CryptoData(), // additional_data + GetAesKwAlgorithmFromKeySize(raw_key.size()), + buffer); +} + +class AesKwImplementation : public AesAlgorithm { + public: + AesKwImplementation() + : AesAlgorithm( + blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey, + "KW") {} + + Status Encrypt(const blink::WebCryptoAlgorithm& algorithm, + const blink::WebCryptoKey& key, + const CryptoData& data, + std::vector<uint8_t>* buffer) const override { + return AesKwEncryptDecrypt(ENCRYPT, algorithm, key, data, buffer); + } + + Status Decrypt(const blink::WebCryptoAlgorithm& algorithm, + const blink::WebCryptoKey& key, + const CryptoData& data, + std::vector<uint8_t>* buffer) const override { + return AesKwEncryptDecrypt(DECRYPT, algorithm, key, data, buffer); + } +}; + +} // namespace + +AlgorithmImplementation* CreatePlatformAesKwImplementation() { + return new AesKwImplementation; +} + +} // namespace webcrypto + +} // namespace content diff --git a/pool/shard007/C++/0092394_rfnoc_ddc_python.cc b/pool/shard007/C++/0092394_rfnoc_ddc_python.cc new file mode 100644 index 0000000000000000000000000000000000000000..525b8c04db0f47e0feb9f072e9465c9431f302d8 --- /dev/null +++ b/pool/shard007/C++/0092394_rfnoc_ddc_python.cc @@ -0,0 +1,65 @@ +/* + * Copyright 2021 Free Software Foundation, Inc. + * + * This file is part of GNU Radio + * + * SPDX-License-Identifier: GPL-3.0-or-later + * + */ + +/***********************************************************************************/ +/* This file is automatically generated using bindtool and can be manually edited */ +/* The following lines can be configured to regenerate this file during cmake */ +/* If manual edits are made, the following tags should be modified accordingly. */ +/* BINDTOOL_GEN_AUTOMATIC(0) */ +/* BINDTOOL_USE_PYGCCXML(0) */ +/* BINDTOOL_HEADER_FILE(rfnoc_ddc.h) */ +/* BINDTOOL_HEADER_FILE_HASH(0b41834dd8deb06ad7cbca294130abb3) */ +/***********************************************************************************/ + +#include <pybind11/complex.h> +#include <pybind11/pybind11.h> +#include <pybind11/stl.h> + +namespace py = pybind11; + +#include <gnuradio/uhd/rfnoc_ddc.h> +// pydoc.h is automatically generated in the build directory +#include <rfnoc_ddc_pydoc.h> + +void bind_rfnoc_ddc(py::module& m) +{ + + using rfnoc_ddc = ::gr::uhd::rfnoc_ddc; + + + py::class_<rfnoc_ddc, + gr::uhd::rfnoc_block, + gr::block, + gr::basic_block, + std::shared_ptr<rfnoc_ddc>>(m, "rfnoc_ddc", D(rfnoc_ddc)) + + .def(py::init(&rfnoc_ddc::make), + py::arg("graph"), + py::arg("block_args"), + py::arg("device_select"), + py::arg("instance"), + D(rfnoc_ddc, make)) + + + .def("set_freq", + &rfnoc_ddc::set_freq, + py::arg("freq"), + py::arg("chan"), + py::arg("time") = uhd::time_spec_t::ASAP, + D(rfnoc_ddc, set_freq)) + + + .def("set_output_rate", + &rfnoc_ddc::set_output_rate, + py::arg("rate"), + py::arg("chan"), + D(rfnoc_ddc, set_output_rate)) + + ; +} diff --git a/pool/shard007/C++/0092404_GetInstancesResult.cpp b/pool/shard007/C++/0092404_GetInstancesResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ade8b971b5af033f0f5bdbefd692f367eb0b12a4 --- /dev/null +++ b/pool/shard007/C++/0092404_GetInstancesResult.cpp @@ -0,0 +1,59 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include <aws/lightsail/model/GetInstancesResult.h> +#include <aws/core/utils/json/JsonSerializer.h> +#include <aws/core/AmazonWebServiceResult.h> +#include <aws/core/utils/StringUtils.h> +#include <aws/core/utils/UnreferencedParam.h> + +#include <utility> + +using namespace Aws::Lightsail::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +GetInstancesResult::GetInstancesResult() +{ +} + +GetInstancesResult::GetInstancesResult(const Aws::AmazonWebServiceResult<JsonValue>& result) +{ + *this = result; +} + +GetInstancesResult& GetInstancesResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) +{ + JsonView jsonValue = result.GetPayload().View(); + if(jsonValue.ValueExists("instances")) + { + Array<JsonView> instancesJsonList = jsonValue.GetArray("instances"); + for(unsigned instancesIndex = 0; instancesIndex < instancesJsonList.GetLength(); ++instancesIndex) + { + m_instances.push_back(instancesJsonList[instancesIndex].AsObject()); + } + } + + if(jsonValue.ValueExists("nextPageToken")) + { + m_nextPageToken = jsonValue.GetString("nextPageToken"); + + } + + + + return *this; +} diff --git a/pool/shard007/C++/0092413_1-io.cc b/pool/shard007/C++/0092413_1-io.cc new file mode 100644 index 0000000000000000000000000000000000000000..9711d21162a013e4fe0e7c8cc281576951253884 --- /dev/null +++ b/pool/shard007/C++/0092413_1-io.cc @@ -0,0 +1,71 @@ +// 2001-05-21 Benjamin Kosnik <bkoz@redhat.com> + +// Copyright (C) 2001, 2002, 2003 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 2, or (at your option) +// any later version. + +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING. If not, write to the Free +// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, +// USA. + +// 27.8.1.4 Overridden virtual functions + +// { dg-require-fileio "" } + +#include <fstream> +#include <testsuite_hooks.h> +#include <testsuite_io.h> + +// @require@ %-*.tst %-*.txt +// @diff@ %-*.tst %*.txt + +const char name_01[] = "filebuf_virtuals-1.txt"; // file with data in it +const char name_03[] = "tmp_sputn_1io.tst"; // empty file, need to create + +void test05() +{ + using namespace std; + using namespace __gnu_test; + + typedef filebuf::int_type int_type; + typedef filebuf::traits_type traits_type; + typedef size_t size_type; + + bool test __attribute__((unused)) = true; + streamsize strmsz_1, strmsz_2; + + // streamsize sputn(const char_typs* s, streamsize n) + // write up to n chars to out_cur from s, returning number assigned + // NB *sputn will happily put '\0' into your stream if you give it a chance* + + // in | out + { + constraint_filebuf fb_03; + fb_03.open(name_03, ios_base::out | ios_base::in | ios_base::trunc); + VERIFY( !fb_03.write_position() ); + VERIFY( !fb_03.read_position() ); + strmsz_1 = fb_03.sputn("racadabras", 10);//"abracadabras or what?" + VERIFY( strmsz_1 == 10 ); + strmsz_2 = fb_03.sputn(", i wanna reach out and", 10); + VERIFY( strmsz_2 == 10 ); + VERIFY( strmsz_1 == strmsz_2 ); + VERIFY( fb_03.write_position() ); + VERIFY( !fb_03.read_position() ); + } +} + +int main() +{ + test05(); + return 0; +} diff --git a/pool/shard007/C++/0092423_dump.cpp b/pool/shard007/C++/0092423_dump.cpp new file mode 100644 index 0000000000000000000000000000000000000000..decb448f69bda011a7b104d1ffbae7e438c72837 --- /dev/null +++ b/pool/shard007/C++/0092423_dump.cpp @@ -0,0 +1,45 @@ +#define SOL_ALL_SAFETIES_ON 1 +#include <sol/sol.hpp> + +#include <iostream> + + +int main() { + std::cout << "=== dump (serialize between states) ===" + << std::endl; + + // 2 states, transferring function from 1 to another + sol::state lua; + sol::state lua2; + + // we're not going to run the code on the first + // state, so we only actually need + // the base lib on the second state + // (where we will run the serialized bytecode) + lua2.open_libraries(sol::lib::base); + + // load this code (but do not run) + sol::load_result lr + = lua.load("a = function (v) print(v) return v end"); + // check if it's sucessfully loaded + sol_c_assert(lr.valid()); + + // turn it into a function, then dump the bytecode + sol::protected_function target + = lr.get<sol::protected_function>(); + sol::bytecode target_bc = target.dump(); + + // reload the byte code + // in the SECOND state + auto result2 = lua2.safe_script( + target_bc.as_string_view(), sol::script_pass_on_error); + // check if it was done properly + sol_c_assert(result2.valid()); + + // check in the second state if it was valid + sol::protected_function pf = lua2["a"]; + int v = pf(25557); + sol_c_assert(v == 25557); + + return 0; +} \ No newline at end of file diff --git a/pool/shard007/C++/0092424_WRSK_UltrasonicSensor.cpp b/pool/shard007/C++/0092424_WRSK_UltrasonicSensor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ff1e39b55e9c7771befccec979d8a8d740834ebb --- /dev/null +++ b/pool/shard007/C++/0092424_WRSK_UltrasonicSensor.cpp @@ -0,0 +1,111 @@ +#if defined(ARDUINO) && ARDUINO >= 100 +#include "Arduino.h" +#else +#include "WProgram.h" +#endif + + +#include "WRSK_UltrasonicSensor.h" + +WRSK_UltrasonicSensor::WRSK_UltrasonicSensor(int _echoPin, int _triggerPin) +{ + this->echoPin = _echoPin; + this->triggerPin = _triggerPin; + this->dbgLevel = 0; + initUltrasonicSensor(); +} + +WRSK_UltrasonicSensor::WRSK_UltrasonicSensor(int _echoPin, int _triggerPin, int _dbgLevel) +{ + this->echoPin = _echoPin; + this->triggerPin = _triggerPin; + this->dbgLevel = _dbgLevel; + initUltrasonicSensor(); +} + +float WRSK_UltrasonicSensor::read(void) +{ + return readcm(); +} + +float WRSK_UltrasonicSensor::readcm(void) +{ + int pulsein; + float distance; + + pulsein = readRAW(); + distance = microsecondsToCentimeters(pulsein); + if (distance < 4 && distance > 60) + { + distance = -1; + } + if (this->dbgLevel > 1) + { + Serial.print("Distance: "); + Serial.print(distance, DEC); + Serial.println(" cm"); + } + return distance; +} + +float WRSK_UltrasonicSensor::readinch(void) +{ + int pulsein; + float distance; + + pulsein = readRAW(); + distance = microsecondsToInches(pulsein); + if (distance < 2 && distance > 24) + { + distance = -1; + } + if (this->dbgLevel > 1) + { + Serial.print("Distance: "); + Serial.print(distance, DEC); + Serial.println(" in"); + } + return distance; +} + + +int WRSK_UltrasonicSensor::readRAW(void) +{ + int pulsein; + // The HC-SR04 is triggered by a HIGH pulse of 10 or more microseconds. + digitalWrite(this->triggerPin, HIGH); + delayMicroseconds(10); + digitalWrite(this->triggerPin, LOW); + + // The same pin is used to read the signal from the HC-SR04 a HIGH + // pulse whose duration is the time (in microseconds) from the sending + // of the ping to the reception of its echo off of an object. + pulsein = pulseIn(this->echoPin, HIGH); + return pulsein; +} + +void WRSK_UltrasonicSensor::initUltrasonicSensor(void) +{ + pinMode(this->triggerPin, OUTPUT); + pinMode(this->echoPin, INPUT); + digitalWrite(this->triggerPin, LOW); +} + +float WRSK_UltrasonicSensor::microsecondsToInches(int microseconds) +{ + // According to Parallax's datasheet for the PING))), there are + // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per + // second). This gives the distance travelled by the ping, outbound + // and return, so we divide by 2 to get the distance of the obstacle. + return microseconds / 74.0 / 2.0; +} + +float WRSK_UltrasonicSensor::microsecondsToCentimeters(int microseconds) +{ + // The speed of sound is 340 m/s or 29 microseconds per centimeter. + // The ping travels out and back, so to find the distance of the + // object we take half of the distance travelled. + return microseconds / 29.0 / 2.0; +} + + diff --git a/pool/shard007/C++/0092443_browser_cdm_cast.cc b/pool/shard007/C++/0092443_browser_cdm_cast.cc new file mode 100644 index 0000000000000000000000000000000000000000..8db9563d31692f5e819a2291f29916da45a0e8e5 --- /dev/null +++ b/pool/shard007/C++/0092443_browser_cdm_cast.cc @@ -0,0 +1,116 @@ +// 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 "chromecast/media/cdm/browser_cdm_cast.h" + +#include "media/base/cdm_key_information.h" + +namespace chromecast { +namespace media { + +BrowserCdmCast::BrowserCdmCast() + : next_registration_id_(0) { +} + +BrowserCdmCast::~BrowserCdmCast() { + base::AutoLock auto_lock(callback_lock_); + for (std::map<uint32_t, base::Closure>::const_iterator it = + cdm_unset_callbacks_.begin(); it != cdm_unset_callbacks_.end(); ++it) { + it->second.Run(); + } +} + +void BrowserCdmCast::SetCallbacks( + const ::media::SessionMessageCB& session_message_cb, + const ::media::SessionClosedCB& session_closed_cb, + const ::media::SessionErrorCB& session_error_cb, + const ::media::SessionKeysChangeCB& session_keys_change_cb, + const ::media::SessionExpirationUpdateCB& session_expiration_update_cb) { + session_message_cb_ = session_message_cb; + session_closed_cb_ = session_closed_cb; + session_error_cb_ = session_error_cb; + session_keys_change_cb_ = session_keys_change_cb; + session_expiration_update_cb_ = session_expiration_update_cb; +} + +int BrowserCdmCast::RegisterPlayer(const base::Closure& new_key_cb, + const base::Closure& cdm_unset_cb) { + int registration_id = next_registration_id_++; + DCHECK(!new_key_cb.is_null()); + DCHECK(!cdm_unset_cb.is_null()); + { + base::AutoLock auto_lock(callback_lock_); + DCHECK(!ContainsKey(new_key_callbacks_, registration_id)); + DCHECK(!ContainsKey(cdm_unset_callbacks_, registration_id)); + new_key_callbacks_[registration_id] = new_key_cb; + cdm_unset_callbacks_[registration_id] = cdm_unset_cb; + } + return registration_id; +} + +void BrowserCdmCast::UnregisterPlayer(int registration_id) { + base::AutoLock auto_lock(callback_lock_); + DCHECK(ContainsKey(new_key_callbacks_, registration_id)); + DCHECK(ContainsKey(cdm_unset_callbacks_, registration_id)); + new_key_callbacks_.erase(registration_id); + cdm_unset_callbacks_.erase(registration_id); +} + +void BrowserCdmCast::LoadSession( + ::media::MediaKeys::SessionType session_type, + const std::string& session_id, + scoped_ptr<::media::NewSessionCdmPromise> promise) { + NOTREACHED() << "LoadSession not supported"; + session_error_cb_.Run(session_id, + ::media::MediaKeys::Exception::NOT_SUPPORTED_ERROR, + 0, + std::string()); +} + +::media::CdmContext* BrowserCdmCast::GetCdmContext() { + NOTREACHED(); + return nullptr; +} + +void BrowserCdmCast::OnSessionMessage(const std::string& session_id, + const std::vector<uint8>& message, + const GURL& destination_url) { + // Note: Message type is not supported in Chromecast. Do our best guess here. + ::media::MediaKeys::MessageType message_type = + destination_url.is_empty() ? ::media::MediaKeys::LICENSE_REQUEST + : ::media::MediaKeys::LICENSE_RENEWAL; + session_message_cb_.Run(session_id, + message_type, + message, + destination_url); +} + +void BrowserCdmCast::OnSessionClosed(const std::string& session_id) { + session_closed_cb_.Run(session_id); +} + +void BrowserCdmCast::OnSessionKeysChange( + const std::string& session_id, + const ::media::KeyIdAndKeyPairs& keys) { + ::media::CdmKeysInfo cdm_keys_info; + for (const std::pair<std::string, std::string>& key : keys) { + scoped_ptr< ::media::CdmKeyInformation> cdm_key_information( + new ::media::CdmKeyInformation()); + cdm_key_information->key_id.assign(key.first.begin(), key.first.end()); + cdm_keys_info.push_back(cdm_key_information.release()); + } + session_keys_change_cb_.Run(session_id, true, cdm_keys_info.Pass()); + + // Notify listeners of a new key. + { + base::AutoLock auto_lock(callback_lock_); + for (std::map<uint32_t, base::Closure>::const_iterator it = + new_key_callbacks_.begin(); it != new_key_callbacks_.end(); ++it) { + it->second.Run(); + } + } +} + +} // namespace media +} // namespace chromecast diff --git a/pool/shard007/C++/0092445_my_app.cpp b/pool/shard007/C++/0092445_my_app.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7c2aae2b9ff2f0b22c20049eeb26f410a960f6b6 --- /dev/null +++ b/pool/shard007/C++/0092445_my_app.cpp @@ -0,0 +1,69 @@ +#include <seqan/sequence.h> +#include <seqan/basic.h> +#include <iostream> +using namespace seqan; + +template <typename TAlphabet> +void showAllLetterOfMyAlphabet(TAlphabet const &) +{ + typedef typename Size<TAlphabet>::Type TSize; + TSize alphSize = ValueSize<TAlphabet>::VALUE; + for (TSize i = 0; i < alphSize; ++i) + std::cout << i << ',' << TAlphabet(i) << " "; + std::cout << std::endl; +} + +//template <typename String> class <CharString, DnaString, Peptide> +template <typename TString> +void countOneMers(TString const sequence) +{ + typedef typename Size<TString>::Type TSize; + typedef typename Value<TString>::Type TAlphabet; + + typedef String<TSize> TCounterString; + TSize alphSize = ValueSize<TAlphabet>::Type; + TCounterString table; + resize(table, alphSize,0); + + typedef typename Iterator<TCounterString>::Type TCountIter; + TCounterIter countIt = begin(table); + TCounterIter countItEnd = end(table); + for(TSize pos=0; countIt != countItEnd; ++countIt, ++pos) + { + if(value(countIt > 0) + { + std::cout <<TAlphabet(pos) << ':' << value(countIt) << std::endl; + } + } + +} + + +int main() +{ + countOneMers("mississipi"); + + typedef String<AminoAcid> TAminoAcidString; + TAminoAcidString str = "MQDRVKRPMNAFIVWSRDQRRKMALEN"; + Iterator<String<AminoAcid> >::Type it = begin(str); + Iterator<String<AminoAcid> >::Type itEnd = end(str); + +// std::cout << str; + while(it != itEnd) + { + if(value(it) == 'R') + { + std::cout<< 'A'; + } else { + std::cout << *it; + } + ++it; + + } + + + showAllLetterOfMyAlphabet(AminoAcid()); + showAllLetterOfMyAlphabet(Dna()); + showAllLetterOfMyAlphabet(Dna5()); + return 0; +} \ No newline at end of file diff --git a/pool/shard007/C++/0092446_ToolButton.cpp b/pool/shard007/C++/0092446_ToolButton.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f682d238485fb60f0b536e0125613c424c16dbe --- /dev/null +++ b/pool/shard007/C++/0092446_ToolButton.cpp @@ -0,0 +1,94 @@ +#include "ToolButton.h" +#include "gui/interface/Keys.h" + +ToolButton::ToolButton(ui::Point position, ui::Point size, std::string text_, std::string toolTip): + ui::Button(position, size, text_, toolTip) +{ + SetSelectionState(-1); + Appearance.BorderActive = ui::Colour(255, 0, 255); +} + +void ToolButton::OnMouseClick(int x, int y, unsigned int button) +{ + isButtonDown = true; +} + +void ToolButton::OnMouseUnclick(int x, int y, unsigned int button) +{ + if(isButtonDown) + { + isButtonDown = false; + if(button == BUTTON_LEFT) + SetSelectionState(0); + if(button == BUTTON_RIGHT) + SetSelectionState(1); + if(button == BUTTON_MIDDLE) + SetSelectionState(2); + DoAction(); + } +} + +void ToolButton::Draw(const ui::Point& screenPos) +{ + Graphics * g = ui::Engine::Ref().g; + int totalColour = Appearance.BackgroundInactive.Blue + (3*Appearance.BackgroundInactive.Green) + (2*Appearance.BackgroundInactive.Red); + + if (Appearance.GetTexture()) + { + g->draw_image(Appearance.GetTexture(), screenPos.X+2, screenPos.Y+2, 255); + } + else + { + g->fillrect(screenPos.X+2, screenPos.Y+2, Size.X-4, Size.Y-4, Appearance.BackgroundInactive.Red, Appearance.BackgroundInactive.Green, Appearance.BackgroundInactive.Blue, Appearance.BackgroundInactive.Alpha); + } + + if (isMouseInside && currentSelection == -1) + { + g->drawrect(screenPos.X, screenPos.Y, Size.X, Size.Y, Appearance.BorderActive.Red, Appearance.BorderActive.Green, Appearance.BorderActive.Blue, Appearance.BorderActive.Alpha); + } + else + { + g->drawrect(screenPos.X, screenPos.Y, Size.X, Size.Y, Appearance.BorderInactive.Red, Appearance.BorderInactive.Green, Appearance.BorderInactive.Blue, Appearance.BorderInactive.Alpha); + } + + if (totalColour<544) + { + g->drawtext(screenPos.X+textPosition.X, screenPos.Y+textPosition.Y, buttonDisplayText.c_str(), 255, 255, 255, 255); + } + else + { + g->drawtext(screenPos.X+textPosition.X, screenPos.Y+textPosition.Y, buttonDisplayText.c_str(), 0, 0, 0, 255); + } +} + +void ToolButton::SetSelectionState(int state) +{ + currentSelection = state; + switch(state) + { + case 0: + Appearance.BorderInactive = ui::Colour(255, 0, 255); + break; + case 1: + Appearance.BorderInactive = ui::Colour(240, 240, 100); + break; + case 2: + Appearance.BorderInactive = ui::Colour(0, 255, 0); + break; + case 3: + Appearance.BorderInactive = ui::Colour(0, 255, 255); + break; + default: + Appearance.BorderInactive = ui::Colour(0, 0, 0); + break; + } +} + +int ToolButton::GetSelectionState() +{ + return currentSelection; +} + +ToolButton::~ToolButton() { +} + diff --git a/pool/shard007/C++/0092448_ExmplSurfHeightMap.cpp b/pool/shard007/C++/0092448_ExmplSurfHeightMap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a5a6de7126f6eff389b7f6e9c6c6dbd4d639b8a2 --- /dev/null +++ b/pool/shard007/C++/0092448_ExmplSurfHeightMap.cpp @@ -0,0 +1,196 @@ +/** + * Copyright (C) 2012 + * Ekaterina Potapova + * Automation and Control Institute + * Vienna University of Technology + * Gusshausstraße 25-29 + * 1040 Vienna, Austria + * potapova(at)acin.tuwien.ac.at + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see http://www.gnu.org/licenses/ + */ + + +#include "v4r/attention_segmentation/AttentionExampleUtils.h" + +#include <opencv2/opencv.hpp> + +#include "v4r/attention_segmentation/AttentionModule.h" +#include "v4r/attention_segmentation/AttentionExampleUtils.h" + +// This program shows the use of Surface Height Saliency Map on one image +void printUsage(const char *argv0); + +void printUsage(const char *argv0) +{ + printf( + "Calculates Surface Height Map\n" + "usage: %s image.png cloud.pcd type pyramid_type combination_type normalization_type result.png\n" + " image.png ... color image\n" + " cloud.pcd ... point cloud\n" + " type ... 0 -- distance map; 1 -- tall map; 2 -- short map\n" + " pyramid_type ... 0 -- no pyramid; 1 -- simple pyramid; 2 -- Itti pyramid; 3 -- Frintrop pyramid\n" + " combination_type ... 0 -- SUM; 1 -- MUL; 2 -- MAX\n" + " normalization_type ... 0 -- LIN; 1 -- NMS; 2 -- NLM\n" + " result.png ... output file name\n", argv0); + printf(" Example: %s image.png cloud.pcd 0 0 0 0\n",argv0); +} + +int main(int argc, char** argv) +{ + if(argc != 8) + { + printUsage(argv[0]); + return(0); + } + + // read image + std::string image_name(argv[1]); + cv::Mat image = cv::imread(image_name,-1); + + pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZRGB>()); + std::string cloud_name(argv[2]); + if (pcl::io::loadPCDFile<pcl::PointXYZRGB> (cloud_name,*cloud) == -1) + { + printf("[ERROR]: Couldn't read point cloud.\n"); + return -1; + } + cloud->width = image.cols; + cloud->height = image.rows; + + int type = atoi(argv[3]); + int pyramid_type = atoi(argv[4]); + int combination_type = atoi(argv[5]); + int normalization_type = atoi(argv[6]); + + std::string output_name(argv[7]); + + pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients()); + pcl::PointCloud<pcl::Normal>::Ptr normals(new pcl::PointCloud<pcl::Normal>()); + pcl::PointIndices::Ptr object_indices_in_the_hull(new pcl::PointIndices()); + v4r::preparePointCloud(cloud,coefficients,normals,object_indices_in_the_hull); + + // start creating parameters + v4r::SurfaceHeightSaliencyMap surfaceHeightSaliencyMap; + surfaceHeightSaliencyMap.setWidth(image.cols); + surfaceHeightSaliencyMap.setHeight(image.rows); + surfaceHeightSaliencyMap.setCloud(cloud); + surfaceHeightSaliencyMap.setIndices(object_indices_in_the_hull); + surfaceHeightSaliencyMap.setNormals(normals); + surfaceHeightSaliencyMap.setModelCoefficients(coefficients); + + printf("Saliency Map Type: "); + switch(type) + { + case(0): + printf("DISTANCE MAP \n"); + surfaceHeightSaliencyMap.setHeightType(v4r::AM_DISTANCE); + break; + case(1): + printf("TALL MAP \n"); + surfaceHeightSaliencyMap.setHeightType(v4r::AM_TALL); + break; + case(2): + printf("SHORT MAP \n"); + surfaceHeightSaliencyMap.setHeightType(v4r::AM_SHORT); + break; + default: + printf("UNDEFINED -- return \n"); + return(0); + } + + printf("Combination Type: "); + switch(combination_type) + { + case(0): + printf("SUM \n"); + surfaceHeightSaliencyMap.setCombinationType(v4r::AM_COMB_SUM); + break; + case(1): + printf("MUL \n"); + surfaceHeightSaliencyMap.setCombinationType(v4r::AM_COMB_MUL); + break; + case(2): + printf("MAX \n"); + surfaceHeightSaliencyMap.setCombinationType(v4r::AM_COMB_MAX); + break; + default: + printf("UNDEFINED -- return \n"); + return(0); + } + + printf("Normalization Type: "); + switch(normalization_type) + { + case(0): + printf("LIN \n"); + surfaceHeightSaliencyMap.setNormalizationType(v4r::NT_NONE); + break; + case(1): + printf("NMS \n"); + surfaceHeightSaliencyMap.setNormalizationType(v4r::NT_NONMAX); + break; + case(2): + printf("NLM \n"); + surfaceHeightSaliencyMap.setNormalizationType(v4r::NT_FRINTROP_NORM); + break; + default: + printf("UNDEFINED -- return \n"); + return(0); + } + + printf("Pyramid Type: "); + switch(pyramid_type) + { + case(0): + printf("NONE \n"); + surfaceHeightSaliencyMap.calculate(); + break; + case(1): + printf("SIMPLE \n"); + surfaceHeightSaliencyMap.calculatePyramid(v4r::SIMPLE_PYRAMID); + break; + case(2): + printf("ITTI \n"); + surfaceHeightSaliencyMap.calculatePyramid(v4r::ITTI_PYRAMID); + break; + case(3): + printf("FRINTROP \n"); + surfaceHeightSaliencyMap.calculatePyramid(v4r::FRINTROP_PYRAMID); + break; + default: + printf("UNDEFINED -- return \n"); + return(0); + } + + cv::Mat map; + + if(surfaceHeightSaliencyMap.getMap(map)) + { + printf("[INFO]: Computation completed.\n"); +// cv::imshow("Surface Distance Map",map); +// printf("[INFO]: Press any key to continue.\n"); +// cv::waitKey(); + v4r::normalize(map); + cv::Mat temp; + map.convertTo(temp,CV_8U,255); + cv::imwrite(output_name,temp); + } + else + { + printf("[ERROR]: Computation failed.\n"); + } + + return(0); +} diff --git a/pool/shard007/C++/0092449_ActivityConfigurator.cpp b/pool/shard007/C++/0092449_ActivityConfigurator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6c64bab74d82cb5f40a527a386d0e93dd52c556c --- /dev/null +++ b/pool/shard007/C++/0092449_ActivityConfigurator.cpp @@ -0,0 +1,234 @@ +// @@@LICENSE +// +// Copyright (c) 2009-2013 LG Electronics, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// LICENSE@@@ + +#include "core/MojObject.h" +#include "ActivityConfigurator.h" +#include "BusClient.h" +#include "core/MojServiceMessage.h" + +#include <string.h> + +using namespace std; + +const char* const ActivityConfigurator::ACTIVITYMGR_BUS_ADDRESS = "com.palm.activitymanager"; +const char* const ActivityConfigurator::ACTIVITYMGR_CREATE_METHOD = "create"; +const char* const ActivityConfigurator::ACTIVITYMGR_REMOVE_METHOD = "cancel"; +const char* const ActivityConfigurator::ACTIVITY = "activity"; +const char* const ActivityConfigurator::CREATOR = "creator"; +const char* const ActivityConfigurator::APPLICATION_ID = "appId"; +const char* const ActivityConfigurator::SERVICE_ID = "serviceId"; +const char* const ActivityConfigurator::NAME = "name"; +const char* const ActivityConfigurator::ACTIVITY_NAME = "activityName"; +const char* const ActivityConfigurator::FIRST_USE_SAFE = "firstUseSafe"; +const char* const ActivityConfigurator::APP_DIR = "/etc/palm/activities/applications/"; +const char* const ActivityConfigurator::SERVICE_DIR = "/etc/palm/activities/services/"; +const char* const ActivityConfigurator::FIRST_USE_FLAG = "/var/luna/preferences/ran-first-use"; +const char* const ActivityConfigurator::FIRST_USE_PROFILE_FLAG = "/var/luna/preferences/first-use-profile-created"; + +class ActivityConfigureResponse : public ConfiguratorCallback { +public: + ActivityConfigureResponse(ActivityConfigurator *conf, const string& path) + : ConfiguratorCallback(conf, path) + { + } + + ~ActivityConfigureResponse() + { + } + + MojErr Response(MojObject& response, MojErr err) + { + bool success = true; + response.get("returnValue", success); + + if (err || !success) { + MojInt64 errorCode; + if (response.get("errorCode", errorCode)) { + if (errorCode == MojErrExists) { + LOG_DEBUG("caching ok negative response for %s", m_config.c_str()); + bool found = false; + response.del("errorCode", found); + response.del("errorText", found); + err = response.putBool("returnValue", true); + MarkConfigured(); + } else { + LOG_WARNING(MSGID_ACTIVITY_CONFIGURATOR_WARNING, 1, + PMLOGKFV("errorCode", "%d", (int)errorCode), + "Unrecognized errorCode %d", (int)errorCode); + } + } else { + LOG_WARNING(MSGID_ACTIVITY_CONFIGURATOR_WARNING, 0, "errorCode not provided in request failure"); + } + } + return DelegateResponse(response, err); + } +}; + +const char* ActivityConfigurator::ConfiguratorName() const +{ + return "ActivityConfigurator"; +} + +const char* ActivityConfigurator::ServiceName() const +{ + return ACTIVITYMGR_BUS_ADDRESS; +} + +ConfiguratorCallback* ActivityConfigurator::CreateCallback(const std::string &filePath) +{ + return new ActivityConfigureResponse(this, filePath); +} + +ActivityConfigurator::ActivityConfigurator(const std::string& id, ConfigType confType, RunType type, BusClient& busClient, string configDirectory) + : Configurator(id, confType, type, busClient, configDirectory), + m_firstUseOnly(true) +{ + int err; + struct stat buf; + err = stat(FIRST_USE_FLAG, &buf); + if (err == 0) { + err = stat(FIRST_USE_PROFILE_FLAG, &buf); + if (err == 0) { + LOG_DEBUG("Fist Use has completed, installing all Activities"); + m_firstUseOnly = false; + } + } +#ifdef WEBOS_TARGET_MACHINE_STANDALONE + //Set the m_firstUseOnly flag to false as there is no first use run in Desktop. + m_firstUseOnly = false; +#endif +} + +ActivityConfigurator::~ActivityConfigurator() +{ + +} + +bool ActivityConfigurator::CanCacheConfiguratorStatus(const std::string&) const +{ + LOG_TRACE("Entering function %s", __FUNCTION__); + return false; +} + +static void RemoveKey(MojObject& object, const MojChar *key) +{ + bool keydeleted; + object.del(key, keydeleted); +} + +static bool StartsWith(const std::string& s1, const std::string& prefix) +{ + return prefix.length() <= s1.length() && memcmp(s1.c_str(), prefix.c_str(), prefix.length()) == 0; +} + +MojErr ActivityConfigurator::ProcessConfig(const string& filePath, MojObject& params) +{ + LOG_TRACE("Entering function %s", __FUNCTION__); + + const std::string& creator = ParentId(filePath); + + if (creator.empty()) { + LOG_ERROR(MSGID_ACTIVITY_CONFIGURATOR_ERROR, 0, "Service id for activity '%s' is empty - needs to be in an appropriate subdirectory or given as part of the service call", filePath.c_str()); + return MojErrInvalidArg; + } + + if (m_firstUseOnly) { + bool firstUseSafe; + if (!params.get(FIRST_USE_SAFE, firstUseSafe) || !firstUseSafe) { + LOG_DEBUG("Running before first use but activity %s not marked as safe for configuration at this time", filePath.c_str()); + return MojErrInProgress; + } + } + + LOG_DEBUG("ActivityConfigurator creator for %s is %s\n", filePath.c_str(), creator.c_str()); + + MojObject activity; + MojErr err; + err = params.getRequired(ACTIVITY, activity); + MojErrCheck(err); + + ConfigType confType; + + if (m_confType == ConfigUnknown) { + if (StartsWith(filePath, APP_DIR)) { + confType = ConfigApplication; + } else { + if (!StartsWith(filePath, SERVICE_DIR)) { + //Fix for DFISH-14510 turn down logging here + //MojLogWarning(m_log, "Deprecated usage: %s not in application or service subdirectory as required - assumed to be service", filePath.c_str()); + } + confType = ConfigService; + } + } else { + confType = m_confType; + } + + MojObject creatorObj; + switch (confType) { + case ConfigApplication: + err = creatorObj.putString(APPLICATION_ID, creator.c_str()); + break; + case ConfigService: + err = creatorObj.putString(SERVICE_ID, creator.c_str()); + break; + case ConfigUnknown: + // impossible case + assert(false); + break; + } + + MojErrCheck(err); + + err = activity.put(CREATOR, creatorObj); + MojErrCheck(err); + err = params.put(ACTIVITY, activity); + MojErrCheck(err); + + // strip configurator-specific keys + // so that the schema on activity manager isn't violated + RemoveKey(params, FIRST_USE_SAFE); + + return m_busClient.CreateRequest()->send(CreateCallback(filePath)->m_slot, ServiceName(), ACTIVITYMGR_CREATE_METHOD, params); +} + +MojErr ActivityConfigurator::ProcessConfigRemoval(const string& filePath, MojObject& params) +{ + LOG_TRACE("Entering function %s", __FUNCTION__); + MojErr err; + + MojObject activity; + MojString activityName; + + err = params.getRequired(ACTIVITY, activity); MojErrCheck(err); + err = activity.getRequired(NAME, activityName); MojErrCheck(err); + + MojObject request(MojObject::TypeObject); + const std::string& creator = ParentId(filePath); + + if (creator.empty()) { + LOG_ERROR(MSGID_ACTIVITY_CONFIGURATOR_ERROR, 0, "Service id for activity '%s' is empty - needs to be in an appropriate subdirectory or given as part of the service call", filePath.c_str()); + return MojErrInvalidArg; + } + + // {"activityName": "..."} + err = request.putString(ACTIVITY_NAME, activityName); MojErrCheck(err); + // {"activityName": "...", "creator": "..."} + err = request.putString(CREATOR, creator.c_str()); MojErrCheck(err); + + return m_busClient.CreateRequest()->send(CreateCallback(filePath)->m_slot, ServiceName(), ACTIVITYMGR_REMOVE_METHOD, request); +} diff --git a/pool/shard007/C++/0092450_fs_util.cpp b/pool/shard007/C++/0092450_fs_util.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fe6e642eb5cd674720f635589ca88ee415affa40 --- /dev/null +++ b/pool/shard007/C++/0092450_fs_util.cpp @@ -0,0 +1,182 @@ +/*************************************************************** + * + * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, + * University of Wisconsin-Madison, WI. + * + * 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. + * + ***************************************************************/ + + +#ifdef FS_UTIL_TEST +# include <stdio.h> +# include <stdlib.h> +# include <errno.h> +#else +# include "condor_common.h" +# include "condor_debug.h" +#endif + +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#include "condor_constants.h" +#include "basename.h" +#include "fs_util.h" + +// Historically, there was also a USE_STATVFS that only was used +// on Solaris. +#if defined HAVE_STATFS +# define USE_STATFS +#endif + + +#ifdef HAVE_SYS_TYPES_H +# include <sys/types.h> +#endif + +#ifdef HAVE_SYS_PARAM_H +# include <sys/param.h> +#endif + +#ifdef USE_STATFS +#ifdef LINUX +#include <sys/statfs.h> +#include <linux/magic.h> +#else +// statfs isn't POSIX; MacOS has the same function but in a different +// header file compared to Linux. +#include <sys/mount.h> +#define NFS_SUPER_MAGIC 0x6969 // From the man pages of statfs() +#endif +#endif + +#include <string.h> + +#if( defined USE_STATFS ) +static int +detect_nfs_statfs( const char *path, bool *is_nfs ) +{ + int status; + struct statfs buf; + +# if (STATFS_ARGS == 2) + status = statfs( path, &buf ); +# elif (STATFS_ARGS == 4) + status = statfs( path, &buf, sizeof(buf), 0 ); +# else +# error "Unknown statfs() implemenation" +# endif + + if ( ( status < 0 ) && ( errno == ENOENT )) { + // file doesn't exist yet, so check parent directory. + char *_dir_name; + _dir_name = condor_dirname(path); +# ifdef FS_UTIL_TEST + printf("checking %s instead...\n", _dir_name); +# endif +# if (STATFS_ARGS == 2) + status = statfs( _dir_name, &buf ); +# elif (STATFS_ARGS == 4) + status = statfs( _dir_name, &buf, sizeof(buf), 0 ); +# else +# error "Unknown statfs() implemenation" +# endif + free(_dir_name); + } + + if ( status < 0 ) { +# if (!defined FS_UTIL_TEST ) + dprintf( D_ALWAYS, "statfs(%s) failed: %d/%s\n", + path, errno, strerror( errno ) ); + if (EOVERFLOW == errno) { + dprintf(D_ALWAYS, + "statfs overflow, if %s is a large volume make " + "sure you have a 64 bit version of Condor\n", path); + } +# endif + return -1; + } + + // 1st try: Look at the fstypename string +# if defined HAVE_STRUCT_STATFS_F_FSTYPENAME + if ( !strncmp( buf.f_fstypename, "nfs", 3 ) ) { + *is_nfs = true; + } else { + *is_nfs = false; + } +# ifdef FS_UTIL_TEST + printf( "detect_nfs_statfs: f_fstypename = %s -> %s\n", + buf.f_fstypename, *is_nfs ? "true" : "false" ); +# endif + + // #2: Look at the f_type value +# elif defined(UNIX) + if ( buf.f_type == NFS_SUPER_MAGIC ) { + *is_nfs = true; + } else { + *is_nfs = false; + } +# ifdef FS_UTIL_TEST + printf( "detect_nfs_statfs: f_type = %x -> %s\n", + buf.f_type, *is_nfs ? "true" : "false" ); +# endif + + // #3: Completely unknown +# else +# error "Neither F_TYPE or F_FSTYP defined!" + +# endif + + return 0; +} +#endif + +int +fs_detect_nfs( const char *path, + bool *is_nfs ) +{ +#if defined USE_STATFS + return detect_nfs_statfs( path, is_nfs ); +#else +# if !defined(WIN32) +# warning "No valid fs type detection" +# endif + *is_nfs = false; + return 0; +#endif + +} + +#ifdef FS_UTIL_TEST +int +main( int argc, const char *argv[] ) +{ + const char *path = argv[1]; + bool is_nfs; + + if ( argc != 2 ) { + fprintf( stderr, "usage: fs_util_test path\n" ); + exit( 1 ); + } + if ( fs_detect_nfs( path, &is_nfs ) < 0 ) { + fprintf( stderr, "fs_detect_nfs(%s) failed\n", path ); + exit( 1 ); + } + printf( "%s %s on NFS\n", path, is_nfs ? "is" : "is not" ); + + return 0; +} +#endif + diff --git a/pool/shard007/C++/0092452_ImageIndex.cpp b/pool/shard007/C++/0092452_ImageIndex.cpp new file mode 100644 index 0000000000000000000000000000000000000000..06918338ac39a37697d6ef3bc7fa44d3ebb826b2 --- /dev/null +++ b/pool/shard007/C++/0092452_ImageIndex.cpp @@ -0,0 +1,170 @@ +// +// Copyright 2014 The ANGLE Project Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +// + +// ImageIndex.cpp: Implementation for ImageIndex methods. + +#include "libANGLE/ImageIndex.h" +#include "libANGLE/Constants.h" +#include "common/utilities.h" + +namespace gl +{ + +ImageIndex::ImageIndex(const ImageIndex &other) + : type(other.type), + mipIndex(other.mipIndex), + layerIndex(other.layerIndex) +{} + +ImageIndex &ImageIndex::operator=(const ImageIndex &other) +{ + type = other.type; + mipIndex = other.mipIndex; + layerIndex = other.layerIndex; + return *this; +} + +ImageIndex ImageIndex::Make2D(GLint mipIndex) +{ + return ImageIndex(GL_TEXTURE_2D, mipIndex, ENTIRE_LEVEL); +} + +ImageIndex ImageIndex::MakeCube(GLenum target, GLint mipIndex) +{ + ASSERT(gl::IsCubeMapTextureTarget(target)); + return ImageIndex(target, mipIndex, CubeMapTextureTargetToLayerIndex(target)); +} + +ImageIndex ImageIndex::Make2DArray(GLint mipIndex, GLint layerIndex) +{ + return ImageIndex(GL_TEXTURE_2D_ARRAY, mipIndex, layerIndex); +} + +ImageIndex ImageIndex::Make3D(GLint mipIndex, GLint layerIndex) +{ + return ImageIndex(GL_TEXTURE_3D, mipIndex, layerIndex); +} + +ImageIndex ImageIndex::MakeGeneric(GLenum target, GLint mipIndex) +{ + GLint layerIndex = IsCubeMapTextureTarget(target) ? CubeMapTextureTargetToLayerIndex(target) : ENTIRE_LEVEL; + return ImageIndex(target, mipIndex, layerIndex); +} + +ImageIndex ImageIndex::MakeInvalid() +{ + return ImageIndex(GL_NONE, -1, -1); +} + +bool ImageIndex::operator<(const ImageIndex &other) const +{ + if (type != other.type) + { + return type < other.type; + } + else if (mipIndex != other.mipIndex) + { + return mipIndex < other.mipIndex; + } + else + { + return layerIndex < other.layerIndex; + } +} + +ImageIndex::ImageIndex(GLenum typeIn, GLint mipIndexIn, GLint layerIndexIn) + : type(typeIn), + mipIndex(mipIndexIn), + layerIndex(layerIndexIn) +{} + +ImageIndexIterator ImageIndexIterator::Make2D(GLint minMip, GLint maxMip) +{ + return ImageIndexIterator(GL_TEXTURE_2D, Range<GLint>(minMip, maxMip), + Range<GLint>(ImageIndex::ENTIRE_LEVEL, ImageIndex::ENTIRE_LEVEL), NULL); +} + +ImageIndexIterator ImageIndexIterator::MakeCube(GLint minMip, GLint maxMip) +{ + return ImageIndexIterator(GL_TEXTURE_CUBE_MAP, Range<GLint>(minMip, maxMip), Range<GLint>(0, 6), NULL); +} + +ImageIndexIterator ImageIndexIterator::Make3D(GLint minMip, GLint maxMip, + GLint minLayer, GLint maxLayer) +{ + return ImageIndexIterator(GL_TEXTURE_3D, Range<GLint>(minMip, maxMip), Range<GLint>(minLayer, maxLayer), NULL); +} + +ImageIndexIterator ImageIndexIterator::Make2DArray(GLint minMip, GLint maxMip, + const GLsizei *layerCounts) +{ + return ImageIndexIterator(GL_TEXTURE_2D_ARRAY, Range<GLint>(minMip, maxMip), + Range<GLint>(0, IMPLEMENTATION_MAX_2D_ARRAY_TEXTURE_LAYERS), layerCounts); +} + +ImageIndexIterator::ImageIndexIterator(GLenum type, const Range<GLint> &mipRange, + const Range<GLint> &layerRange, const GLsizei *layerCounts) + : mType(type), + mMipRange(mipRange), + mLayerRange(layerRange), + mLayerCounts(layerCounts), + mCurrentMip(mipRange.start), + mCurrentLayer(layerRange.start) +{} + +GLint ImageIndexIterator::maxLayer() const +{ + return (mLayerCounts ? static_cast<GLint>(mLayerCounts[mCurrentMip]) : mLayerRange.end); +} + +ImageIndex ImageIndexIterator::next() +{ + ASSERT(hasNext()); + + ImageIndex value = current(); + + // Iterate layers in the inner loop for now. We can add switchable + // layer or mip iteration if we need it. + + if (mCurrentLayer != ImageIndex::ENTIRE_LEVEL) + { + if (mCurrentLayer < maxLayer()-1) + { + mCurrentLayer++; + } + else if (mCurrentMip < mMipRange.end-1) + { + mCurrentMip++; + mCurrentLayer = mLayerRange.start; + } + } + else if (mCurrentMip < mMipRange.end-1) + { + mCurrentMip++; + mCurrentLayer = mLayerRange.start; + } + + return value; +} + +ImageIndex ImageIndexIterator::current() const +{ + ImageIndex value(mType, mCurrentMip, mCurrentLayer); + + if (mType == GL_TEXTURE_CUBE_MAP) + { + value.type = LayerIndexToCubeMapTextureTarget(mCurrentLayer); + } + + return value; +} + +bool ImageIndexIterator::hasNext() const +{ + return (mCurrentMip < mMipRange.end || mCurrentLayer < maxLayer()); +} + +} diff --git a/pool/shard007/C++/0092453_carddav-plugin.cpp b/pool/shard007/C++/0092453_carddav-plugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0f5538ca6ea5fe6a4013360e38b06b78d982131a --- /dev/null +++ b/pool/shard007/C++/0092453_carddav-plugin.cpp @@ -0,0 +1,179 @@ +/* + Copyright (C) 2015 Martin Klapetek <mklapetek@kde.org> + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "carddav-plugin.h" +#include "carddav_p.h" +#include "syncer_p.h" + +#include <KJob> +#include <KConfigCore/KSharedConfig> +#include <KConfigCore/KConfigGroup> + +#include <Accounts/Service> +#include <Accounts/Manager> +#include <Accounts/Account> +#include <Accounts/AccountService> +#include <QTimer> + +#include "getcredentialsjob.h" +#include "core.h" + +class KAccountsCardDavPlugin::Private { +public: + Private(KAccountsCardDavPlugin *qq) { q = qq; }; + + KAccountsCardDavPlugin *q; + KSharedConfig::Ptr config; + QTimer *syncTimer; +}; + + +//--------------------------------------------------------------------------------------- + +KAccountsCardDavPlugin::KAccountsCardDavPlugin(QObject *parent) + : KAccountsDPlugin(parent), + d(new Private(this)) +{ + d->config = KSharedConfig::openConfig(QStringLiteral("kaccounts-carddavrc")); + d->syncTimer = new QTimer(this); + d->syncTimer->setInterval(1000 * 60 *30); + + connect(d->syncTimer, &QTimer::timeout, this, &KAccountsCardDavPlugin::syncAllAccounts); + + syncAllAccounts(); +} + +KAccountsCardDavPlugin::~KAccountsCardDavPlugin() +{ +} + +void KAccountsCardDavPlugin::syncAllAccounts() +{ + KConfigGroup global = d->config->group("Global"); + QList<quint32> syncedAccounts = global.readEntry("syncedAccounts", QList<quint32>()); + + if (syncedAccounts.isEmpty()) { + Accounts::AccountIdList accounts = KAccounts::accountsManager()->accountListEnabled(QStringLiteral("dav-contacts")); + syncedAccounts << accounts; + } + + qDebug() << "List of accounts to sync:" << syncedAccounts; + Q_FOREACH (const quint32 accountId, syncedAccounts) { + KConfigGroup currentAccount = d->config->group("account" + QString::number(accountId)); + QDateTime lastSync = QDateTime::fromString(currentAccount.readEntry("lastSync", QStringLiteral("2000-09-22T00:00:00+00:00")), Qt::ISODate); + if (QDateTime::currentDateTime() > lastSync) { + qDebug() << "Starting carddav contacts import for account" << accountId; + getCredentials(accountId); + } + } +} + +void KAccountsCardDavPlugin::onAccountCreated(const Accounts::AccountId accountId, const Accounts::ServiceList &serviceList) +{ + Accounts::Account *account = KAccounts::accountsManager()->account(accountId); + + if (!account) { + qWarning() << "Invalid account for id" << accountId; + return; + } + + Q_FOREACH (const Accounts::Service &service, serviceList) { + account->selectService(service); + if (service.serviceType() == QLatin1String("dav-contacts") && account->isEnabled()) { + qDebug() << "Starting carddav contacts import for account" << accountId << "and service" << service.serviceType(); + getCredentials(accountId); + } + } +} + +void KAccountsCardDavPlugin::onAccountRemoved(const Accounts::AccountId accountId) +{ +} + +void KAccountsCardDavPlugin::onServiceEnabled(const Accounts::AccountId accountId, const Accounts::Service &service) +{ +} + +void KAccountsCardDavPlugin::onServiceDisabled(const Accounts::AccountId accountId, const Accounts::Service &service) +{ +} + +void KAccountsCardDavPlugin::getCredentials(const Accounts::AccountId accountId) +{ + GetCredentialsJob *credentialsJob = new GetCredentialsJob(accountId, this); + connect(credentialsJob, &GetCredentialsJob::finished, this, &KAccountsCardDavPlugin::importContacts); + credentialsJob->start(); +} + +void KAccountsCardDavPlugin::importContacts(KJob *job) +{ + GetCredentialsJob *credentialsJob = qobject_cast<GetCredentialsJob*>(job); + job->deleteLater(); + + if (!credentialsJob) { + return; + } + + const QVariantMap &data = credentialsJob->credentialsData(); + Accounts::Account *account = KAccounts::accountsManager()->account(credentialsJob->accountId()); + + if (!account) { + return; + } + + QUrl carddavUrl = account->value("carddavUrl").toUrl(); + + qDebug() << "Using: host:" << carddavUrl.host() << "path:" << carddavUrl.path(); + + Syncer *s = new Syncer(nullptr); + s->setProperty("accountId", credentialsJob->accountId()); + + const QString &userName = data.value("AccountUsername").toString(); + + CardDav *m_cardDav = new CardDav(s, + carddavUrl.scheme() + "://" + carddavUrl.host(), + carddavUrl.path(), + userName, + data.value("Secret").toString()); + + QObject::connect(m_cardDav, SIGNAL(remoteChanges(QList<KContacts::Addressee>,QList<KContacts::Addressee>,QList<KContacts::Addressee>)), + s, SLOT(continueSync(QList<KContacts::Addressee>,QList<KContacts::Addressee>,QList<KContacts::Addressee>))); + QObject::connect(m_cardDav, SIGNAL(upsyncCompleted()), + s, SLOT(syncFinished())); + QObject::connect(m_cardDav, SIGNAL(error(int)), + s, SLOT(cardDavError(int))); + + QObject::connect(s, &Syncer::syncSucceeded, [=] { + d->syncTimer->start(); + quint32 accountId = s->property("accountId").toUInt(); + + KConfigGroup global = d->config->group("Global"); + QList<quint32> syncedAccounts = global.readEntry("syncedAccounts", QList<quint32>()); + if (!syncedAccounts.contains(accountId)) { + syncedAccounts.append(accountId); + } + global.writeEntry("syncedAccounts", syncedAccounts); + global.sync(); + + KConfigGroup currentAccount = d->config->group("account" + QString::number(accountId)); + currentAccount.writeEntry("lastSync", QDateTime::currentDateTime().toString(Qt::ISODate)); + currentAccount.sync(); + }); + + m_cardDav->determineRemoteAMR(); +} diff --git a/pool/shard007/C++/0092455_test_internal_priority_queue.cpp b/pool/shard007/C++/0092455_test_internal_priority_queue.cpp new file mode 100644 index 0000000000000000000000000000000000000000..60dd7aa8f96064939fb97c94a0f55c4ee0cd1e77 --- /dev/null +++ b/pool/shard007/C++/0092455_test_internal_priority_queue.cpp @@ -0,0 +1,69 @@ +// -*- mode: c++; tab-width: 4; indent-tabs-mode: t; c-file-style: "stroustrup"; -*- +// vi:set ts=4 sts=4 sw=4 noet : +// Copyright 2008, 2012, The TPIE development team +// +// This file is part of TPIE. +// +// TPIE is free software: you can redistribute it and/or modify it under +// the terms of the GNU Lesser General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at your +// option) any later version. +// +// TPIE is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +// License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with TPIE. If not, see <http://www.gnu.org/licenses/> +#include "common.h" +#include <tpie/internal_priority_queue.h> +#include <vector> +#include "priority_queue.h" + +// Method coverage of tpie::internal_priority_queue +// +// Method Covered by unit test +// ctor(max_size) basic +// ctor(max_size, IT, IT) TODO +// clear TODO +// empty TODO +// get_array TODO +// insert TODO +// make_safe TODO +// pop basic +// pop_and_push TODO +// push basic +// resize TODO +// size basic +// top basic +// unsafe_push TODO + +using namespace tpie; + +bool basic_test() { + size_t z = 104729; + internal_priority_queue<uint64_t, bit_pertume_compare<std::greater<uint64_t> > > pq(z); + return basic_pq_test(pq, z); +} + +bool large_cycle(){ + size_t x = 524*1024*102; + internal_priority_queue<uint64_t, bit_pertume_compare<std::greater<uint64_t> > > pq(x); + return cyclic_pq_test(pq, x, 20000000); +} + +class my_memory_test: public memory_test { +public: + internal_priority_queue<int> * a; + virtual void alloc() {a = tpie_new<internal_priority_queue<int> >(123456);} + virtual void free() {tpie_delete(a);} + virtual size_type claimed_size() {return static_cast<size_type>(internal_priority_queue<int>::memory_usage(123456));} +}; + +int main(int argc, char **argv) { + return tpie::tests(argc, argv) + .test(basic_test, "basic") + .test(large_cycle, "large_cycle") + .test(my_memory_test(), "memory"); +} diff --git a/pool/shard007/C++/0092457_DogandGopher.cpp b/pool/shard007/C++/0092457_DogandGopher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a314b7b6d4518abee859ef8898dda35d5fe359b5 --- /dev/null +++ b/pool/shard007/C++/0092457_DogandGopher.cpp @@ -0,0 +1,80 @@ +/* + * By: ulises-jeremias + * From: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1251 + * Name: Dog and Gopher + * Date: 08/11/2017 + */ + +#include <iostream> +#include <vector> +#include <utility> +#include <algorithm> +#include <cmath> + +#define INF 1 << 30 + +using namespace std; + +struct point { + double x, y; + point () { + x = y = 0.0; + } + + point (double _x, double _y) : x(_x), y(_y) { + }; +}; + +int n; +double x, y; +point gopher, dog, escape; +vector<point> holes; + +double dist_point (const point &a, const point &b) { + return hypot(a.x-b.x, a.y-b.y); +} + +bool can_escape() +{ + int i; + + for (i = 0; i < n; i++) { + if (dist_point(gopher, holes[i]) <= dist_point(dog, holes[i]) * 0.5) { + escape.x = holes[i].x; + escape.y = holes[i].y; + return true; + } + } + + return false; +} + +int main(int argc, char const *argv[]) +{ + #ifndef ONLINE_JUDGE + #define ONLINE_JUDGE + ios_base::sync_with_stdio(false); + cin.tie(NULL); + #endif + + // cout << fixed << setprecision(3); + + int i, j; + + while (cin >> n >> gopher.x >> gopher.y >> dog.x >> dog.y) { + holes.clear(); + + for (i = 0; i < n; i++) { + cin >> x >> y; + holes.push_back(point(x, y)); + } + + if (can_escape()) { + printf("The gopher can escape through the hole at (%.03lf,%.03lf).\n", escape.x, escape.y); + } else { + printf("The gopher cannot escape.\n"); + } + } + + return 0; +} diff --git a/pool/shard007/C++/0092467_shield.cpp b/pool/shard007/C++/0092467_shield.cpp new file mode 100644 index 0000000000000000000000000000000000000000..33067e495ded0c9d10544dc1eaf448e24e5fa61c --- /dev/null +++ b/pool/shard007/C++/0092467_shield.cpp @@ -0,0 +1,31 @@ + +#include "ingameelements/shield.h" + +void Shield::init(uint64_t id_, Gamestate &state, double maxhp, Team team_) +{ + MovingEntity::init(id_, state); + + hp = maxhp; + team = team_; +} + +double Shield::damage(Gamestate &state, double amount, EntityPtr source, Damagetype damagetype) +{ + double oldhp = hp; + hp -= amount; + if (hp <= 0) + { + shieldbreak(state); + } + return std::min(amount, oldhp); +} + +void Shield::interpolate(Entity &prev_entity, Entity &next_entity, double alpha) +{ + MovingEntity::interpolate(prev_entity, next_entity, alpha); + + Shield &prev_e = static_cast<Shield&>(prev_entity); + Shield &next_e = static_cast<Shield&>(next_entity); + + hp = prev_e.hp + alpha*(next_e.hp - prev_e.hp); +} \ No newline at end of file diff --git a/pool/shard007/C++/0092473_transactiondescdialog.cpp b/pool/shard007/C++/0092473_transactiondescdialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6afd4419d1326cd336b3a4da0528d6f985bf762d --- /dev/null +++ b/pool/shard007/C++/0092473_transactiondescdialog.cpp @@ -0,0 +1,101 @@ +#include "transactiondescdialog.h" +#include "ui_transactiondescdialog.h" + +#include "transactiontablemodel.h" +#include "init.h" //need pwalletMain +#include "net.h" +#include "bitcoinrpc.h" +#include <boost/algorithm/string.hpp> +#include "util.h" +#include <QModelIndex> +#include <QDebug> +#include <QtDebug> + +TransactionDescDialog::TransactionDescDialog(const QModelIndex &idx, QWidget *parent) : + QDialog(parent), + ui(new Ui::TransactionDescDialog) +{ + ui->setupUi(this); + + QString desc = idx.data(TransactionTableModel::LongDescriptionRole).toString(); + int status = idx.data(TransactionTableModel::StatusRole).toInt(); + + //there must be a less laughable way to get the tx id than this :P + QString hash = idx.data(TransactionTableModel::Hash).toString(); + std::string tx_id_str = hash.toUtf8().constData(); + tx_id = uint256(tx_id_str); + + ui->detailText->setHtml(desc); + ui->retrieveButton->setEnabled(status == TransactionStatus::Escrow || status == TransactionStatus::Expiry ); + + isEscrow = (status == TransactionStatus::Escrow); + depth = idx.data(TransactionTableModel::Depth).toInt(); + connect(ui->retrieveButton, SIGNAL(clicked()), this, SLOT(retrieveTxHandler())); +} + +TransactionDescDialog::~TransactionDescDialog() +{ + delete ui; +} + +void TransactionDescDialog::retrieveTxHandler() +{ + std::string retrieve; + QString err; + std::string ret; + + + if (pwalletMain->ReadRetrieveStringFromHashMap(tx_id, retrieve, isEscrow)) { + + qDebug() << QString(retrieve.c_str()); + + std::vector<std::string> params; + boost::split(params, retrieve, boost::is_any_of(" ")); + if (isEscrow ) { + std::string const destination_address = params[0]; + uint256 const bind_txid = ParseHashV(params[1], "bind_txid"); + ret = CreateTransferExpiry(destination_address, bind_txid, depth); + err = QString(ret.c_str()); + + if (depth >= 5 && !err.startsWith(QString("OK!")) ) { + try { + + std::string const destination_address = params[0]; + uint256 const sender_confirmtx_hash = ParseHashV(params[1], "sender_confirmtx_hash"); + std::string const sender_tor_address = params[2]; + uint64_t const sender_address_bind_nonce = toUint64(params[3]); + uint64_t const transfer_nonce = toUint64(params[4]); + std::vector<unsigned char> const transfer_tx_hash = ParseHexV(params[5],"transfer_tx_hash"); + + ret = CreateTransferEscrow ( + destination_address, + sender_confirmtx_hash, + sender_tor_address, + sender_address_bind_nonce, + transfer_nonce, + transfer_tx_hash, + depth + ); + err = QString(ret.c_str()); + + } + catch (const std::exception& ex) + { + err = QString(ex.what()); + } + } + + } else { + + std::string const destination_address = params[0]; + uint256 const bind_txid = ParseHashV(params[1], "bind_txid"); + ret = CreateTransferExpiry(destination_address, bind_txid, depth); + err = QString(ret.c_str()); + } + } + if (err.startsWith(QString("OK!"))) { + //retrieval success, so delete entry in the map + pwalletMain->DeleteRetrieveStringFromDB(tx_id); + } + ui->detailText->setText(err); +} diff --git a/pool/shard007/C++/0092477_nameserver.cpp b/pool/shard007/C++/0092477_nameserver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..075dab56a558f2d56a721af799c277c96cbec898 --- /dev/null +++ b/pool/shard007/C++/0092477_nameserver.cpp @@ -0,0 +1,91 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Alexander Rössler +** License: LGPL version 2.1 +** +** This file is part of QtQuickVcp. +** +** All rights reserved. This program and the accompanying materials +** are made available under the terms of the GNU Lesser General Public License +** (LGPL) version 2.1 which accompanies this distribution, and is available at +** http://www.gnu.org/licenses/lgpl-2.1.html +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** Contributors: +** Alexander Rössler @ The Cool Tool GmbH <mail DOT aroessler AT gmail DOT com> +** +****************************************************************************/ + +#include "nameserver.h" + +namespace qtquickvcp { + +NameServer::NameServer(QObject *parent) : + QObject(parent), + m_hostName(QString()), + m_hostAddress(QHostAddress()), + m_port(5353), + m_dnsLookup(nullptr) +{ +} + +void NameServer::updateHostAddress() +{ + QHostAddress newHostAddress(m_hostName); + + if (!newHostAddress.isNull()) + { + m_hostAddress = newHostAddress; + } + else + { + m_hostAddress = QHostAddress(); + + if (!m_hostName.isEmpty()) + { + if (m_dnsLookup != nullptr) + { + m_dnsLookup->abort(); + m_dnsLookup->deleteLater(); + } + + m_dnsLookup = new QDnsLookup(this); + connect(m_dnsLookup, &QDnsLookup::finished, + this, &NameServer::handleServers); + + m_dnsLookup->setType(QDnsLookup::A); + m_dnsLookup->setName(m_hostName); + m_dnsLookup->lookup(); + } + } + + emit hostAddressChanged(m_hostAddress); +} + +void NameServer::handleServers() +{ + if (m_dnsLookup->error() != QDnsLookup::NoError) // TODO: better error handling + { +#ifdef QT_DEBUG + qDebug() << "DNS lookup error:" << m_dnsLookup->errorString(); +#endif + m_dnsLookup->deleteLater(); + m_dnsLookup = nullptr; + return; + } + + foreach (const QDnsHostAddressRecord &record, m_dnsLookup->hostAddressRecords()) + { + m_hostAddress = record.value(); // first wins + emit hostAddressChanged(m_hostAddress); + break; + } + + m_dnsLookup->deleteLater(); + m_dnsLookup = nullptr; +} +} // namespace qtquickvcp diff --git a/pool/shard007/C++/0092485_ListArchivesResult.cpp b/pool/shard007/C++/0092485_ListArchivesResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..810eac2221e361f8c9bab2af5f05c526d19afcb3 --- /dev/null +++ b/pool/shard007/C++/0092485_ListArchivesResult.cpp @@ -0,0 +1,49 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include <aws/eventbridge/model/ListArchivesResult.h> +#include <aws/core/utils/json/JsonSerializer.h> +#include <aws/core/AmazonWebServiceResult.h> +#include <aws/core/utils/StringUtils.h> +#include <aws/core/utils/UnreferencedParam.h> + +#include <utility> + +using namespace Aws::EventBridge::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +ListArchivesResult::ListArchivesResult() +{ +} + +ListArchivesResult::ListArchivesResult(const Aws::AmazonWebServiceResult<JsonValue>& result) +{ + *this = result; +} + +ListArchivesResult& ListArchivesResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) +{ + JsonView jsonValue = result.GetPayload().View(); + if(jsonValue.ValueExists("Archives")) + { + Array<JsonView> archivesJsonList = jsonValue.GetArray("Archives"); + for(unsigned archivesIndex = 0; archivesIndex < archivesJsonList.GetLength(); ++archivesIndex) + { + m_archives.push_back(archivesJsonList[archivesIndex].AsObject()); + } + } + + if(jsonValue.ValueExists("NextToken")) + { + m_nextToken = jsonValue.GetString("NextToken"); + + } + + + + return *this; +} diff --git a/pool/shard007/C++/0092490_main.cpp b/pool/shard007/C++/0092490_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1968eb3e4871e6d49c0288e919c9caa710014687 --- /dev/null +++ b/pool/shard007/C++/0092490_main.cpp @@ -0,0 +1,258 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +/* + * File: main.cpp + * Author: A7mad + * + * Created on April 15, 2017, 6:57 PM + */ + +#include "ClientData.h" + +#include <iostream> +#include <fstream> +#include <iomanip> +#include <cstdlib> + +using namespace std; + +int enterChoice(); + +void createTextFile(fstream &); + +void updateRecord(fstream &); + +void newRecord(fstream &); + +void deleteRecord(fstream &); + +void outputLine(ostream &, const ClientData &); + +int getAccount(const char *const); + +enum Choices { + PRINT = 1, UPDATE, NEW, DELETE, END +}; + +int main(int argc, const char *argv[]) { + // open file for reading and writing + fstream inOutCredit("//media//maxmya//Projects//Collage Projects//Spring 2017//File Structure//CASE STUDY//credit.dat", ios::in | ios::out | ios::binary); + + // exit program if fstream cannot open file + if (!inOutCredit) { + cerr << "File could not be opened." << endl; + exit(EXIT_FAILURE); + } + + int choice; // store user choice + + // enable user to specify action + while ((choice = enterChoice()) != END) { + switch (choice) { + case PRINT: // create text file from record file + createTextFile(inOutCredit); + break; + case UPDATE: // update record + updateRecord(inOutCredit); + break; + case NEW: // create record + newRecord(inOutCredit); + break; + case DELETE: // delete existing record + deleteRecord(inOutCredit); + break; + default: // display error if user does not select valid choice + cerr << "Incorrect choice" << endl; + break; + } + inOutCredit.clear(); // reset end-of-file indicator + } + return 0; +} +// enable user to input menu choice + +int enterChoice() { + // display available options + cout << "\nEnter you choice" << endl + << "1 - store a formatted text file of accounts" << endl + << " called \"print.txt\" for printing" << endl + << "2 - update an account" << endl + << "3 - add a new account" << endl + << "4 - delete an account" << endl + << "5 - end program\n? "; + + int menuChoice; + + cin >> menuChoice; // input menu selection from user + + return menuChoice; +} +// create formatted text file for printing + +void createTextFile(fstream &readFromFile) { + + // create text file + ofstream outPrintFile("//media//maxmya//Projects//Collage Projects//Spring 2017//File Structure//CASE STUDY//print.txt", ios::out); + + // exit program if ofstream cannot create file + if (!outPrintFile) { + cerr << "File could not be created" << endl; + exit(EXIT_FAILURE); + } + + outPrintFile << left << setw(10) << "Account" << setw(16) + << "Last Name" << setw(11) << "First Name" << right + << setw(10) << "Balance" << setw(10) << "BranchId" << endl; + + // set file-position pointer to beginning of readFromFile + readFromFile.seekg(0); + + // read first record from record file + ClientData client; + readFromFile.read(reinterpret_cast<char *> (&client), sizeof(ClientData)); + + // copy all record from record file into text file + while (!readFromFile.eof()) { + // write single record to text file + if (client.getAccountNumber() != 0) // skip empty records + outputLine(outPrintFile, client); + + // read next record from record file + readFromFile.read(reinterpret_cast<char *> (&client), sizeof(ClientData)); + } +} +// update balance in record + +void updateRecord(fstream &updateFile) { + // obtain number of account to update + int accountNumber = getAccount("Enter account to update"); + + // move file-position pointer to correct record in file + updateFile.seekg((accountNumber - 1) * sizeof(ClientData)); + + // read first record from file + ClientData client; + updateFile.read(reinterpret_cast<char *> (&client), sizeof(ClientData)); + + // update record + if (client.getAccountNumber() != 0) { + outputLine(cout, client); // display the record + + // request user to specify the transaction + cout << "\nEnter charge (+) or payment (-): "; + double transaction; // char or payment + cin >> transaction; + + // update record balance + double oldBalance = client.getBalance(); + client.setBalance(oldBalance + transaction); + outputLine(cout, client); // display the record + + // move file-position pointer to correct record in file + updateFile.seekp((accountNumber - 1) * sizeof(ClientData)); + + // write updated record over old record in file + updateFile.write(reinterpret_cast<const char *> (&client), sizeof(ClientData)); + } else { // display error if account does not exist + cerr << "Account #" << accountNumber + << " has no information." << endl; + } +} +// create and insert record + +void newRecord(fstream &insertInFile) { + // obtain number of accounts to create + int accountNumber = getAccount("Enter new account number"); + + // move file-position pointer to correct record in file + insertInFile.seekg((accountNumber - 1) * sizeof(ClientData)); + + // read record from file + ClientData client; + insertInFile.read(reinterpret_cast<char *> (&client), sizeof(ClientData)); + + // create record, if record does not previously exist + if (client.getAccountNumber() == 0) { + string lastName; + string firstName; + double balance; + int branchId; + + // user enters last name, first name, and balance + cout << "Enter lastname, firstname, balance, branchid\n? "; + cin >> setw(15) >> lastName; + cin >> setw(10) >> firstName; + cin >> balance; + cin >> branchId; + + // user values to populate account values + client.setLastName(lastName); + client.setFirstName(firstName); + client.setBalance(balance); + client.setAccountNumber(accountNumber); + client.setBranchID(branchId); + + // move file-position pointer to correct record in file + insertInFile.seekp((accountNumber - 1) * sizeof(ClientData)); + + // insert record in file + insertInFile.write(reinterpret_cast<const char *> (&client), sizeof(ClientData)); + } else { // display error if account already exists + cerr << "Account #" << accountNumber << " already contains information." << endl; + } +} +// delete an existing record + +void deleteRecord(fstream &deleteFromFile) { + // obtain number of account to delete + int accountNumber = getAccount("Enter account to delete"); + + // move file-position pointer to correct record in file + deleteFromFile.seekg((accountNumber - 1) * sizeof(ClientData)); + + // read record from file + ClientData client; + deleteFromFile.read(reinterpret_cast<char *> (&client), sizeof(ClientData)); + + // delete record, if record exists in file + if (client.getAccountNumber() != 0) { + ClientData blankClient; // create blank record + + // move file-position pointer to correct record in file + deleteFromFile.seekp((accountNumber - 1) * sizeof(ClientData)); + + // replace existing record with blank record + deleteFromFile.write(reinterpret_cast<const char *> (&blankClient), sizeof(ClientData)); + + cout << "Account #" << accountNumber << " deleted.\n"; + } else { // display error if record does not exist + cerr << "Account #" << accountNumber << " is empty.\n"; + } +} +// display single record + +void outputLine(ostream &output, const ClientData &record) { + output << left << setw(10) << record.getAccountNumber() + << setw(16) << record.getLastName() + << setw(11) << record.getFirstName() + << setw(10) << setprecision(2) << right << fixed + << showpoint << record.getBalance() + << left << setw(10) << record.getBranchID() << endl; +} +// obtain account number value from user + +int getAccount(const char *const prompt) { + int accountNumber; + + // obtain account number value + do { + cout << prompt << " ( 1 - 100 ): "; + cin >> accountNumber; + } while (accountNumber < 1 || accountNumber > 100); + + return accountNumber; +} diff --git a/pool/shard007/C++/0092492_morse_gpu.cpp b/pool/shard007/C++/0092492_morse_gpu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..96636128db729f52afa9a28f380e0f8ddb2ba4f9 --- /dev/null +++ b/pool/shard007/C++/0092492_morse_gpu.cpp @@ -0,0 +1,122 @@ +/* ---------------------------------------------------------------------- + LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator + http://lammps.sandia.gov, Sandia National Laboratories + Steve Plimpton, sjplimp@sandia.gov + + Copyright (2003) Sandia Corporation. Under the terms of Contract + DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains + certain rights in this software. This software is distributed under + the GNU General Public License. + + See the README file in the top-level LAMMPS directory. +------------------------------------------------------------------------- */ + +/* ---------------------------------------------------------------------- + Contributing authors: Mike Brown (ORNL), brownw@ornl.gov +------------------------------------------------------------------------- */ + +#include <iostream> +#include <cassert> +#include <math.h> + +#include "morse_gpu_memory.h" + +using namespace std; + +static MOR_GPU_Memory<PRECISION,ACC_PRECISION> MORMF; + +// --------------------------------------------------------------------------- +// Allocate memory on host and device and copy constants to device +// --------------------------------------------------------------------------- +int mor_gpu_init(const int ntypes, double **cutsq, + double **host_lj1, double **host_lj2, double **host_lj3, + double **host_lj4, double **offset, double *special_lj, + const int inum, const int nall, const int max_nbors, + const int maxspecial, const double cell_size, int &gpu_mode, + FILE *screen) { + MORMF.clear(); + gpu_mode=MORMF.device->gpu_mode(); + double gpu_split=MORMF.device->particle_split(); + int first_gpu=MORMF.device->first_device(); + int last_gpu=MORMF.device->last_device(); + int world_me=MORMF.device->world_me(); + int gpu_rank=MORMF.device->gpu_rank(); + int procs_per_gpu=MORMF.device->procs_per_gpu(); + + MORMF.device->init_message(screen,"morse",first_gpu,last_gpu); + + bool message=false; + if (MORMF.device->replica_me()==0 && screen) + message=true; + + if (message) { + fprintf(screen,"Initializing GPU and compiling on process 0..."); + fflush(screen); + } + + int init_ok=0; + if (world_me==0) + init_ok=MORMF.init(ntypes, cutsq, host_lj1, host_lj2, host_lj3, + host_lj4, offset, special_lj, inum, nall, 300, + maxspecial, cell_size, gpu_split, screen); + + MORMF.device->world_barrier(); + if (message) + fprintf(screen,"Done.\n"); + + for (int i=0; i<procs_per_gpu; i++) { + if (message) { + if (last_gpu-first_gpu==0) + fprintf(screen,"Initializing GPU %d on core %d...",first_gpu,i); + else + fprintf(screen,"Initializing GPUs %d-%d on core %d...",first_gpu, + last_gpu,i); + fflush(screen); + } + if (gpu_rank==i && world_me!=0) + init_ok=MORMF.init(ntypes, cutsq, host_lj1, host_lj2, host_lj3, host_lj4, + offset, special_lj, inum, nall, 300, maxspecial, + cell_size, gpu_split, screen); + + MORMF.device->gpu_barrier(); + if (message) + fprintf(screen,"Done.\n"); + } + if (message) + fprintf(screen,"\n"); + + if (init_ok==0) + MORMF.estimate_gpu_overhead(); + return init_ok; +} + +void mor_gpu_clear() { + MORMF.clear(); +} + +int** mor_gpu_compute_n(const int ago, const int inum_full, + const int nall, double **host_x, int *host_type, + double *sublo, double *subhi, int *tag, int **nspecial, + int **special, const bool eflag, const bool vflag, + const bool eatom, const bool vatom, int &host_start, + int **ilist, int **jnum, const double cpu_time, + bool &success) { + return MORMF.compute(ago, inum_full, nall, host_x, host_type, sublo, + subhi, tag, nspecial, special, eflag, vflag, eatom, + vatom, host_start, ilist, jnum, cpu_time, success); +} + +void mor_gpu_compute(const int ago, const int inum_full, const int nall, + double **host_x, int *host_type, int *ilist, int *numj, + int **firstneigh, const bool eflag, const bool vflag, + const bool eatom, const bool vatom, int &host_start, + const double cpu_time, bool &success) { + MORMF.compute(ago,inum_full,nall,host_x,host_type,ilist,numj, + firstneigh,eflag,vflag,eatom,vatom,host_start,cpu_time,success); +} + +double mor_gpu_bytes() { + return MORMF.host_memory_usage(); +} + + diff --git a/pool/shard007/C++/0092493_preload_request.cc b/pool/shard007/C++/0092493_preload_request.cc new file mode 100644 index 0000000000000000000000000000000000000000..9e5e2f5e02fed921b03bb8c46dc059f327151ce7 --- /dev/null +++ b/pool/shard007/C++/0092493_preload_request.cc @@ -0,0 +1,165 @@ +// 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. + +#include "third_party/blink/renderer/core/html/parser/preload_request.h" + +#include "third_party/blink/public/common/features.h" +#include "third_party/blink/renderer/core/dom/document.h" +#include "third_party/blink/renderer/core/frame/local_dom_window.h" +#include "third_party/blink/renderer/core/frame/local_frame.h" +#include "third_party/blink/renderer/core/frame/settings.h" +#include "third_party/blink/renderer/core/loader/document_loader.h" +#include "third_party/blink/renderer/core/loader/preload_helper.h" +#include "third_party/blink/renderer/core/script/document_write_intervention.h" +#include "third_party/blink/renderer/core/script/script_loader.h" +#include "third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h" +#include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_info.h" +#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h" +#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h" +#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h" +#include "third_party/blink/renderer/platform/network/network_state_notifier.h" +#include "third_party/blink/renderer/platform/weborigin/security_policy.h" + +namespace blink { + +PreloadRequest::ExclusionInfo::ExclusionInfo(const KURL& document_url, + HashSet<KURL> scopes, + HashSet<KURL> resources) + : document_url_(document_url), + scopes_(std::move(scopes)), + resources_(std::move(resources)) {} + +PreloadRequest::ExclusionInfo::~ExclusionInfo() = default; + +bool PreloadRequest::ExclusionInfo::ShouldExclude( + const KURL& base_url, + const String& resource_url) const { + if (resources_.IsEmpty() && scopes_.IsEmpty()) + return false; + KURL url = KURL(base_url.IsEmpty() ? document_url_ : base_url, resource_url); + if (resources_.Contains(url)) + return true; + for (const auto& scope : scopes_) { + if (url.GetString().StartsWith(scope.GetString())) + return true; + } + return false; +} + +KURL PreloadRequest::CompleteURL(Document* document) { + if (!base_url_.IsEmpty()) + return document->CompleteURLWithOverride(resource_url_, base_url_); + return document->CompleteURL(resource_url_); +} + +// static +std::unique_ptr<PreloadRequest> PreloadRequest::CreateIfNeeded( + const String& initiator_name, + const TextPosition& initiator_position, + const String& resource_url, + const KURL& base_url, + ResourceType resource_type, + const network::mojom::ReferrerPolicy referrer_policy, + ResourceFetcher::IsImageSet is_image_set, + const ExclusionInfo* exclusion_info, + const FetchParameters::ResourceWidth& resource_width, + const ClientHintsPreferences& client_hints_preferences, + RequestType request_type) { + // Never preload data URLs. We also disallow relative ref URLs which become + // data URLs if the document's URL is a data URL. We don't want to create + // extra resource requests with data URLs to avoid copy / initialization + // overhead, which can be significant for large URLs. + if (resource_url.IsEmpty() || resource_url.StartsWith("#") || + ProtocolIs(resource_url, "data")) { + return nullptr; + } + + if (exclusion_info && exclusion_info->ShouldExclude(base_url, resource_url)) + return nullptr; + + return base::WrapUnique(new PreloadRequest( + initiator_name, initiator_position, resource_url, base_url, resource_type, + resource_width, client_hints_preferences, request_type, referrer_policy, + is_image_set)); +} + +Resource* PreloadRequest::Start(Document* document) { + DCHECK(document->domWindow()); + + FetchInitiatorInfo initiator_info; + initiator_info.name = AtomicString(initiator_name_); + initiator_info.position = initiator_position_; + + const KURL& url = CompleteURL(document); + // Data URLs are filtered out in the preload scanner. + DCHECK(!url.ProtocolIsData()); + + ResourceRequest resource_request(url); + resource_request.SetReferrerPolicy(referrer_policy_); + + resource_request.SetRequestContext( + ResourceFetcher::DetermineRequestContext(resource_type_, is_image_set_)); + resource_request.SetRequestDestination( + ResourceFetcher::DetermineRequestDestination(resource_type_)); + + resource_request.SetFetchImportanceMode(importance_); + + if (resource_type_ == ResourceType::kImage && url.ProtocolIsInHTTPFamily() && + base::FeatureList::IsEnabled(blink::features::kSubresourceRedirect) && + blink::GetNetworkStateNotifier().SaveDataEnabled()) { + resource_request.SetPreviewsState(resource_request.GetPreviewsState() | + PreviewsTypes::kSubresourceRedirectOn); + } + + ResourceLoaderOptions options(document->domWindow()->GetCurrentWorld()); + options.initiator_info = initiator_info; + FetchParameters params(std::move(resource_request), options); + + auto* origin = document->domWindow()->GetSecurityOrigin(); + if (script_type_ == mojom::blink::ScriptType::kModule) { + DCHECK_EQ(resource_type_, ResourceType::kScript); + params.SetCrossOriginAccessControl( + origin, ScriptLoader::ModuleScriptCredentialsMode(cross_origin_)); + params.SetModuleScript(); + } else if (cross_origin_ != kCrossOriginAttributeNotSet) { + params.SetCrossOriginAccessControl(origin, cross_origin_); + } + + params.SetDefer(defer_); + params.SetResourceWidth(resource_width_); + params.GetClientHintsPreferences().UpdateFrom(client_hints_preferences_); + params.SetIntegrityMetadata(integrity_metadata_); + params.SetContentSecurityPolicyNonce(nonce_); + params.SetParserDisposition(kParserInserted); + + if (request_type_ == kRequestTypeLinkRelPreload) + params.SetLinkPreload(true); + + if (script_type_ == mojom::blink::ScriptType::kModule) { + DCHECK_EQ(resource_type_, ResourceType::kScript); + params.SetDecoderOptions(TextResourceDecoderOptions::CreateUTF8Decode()); + } else if (resource_type_ == ResourceType::kScript || + resource_type_ == ResourceType::kCSSStyleSheet) { + params.SetCharset(charset_.IsEmpty() ? document->Encoding() + : WTF::TextEncoding(charset_)); + } + FetchParameters::SpeculativePreloadType speculative_preload_type = + FetchParameters::SpeculativePreloadType::kInDocument; + if (from_insertion_scanner_) { + speculative_preload_type = + FetchParameters::SpeculativePreloadType::kInserted; + } + params.SetSpeculativePreloadType(speculative_preload_type); + + if (resource_type_ == ResourceType::kScript) { + // We intentionally ignore the returned value, because we don't resend + // the async request to the blocked script here. + MaybeDisallowFetchForDocWrittenScript(params, *document); + } + params.SetRenderBlockingBehavior(render_blocking_behavior_); + + return PreloadHelper::StartPreload(resource_type_, params, *document); +} + +} // namespace blink diff --git a/pool/shard007/C++/0092498_AnalogControl.cpp b/pool/shard007/C++/0092498_AnalogControl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2beeb46408eb1cdd64ca4ff222894352daae4d51 --- /dev/null +++ b/pool/shard007/C++/0092498_AnalogControl.cpp @@ -0,0 +1,64 @@ +#include "AnalogControl.hpp" + +#include <math.h> /* log10 */ + +namespace talorion { + + AnalogControl::AnalogControl(QString unit, int decimals, QWidget *par) : + QDoubleSpinBox(par) + { + setup(0, 999, unit, decimals); + } + + AnalogControl::AnalogControl(int min, int max, QString unit, QWidget *par): + QDoubleSpinBox(par) + { + setup(min, max, unit, 0); + } + + void AnalogControl::setValue(double val) + { + if(hasFocus()) + return; + + auto rounded_f = static_cast<float>(val); + auto rounded_d = static_cast<double>(rounded_f); + + QDoubleSpinBox::setValue(rounded_d); + } + + void AnalogControl::setup(int min, int max, QString unit, int dec) + { + setButtonSymbols(QDoubleSpinBox::NoButtons); + setAlignment(Qt::AlignRight); + + setMinimum(min); + setMaximum(max); + + if(!unit.isNull()){ + setSuffix(" " + unit); + } + + if ((minimum()) > 1 && log10((maximum()))<=6) + setDecimals(6-log10((maximum()))); + + setSingleStep(max/150.0); + + if(decimals() < dec) + setDecimals(dec); + + } + + void AnalogControl::enterEvent(QEvent *event) + { + emit entered(); + QDoubleSpinBox::enterEvent(event); + } + + void AnalogControl::leaveEvent(QEvent *event) + { + emit left(); + QDoubleSpinBox::enterEvent(event); + } + +} // namespace talorion diff --git a/pool/shard007/C++/0092499_RTPFile.cc b/pool/shard007/C++/0092499_RTPFile.cc new file mode 100644 index 0000000000000000000000000000000000000000..e340e828bd61eb7200342b1559b61cff2e0f0167 --- /dev/null +++ b/pool/shard007/C++/0092499_RTPFile.cc @@ -0,0 +1,240 @@ +/* + * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +#include "RTPFile.h" + +#include <stdlib.h> +#include <limits> + +#ifdef WIN32 +#include <Winsock2.h> +#else +#include <arpa/inet.h> +#endif + +#include BOSS_WEBRTC_U_modules__include__module_common_types_h //original-code:"modules/include/module_common_types.h" +// TODO(tlegrand): Consider removing usage of gtest. +#include "test/gtest.h" + +namespace webrtc { + +void RTPStream::ParseRTPHeader(WebRtcRTPHeader* rtpInfo, + const uint8_t* rtpHeader) { + rtpInfo->header.payloadType = rtpHeader[1]; + rtpInfo->header.sequenceNumber = + (static_cast<uint16_t>(rtpHeader[2]) << 8) | rtpHeader[3]; + rtpInfo->header.timestamp = (static_cast<uint32_t>(rtpHeader[4]) << 24) | + (static_cast<uint32_t>(rtpHeader[5]) << 16) | + (static_cast<uint32_t>(rtpHeader[6]) << 8) | + rtpHeader[7]; + rtpInfo->header.ssrc = (static_cast<uint32_t>(rtpHeader[8]) << 24) | + (static_cast<uint32_t>(rtpHeader[9]) << 16) | + (static_cast<uint32_t>(rtpHeader[10]) << 8) | + rtpHeader[11]; +} + +void RTPStream::MakeRTPheader(uint8_t* rtpHeader, + uint8_t payloadType, + int16_t seqNo, + uint32_t timeStamp, + uint32_t ssrc) { + rtpHeader[0] = 0x80; + rtpHeader[1] = payloadType; + rtpHeader[2] = (seqNo >> 8) & 0xFF; + rtpHeader[3] = seqNo & 0xFF; + rtpHeader[4] = timeStamp >> 24; + rtpHeader[5] = (timeStamp >> 16) & 0xFF; + rtpHeader[6] = (timeStamp >> 8) & 0xFF; + rtpHeader[7] = timeStamp & 0xFF; + rtpHeader[8] = ssrc >> 24; + rtpHeader[9] = (ssrc >> 16) & 0xFF; + rtpHeader[10] = (ssrc >> 8) & 0xFF; + rtpHeader[11] = ssrc & 0xFF; +} + +RTPPacket::RTPPacket(uint8_t payloadType, + uint32_t timeStamp, + int16_t seqNo, + const uint8_t* payloadData, + size_t payloadSize, + uint32_t frequency) + : payloadType(payloadType), + timeStamp(timeStamp), + seqNo(seqNo), + payloadSize(payloadSize), + frequency(frequency) { + if (payloadSize > 0) { + this->payloadData = new uint8_t[payloadSize]; + memcpy(this->payloadData, payloadData, payloadSize); + } +} + +RTPPacket::~RTPPacket() { + delete[] payloadData; +} + +RTPBuffer::RTPBuffer() { + _queueRWLock = RWLockWrapper::CreateRWLock(); +} + +RTPBuffer::~RTPBuffer() { + delete _queueRWLock; +} + +void RTPBuffer::Write(const uint8_t payloadType, + const uint32_t timeStamp, + const int16_t seqNo, + const uint8_t* payloadData, + const size_t payloadSize, + uint32_t frequency) { + RTPPacket* packet = new RTPPacket(payloadType, timeStamp, seqNo, payloadData, + payloadSize, frequency); + _queueRWLock->AcquireLockExclusive(); + _rtpQueue.push(packet); + _queueRWLock->ReleaseLockExclusive(); +} + +size_t RTPBuffer::Read(WebRtcRTPHeader* rtpInfo, + uint8_t* payloadData, + size_t payloadSize, + uint32_t* offset) { + _queueRWLock->AcquireLockShared(); + RTPPacket* packet = _rtpQueue.front(); + _rtpQueue.pop(); + _queueRWLock->ReleaseLockShared(); + rtpInfo->header.markerBit = 1; + rtpInfo->header.payloadType = packet->payloadType; + rtpInfo->header.sequenceNumber = packet->seqNo; + rtpInfo->header.ssrc = 0; + rtpInfo->header.timestamp = packet->timeStamp; + if (packet->payloadSize > 0 && payloadSize >= packet->payloadSize) { + memcpy(payloadData, packet->payloadData, packet->payloadSize); + } else { + return 0; + } + *offset = (packet->timeStamp / (packet->frequency / 1000)); + + return packet->payloadSize; +} + +bool RTPBuffer::EndOfFile() const { + _queueRWLock->AcquireLockShared(); + bool eof = _rtpQueue.empty(); + _queueRWLock->ReleaseLockShared(); + return eof; +} + +void RTPFile::Open(const char* filename, const char* mode) { + if ((_rtpFile = fopen(filename, mode)) == NULL) { + printf("Cannot write file %s.\n", filename); + ADD_FAILURE() << "Unable to write file"; + exit(1); + } +} + +void RTPFile::Close() { + if (_rtpFile != NULL) { + fclose(_rtpFile); + _rtpFile = NULL; + } +} + +void RTPFile::WriteHeader() { + // Write data in a format that NetEQ and RTP Play can parse + fprintf(_rtpFile, "#!RTPencode%s\n", "1.0"); + uint32_t dummy_variable = 0; + // should be converted to network endian format, but does not matter when 0 + EXPECT_EQ(1u, fwrite(&dummy_variable, 4, 1, _rtpFile)); + EXPECT_EQ(1u, fwrite(&dummy_variable, 4, 1, _rtpFile)); + EXPECT_EQ(1u, fwrite(&dummy_variable, 4, 1, _rtpFile)); + EXPECT_EQ(1u, fwrite(&dummy_variable, 2, 1, _rtpFile)); + EXPECT_EQ(1u, fwrite(&dummy_variable, 2, 1, _rtpFile)); + fflush(_rtpFile); +} + +void RTPFile::ReadHeader() { + uint32_t start_sec, start_usec, source; + uint16_t port, padding; + char fileHeader[40]; + EXPECT_TRUE(fgets(fileHeader, 40, _rtpFile) != 0); + EXPECT_EQ(1u, fread(&start_sec, 4, 1, _rtpFile)); + start_sec = ntohl(start_sec); + EXPECT_EQ(1u, fread(&start_usec, 4, 1, _rtpFile)); + start_usec = ntohl(start_usec); + EXPECT_EQ(1u, fread(&source, 4, 1, _rtpFile)); + source = ntohl(source); + EXPECT_EQ(1u, fread(&port, 2, 1, _rtpFile)); + port = ntohs(port); + EXPECT_EQ(1u, fread(&padding, 2, 1, _rtpFile)); + padding = ntohs(padding); +} + +void RTPFile::Write(const uint8_t payloadType, + const uint32_t timeStamp, + const int16_t seqNo, + const uint8_t* payloadData, + const size_t payloadSize, + uint32_t frequency) { + /* write RTP packet to file */ + uint8_t rtpHeader[12]; + MakeRTPheader(rtpHeader, payloadType, seqNo, timeStamp, 0); + ASSERT_LE(12 + payloadSize + 8, std::numeric_limits<u_short>::max()); + uint16_t lengthBytes = htons(static_cast<u_short>(12 + payloadSize + 8)); + uint16_t plen = htons(static_cast<u_short>(12 + payloadSize)); + uint32_t offsetMs; + + offsetMs = (timeStamp / (frequency / 1000)); + offsetMs = htonl(offsetMs); + EXPECT_EQ(1u, fwrite(&lengthBytes, 2, 1, _rtpFile)); + EXPECT_EQ(1u, fwrite(&plen, 2, 1, _rtpFile)); + EXPECT_EQ(1u, fwrite(&offsetMs, 4, 1, _rtpFile)); + EXPECT_EQ(1u, fwrite(&rtpHeader, 12, 1, _rtpFile)); + EXPECT_EQ(payloadSize, fwrite(payloadData, 1, payloadSize, _rtpFile)); +} + +size_t RTPFile::Read(WebRtcRTPHeader* rtpInfo, + uint8_t* payloadData, + size_t payloadSize, + uint32_t* offset) { + uint16_t lengthBytes; + uint16_t plen; + uint8_t rtpHeader[12]; + size_t read_len = fread(&lengthBytes, 2, 1, _rtpFile); + /* Check if we have reached end of file. */ + if ((read_len == 0) && feof(_rtpFile)) { + _rtpEOF = true; + return 0; + } + EXPECT_EQ(1u, fread(&plen, 2, 1, _rtpFile)); + EXPECT_EQ(1u, fread(offset, 4, 1, _rtpFile)); + lengthBytes = ntohs(lengthBytes); + plen = ntohs(plen); + *offset = ntohl(*offset); + EXPECT_GT(plen, 11); + + EXPECT_EQ(1u, fread(rtpHeader, 12, 1, _rtpFile)); + ParseRTPHeader(rtpInfo, rtpHeader); + EXPECT_EQ(lengthBytes, plen + 8); + + if (plen == 0) { + return 0; + } + if (lengthBytes < 20) { + return 0; + } + if (payloadSize < static_cast<size_t>((lengthBytes - 20))) { + return 0; + } + lengthBytes -= 20; + EXPECT_EQ(lengthBytes, fread(payloadData, 1, lengthBytes, _rtpFile)); + return lengthBytes; +} + +} // namespace webrtc diff --git a/pool/shard007/C++/0092502_qlandmarkabstractrequest.cpp b/pool/shard007/C++/0092502_qlandmarkabstractrequest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..afc97f43b4cb50bfa52b6f236b2e01da7c95cb23 --- /dev/null +++ b/pool/shard007/C++/0092502_qlandmarkabstractrequest.cpp @@ -0,0 +1,428 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ +#include "qlandmarkabstractrequest.h" +#include "qlandmarkabstractrequest_p.h" +#include "qlandmarkmanagerengine.h" +#include "qlandmarkmanager_p.h" +#include <QDebug> +#include <QMutexLocker> + +QTM_USE_NAMESPACE + +QLandmarkAbstractRequestPrivate::QLandmarkAbstractRequestPrivate(QLandmarkManager *mgr) + : type(QLandmarkAbstractRequest::InvalidRequest), + state(QLandmarkAbstractRequest::InactiveState), + error(QLandmarkManager::NoError), + errorString(QString()), + manager(mgr) +{ +} + +/*! + \class QLandmarkAbstractRequest + \brief The QLandmarkAbstractRequest class provides the interface + from which all asynchronous request classes inherit. + + + \inmodule QtLocation + \since 1.1 + + \ingroup landmarks-request + + It allows a client to asynchronously request some functionality of a + particular QLandmarkManager. Instances of the class will emit signals when + the state of the request changes, or when more results become available. + + Clients should not attempt to create instances of this class directly, but + should instead use the use-case-specific classes derived from this class. + + All such request classes have a similar interface: clients set the + parameters of the asynchronous call, then call the start() slot of the request. The manager + will then enqueue or begin to process the request, at which point the + request's state will transition from the \c InactiveState to \c ActiveState. + After any state transition, the request will emit the stateChanged() + signal. The manager may (if it supports it) + periodically update the request with results, at + which point the request will emit the resultsAvailable() signal. These + results are not guaranteed to have a stable ordering. Error information is + considered a result, so some requests will emit the resultsAvailable() + signal even if no results are possible from the request (for example, a + landmark remove request) when the manager updates the request with + information about any errors which may have occurred. + + Clients can choose which signals they wish to handle from a request. If the + client is not interested in interim results, they can choose to handle only + the stateChanged() signal, and in the slot to which that signal is + connected, check whether the state has changed to the \c FinishedState + (which signifies that the manager has finished handling the request, and + that the request will not be updated with any more results). If the client + is not interested in any results (including error information), they may + choose to delete the request after calling \l start(), or simply may not + connect the the request's signals to any slots. (Please see the note + below if you are working on Symbian with QtMobility 1.1.0) + + If the request is allocated via operator new, the client must delete the + request when they are no longer using it in order to avoid leaking memory. + That is, the client retains ownership of the request. + + The client may delete a heap-allocated request in various ways: by deleting + it directly (but not within a slot connected to a signal emitted by the + request), or by using the deleteLater() slot to schedule the request for + deletion when control returns to the event loop (from within a slot + connected to a signal emitted by the request, for example \l + stateChanged()). + + An active request may be deleted by the client, but the client will + not receive notifications about whether the request succeeded or not, + nor the results of the request. + + Because clients retain ownership of any request object, and may delete a + request object at any time, the manager engine, implementers must be + careful to ensue that they do not assume that a request has not been + deleted at some time point during processing of a request, particularly + if the engine has a multithreaded implementation. +*/ + +QLandmarkAbstractRequestPrivate::~QLandmarkAbstractRequestPrivate() +{ +} + +void QLandmarkAbstractRequestPrivate::notifyEngine(QLandmarkAbstractRequest* request) +{ + Q_ASSERT(request); + QLandmarkAbstractRequestPrivate* d = request->d_ptr; + if (d) { + QMutexLocker ml(&d->mutex); + QLandmarkManagerEngine *engine = QLandmarkManagerPrivate::getEngine(d->manager); + ml.unlock(); + if (engine) { + engine->requestDestroyed(request); + } + } +} + +/*! + \enum QLandmarkAbstractRequest::RequestType + Defines the possible types of asynchronous requests. + \value InvalidRequest An invalid request + \value LandmarkIdFetchRequest A request to fetch a list of landmark + identifiers. + \value CategoryIdFetchRequest A request to fetch a list of catgory + identifiers. + + \value LandmarkFetchRequest A request to fetch a list of landmarks + \value LandmarkFetchByIdRequest A request to fetch a list of landmarks by id. + \value CategoryFetchRequest A request to fetch a list of categories + \value CategoryFetchByIdRequest A request to fetch a list of categories by id + \value LandmarkSaveRequest A request to save a list of landmarks. + \value LandmarkRemoveRequest A request to remove a list of landmarks. + \value CategorySaveRequest A request to save a list of categories. + \value CategoryRemoveRequest A request to remove a list of categories. + \value ImportRequest A request import landmarks. + \value ExportRequest A request export landmarks. +*/ + +/*! + \enum QLandmarkAbstractRequest::State + Defines the possible states of asynchronous requests. + \value InactiveState Operation not yet started. + \value ActiveState Operation started, not yet finished. + \value FinishedState Operation completed. (Can be mean either successful or + unsuccessful completion). +*/ + +/*! + Constructs a new, invalid asynchronous request with the given \a manager and \a parent. +*/ +QLandmarkAbstractRequest::QLandmarkAbstractRequest(QLandmarkManager *manager, QObject *parent) + : QObject(parent), + d_ptr(new QLandmarkAbstractRequestPrivate(manager)) +{ +} + +/*! + \internal +*/ +QLandmarkAbstractRequest::QLandmarkAbstractRequest(QLandmarkAbstractRequestPrivate *dd, QObject *parent) + : QObject(parent), + d_ptr(dd) +{ +} + +/*! + Destroys the asynchronous request. Because the request object is effectiely a handle to a + request operation, the operation may continue or it may just be canceled, depending upon + the enine implementation, even though the request itself has been destroyed. + The sqlite engine continues the operation behind the scenes if the + request is destroyed whilst active. For the symbian engine see the note below. +*/ +QLandmarkAbstractRequest::~QLandmarkAbstractRequest() +{ + QLandmarkAbstractRequestPrivate::notifyEngine(this); + delete d_ptr; +} + +/*! + Returns the type of this asynchronous request. +*/ +QLandmarkAbstractRequest::RequestType QLandmarkAbstractRequest::type() const +{ + QMutexLocker ml(&d_ptr->mutex); + return d_ptr->type; +} + +/*! + Returns the state of the request +*/ +QLandmarkAbstractRequest::State QLandmarkAbstractRequest::state() +{ + QMutexLocker ml(&d_ptr->mutex); + return d_ptr->state; +} + +/*! + Returns true if the request is in the \c QLandmarkAbstractRequest::Inactive state; + otherwise, returns false. + \sa state() +*/ +bool QLandmarkAbstractRequest::isInactive() const +{ + QMutexLocker ml(&d_ptr->mutex); + return d_ptr->state == QLandmarkAbstractRequest::InactiveState; +} + +/*! + Returns true if the request is in the \c QLandmarkAbstractRequest::Active state; + otherwise, returns false. + \sa state() +*/ +bool QLandmarkAbstractRequest::isActive() const +{ + QMutexLocker ml(&d_ptr->mutex); + return d_ptr->state == QLandmarkAbstractRequest::ActiveState; +} + +/*! + Returns true if the request is in the \c QLandmarkAbstractRequest::Finished state; + otherwise, returns false. + \sa state() +*/ +bool QLandmarkAbstractRequest::isFinished() const +{ + QMutexLocker ml(&d_ptr->mutex); + return d_ptr->state == QLandmarkAbstractRequest::FinishedState; +} + +/*! + Returns the overall error of the most recent asynchronous operation. + \sa errorString() +*/ +QLandmarkManager::Error QLandmarkAbstractRequest::error() const +{ + QMutexLocker ml(&d_ptr->mutex); + return d_ptr->error; +} + +/*! + Returns a human readable string of the last error + that occurred. This error string is intended to be used + by developers only and should not be seen by end users. + \sa error() +*/ +QString QLandmarkAbstractRequest::errorString() const +{ + QMutexLocker ml(&d_ptr->mutex); + return d_ptr->errorString; +} + +/*! + Returns a pointer to the landmark manager which + this request operates on. +*/ +QLandmarkManager *QLandmarkAbstractRequest::manager() const +{ + QMutexLocker ml(&d_ptr->mutex); + return d_ptr->manager; +} + +/*! + Sets the \a manager which this request operates on. + + Note that if a NULL manager is set, the functions + start(), cancel() and waitForFinished() will return false and + error will be set to QLandmarkManager::InvalidManagerError. + + A manager cannot be assigned while the request is in the + QLandmarkAbstractRequest::ActiveState. +*/ +void QLandmarkAbstractRequest::setManager(QLandmarkManager *manager) +{ + QMutexLocker ml(&d_ptr->mutex); + if (d_ptr->state == QLandmarkAbstractRequest::ActiveState && d_ptr->manager) + return; + d_ptr->manager = manager; +} + +/*! + Attempts to start the request. + + Returns true if the request was started, otherwise false. Trying to start a + request that is already active returns false. + \sa cancel(). +*/ +bool QLandmarkAbstractRequest::start() +{ + QMutexLocker ml(&d_ptr->mutex); + if (!d_ptr->manager) { + d_ptr->error = QLandmarkManager::BadArgumentError; + d_ptr->errorString = "No manager assigned to landmark request object"; + qWarning() << d_ptr->errorString; + return false; + } + QLandmarkManagerEngine *engine = d_ptr->manager->engine(); + if (!engine) { + d_ptr->error = QLandmarkManager::InvalidManagerError; + d_ptr->errorString = "The manager is invalid"; + return false; + } + + if (d_ptr->state != QLandmarkAbstractRequest::ActiveState) { + ml.unlock(); + return engine->startRequest(this); + } + else { + return false; + } +} + +/*! + Notifies the request that it should be canceled. + + Returns true if the request was successfully notified + that it should be canceled. The request may or may not honor + the cancel notification. Returns false if the notification + could not be made or the request is not in the + QLandmarkManager::Active state. + + \sa start() +*/ +bool QLandmarkAbstractRequest::cancel() +{ + QMutexLocker ml(&d_ptr->mutex); + if (!d_ptr->manager) { + d_ptr->error = QLandmarkManager::BadArgumentError; + d_ptr->errorString = "No manager assigned to landmark request object"; + qWarning() << d_ptr->errorString; + return false; + } + QLandmarkManagerEngine *engine = d_ptr->manager->engine(); + + if(d_ptr->state == QLandmarkAbstractRequest::ActiveState) { + ml.unlock(); + return engine->cancelRequest(this); + } + else + return false; +} + +/*! + Blocks until the request has been completed or until \a msecs milliseconds + has elapsed. If \a msecs is zero or negative, this function will block indefinitely. + + Returns true if the request was canceled or completed + within the given period, otherwise returns false. Some backends may be unable + to support this operation safely and will return false immediately. + + (Note: This function is not supported for an import request + with the symbian manager which always returns false. As of + Qt Mobility 1.1.1 waitForFinished() is supported using the sqlite manager). + + Note that any signals generated while waiting for the request to be complete + may be queued and delivered sometime after this function has returned, when + the calling thread's event loop is dispatched. If your code depends on + your slots being invoked, you may need to process events after calling + this function. +*/ +bool QLandmarkAbstractRequest::waitForFinished(int msecs) +{ + + QMutexLocker ml(&d_ptr->mutex); + if (!d_ptr->manager) { + d_ptr->error = QLandmarkManager::BadArgumentError; + d_ptr->errorString = "No manager assigned to landmark request object"; + qWarning() << d_ptr->errorString; + return false; + } + QLandmarkManagerEngine *engine = d_ptr->manager->engine(); + + switch(d_ptr->state) { + case QLandmarkAbstractRequest::ActiveState: + ml.unlock(); + return engine->waitForRequestFinished(this, msecs); + case QLandmarkAbstractRequest::FinishedState: + return true; + default: + return false; + } +} + +/*! + \fn void QLandmarkAbstractRequest::resultsAvailable() + This signal is emitted when new results are available. Results + can include the operation error which may be accessed via error(), + or derived-class specific results which are accessible through + the derived class API. + + \sa error() +*/ + +/*! + \fn void QLandmarkAbstractRequest::stateChanged(QLandmarkAbstractRequest::State newState) + This signal is emitted when the state of the request is changed. The new state of + the request will be contained in \a newState. +*/ + +#include "moc_qlandmarkabstractrequest.cpp" + + + + + diff --git a/pool/shard007/C++/0092511_euler.cc b/pool/shard007/C++/0092511_euler.cc new file mode 100644 index 0000000000000000000000000000000000000000..bff93ac20ffa1a8cb238e761ad14eb97a2e2fae5 --- /dev/null +++ b/pool/shard007/C++/0092511_euler.cc @@ -0,0 +1,69 @@ +/* + euler.cc + + + RELACS - Relaxed ELectrophysiological data Acquisition, Control, and Stimulation + Copyright (C) 2002-2015 Jan Benda <jan.benda@uni-tuebingen.de> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + RELACS is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include <cmath> +#include <iostream> +#include <vector> +#include <relacs/odealgorithm.h> +using namespace std; +using namespace relacs; + + +typedef vector< double > dvector; +typedef vector< dvector > dmatrix; + +class LinearFirstOrder +{ +public: + LinearFirstOrder( void ) : Tau( 1.0 ) {}; + LinearFirstOrder( double tau ) : Tau( tau ) {}; + LinearFirstOrder( const LinearFirstOrder &l ) : Tau( l.Tau ) {}; + + void operator()( double x, const dvector &y, dvector &dydx ) const + { + dydx[0] = -y[0]/Tau; + }; + +private: + double Tau; +}; + + +int main( void ) +{ + double x1 = 0.0; + double x2 = 10.0; + double deltax = 0.1; + int n = (int)floor( (x2-x1)/deltax ) + 1; + dvector x( n ); + dvector ystart( 1, 1.0 ); + dmatrix y( 1 ); + for ( unsigned int k=0; k<y.size(); k++ ) + y[k].resize( n ); + + LinearFirstOrder lfo( 2.0 ); + midpointInt( x, y, ystart, x1, x2, deltax, lfo ); + + for ( unsigned int k=0; k<x.size(); k++ ) + cout << x[k] << " " << y[0][k] << endl; + + return 0; +} diff --git a/pool/shard007/C++/0092518_autofill_type_unittest.cc b/pool/shard007/C++/0092518_autofill_type_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..3fc28cc091b261127760058efac915401e413232 --- /dev/null +++ b/pool/shard007/C++/0092518_autofill_type_unittest.cc @@ -0,0 +1,91 @@ +// Copyright 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 "components/autofill/core/browser/autofill_type.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace autofill { +namespace { + +TEST(AutofillTypeTest, ServerFieldTypes) { + // No server data. + AutofillType none(NO_SERVER_DATA); + EXPECT_EQ(NO_SERVER_DATA, none.GetStorableType()); + EXPECT_EQ(NO_GROUP, none.group()); + + // Unknown type. + AutofillType unknown(UNKNOWN_TYPE); + EXPECT_EQ(UNKNOWN_TYPE, unknown.GetStorableType()); + EXPECT_EQ(NO_GROUP, unknown.group()); + + // Type with group but no subgroup. + AutofillType first(NAME_FIRST); + EXPECT_EQ(NAME_FIRST, first.GetStorableType()); + EXPECT_EQ(NAME, first.group()); + + // Type with group and subgroup. + AutofillType phone(PHONE_HOME_NUMBER); + EXPECT_EQ(PHONE_HOME_NUMBER, phone.GetStorableType()); + EXPECT_EQ(PHONE_HOME, phone.group()); + + // Billing type. + AutofillType billing_address(ADDRESS_BILLING_LINE1); + EXPECT_EQ(ADDRESS_HOME_LINE1, billing_address.GetStorableType()); + EXPECT_EQ(ADDRESS_BILLING, billing_address.group()); + + // Last value, to check any offset errors. + AutofillType last(NAME_BILLING_SUFFIX); + EXPECT_EQ(NAME_SUFFIX, last.GetStorableType()); + EXPECT_EQ(NAME_BILLING, last.group()); + + // Boundary (error) condition. + AutofillType boundary(MAX_VALID_FIELD_TYPE); + EXPECT_EQ(UNKNOWN_TYPE, boundary.GetStorableType()); + EXPECT_EQ(NO_GROUP, boundary.group()); + + // Beyond the boundary (error) condition. + AutofillType beyond(static_cast<ServerFieldType>(MAX_VALID_FIELD_TYPE + 10)); + EXPECT_EQ(UNKNOWN_TYPE, beyond.GetStorableType()); + EXPECT_EQ(NO_GROUP, beyond.group()); + + // In-between value. Missing from enum but within range. Error condition. + AutofillType between(static_cast<ServerFieldType>(16)); + EXPECT_EQ(UNKNOWN_TYPE, between.GetStorableType()); + EXPECT_EQ(NO_GROUP, between.group()); +} + +TEST(AutofillTypeTest, HtmlFieldTypes) { + // Unknown type. + AutofillType unknown(HTML_TYPE_UNSPECIFIED, HTML_MODE_NONE); + EXPECT_EQ(UNKNOWN_TYPE, unknown.GetStorableType()); + EXPECT_EQ(NO_GROUP, unknown.group()); + + // Type with group but no subgroup. + AutofillType first(HTML_TYPE_GIVEN_NAME, HTML_MODE_NONE); + EXPECT_EQ(NAME_FIRST, first.GetStorableType()); + EXPECT_EQ(NAME, first.group()); + + // Type with group and subgroup. + AutofillType phone(HTML_TYPE_TEL, HTML_MODE_NONE); + EXPECT_EQ(PHONE_HOME_WHOLE_NUMBER, phone.GetStorableType()); + EXPECT_EQ(PHONE_HOME, phone.group()); + + // Last value, to check any offset errors. + AutofillType last(HTML_TYPE_CREDIT_CARD_EXP_4_DIGIT_YEAR, HTML_MODE_NONE); + EXPECT_EQ(CREDIT_CARD_EXP_4_DIGIT_YEAR, last.GetStorableType()); + EXPECT_EQ(CREDIT_CARD, last.group()); + + // Shipping mode. + AutofillType shipping_first(HTML_TYPE_GIVEN_NAME, HTML_MODE_SHIPPING); + EXPECT_EQ(NAME_FIRST, shipping_first.GetStorableType()); + EXPECT_EQ(NAME, shipping_first.group()); + + // Billing mode. + AutofillType billing_first(HTML_TYPE_GIVEN_NAME, HTML_MODE_BILLING); + EXPECT_EQ(NAME_FIRST, billing_first.GetStorableType()); + EXPECT_EQ(NAME_BILLING, billing_first.group()); +} + +} // namespace +} // namespace autofill diff --git a/pool/shard007/C++/0092522_test-flags.cc b/pool/shard007/C++/0092522_test-flags.cc new file mode 100644 index 0000000000000000000000000000000000000000..7b1b988161f06ac9f1fbba1943a98caa95da4625 --- /dev/null +++ b/pool/shard007/C++/0092522_test-flags.cc @@ -0,0 +1,174 @@ +// Copyright 2006-2008 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. + +#include <stdlib.h> + +#include "v8.h" +#include "cctest.h" + +using namespace v8::internal; + +DEFINE_bool(bool_flag, true, "bool_flag"); +DEFINE_int(int_flag, 13, "int_flag"); +DEFINE_float(float_flag, 2.5, "float-flag"); +DEFINE_string(string_flag, "Hello, world!", "string-flag"); + + +// This test must be executed first! +TEST(Default) { + CHECK(FLAG_bool_flag); + CHECK_EQ(13, FLAG_int_flag); + CHECK_EQ(2.5, FLAG_float_flag); + CHECK_EQ(0, strcmp(FLAG_string_flag, "Hello, world!")); +} + + +static void SetFlagsToDefault() { + for (Flag* f = FlagList::list(); f != NULL; f = f->next()) { + f->SetToDefault(); + } + TestDefault(); +} + + +TEST(Flags1) { + FlagList::Print(__FILE__, false); + FlagList::Print(NULL, true); +} + + +TEST(Flags2) { + SetFlagsToDefault(); + int argc = 7; + const char* argv[] = { "Test2", "-nobool-flag", "notaflag", "--int_flag=77", + "-float_flag=.25", "--string_flag", "no way!" }; + CHECK_EQ(0, FlagList::SetFlagsFromCommandLine(&argc, + const_cast<char **>(argv), + false)); + CHECK_EQ(7, argc); + CHECK(!FLAG_bool_flag); + CHECK_EQ(77, FLAG_int_flag); + CHECK_EQ(.25, FLAG_float_flag); + CHECK_EQ(0, strcmp(FLAG_string_flag, "no way!")); +} + + +TEST(Flags2b) { + SetFlagsToDefault(); + const char* str = + " -nobool-flag notaflag --int_flag=77 -float_flag=.25 " + "--string_flag no_way! "; + CHECK_EQ(0, FlagList::SetFlagsFromString(str, strlen(str))); + CHECK(!FLAG_bool_flag); + CHECK_EQ(77, FLAG_int_flag); + CHECK_EQ(.25, FLAG_float_flag); + CHECK_EQ(0, strcmp(FLAG_string_flag, "no_way!")); +} + + +TEST(Flags3) { + SetFlagsToDefault(); + int argc = 8; + const char* argv[] = + { "Test3", "--bool_flag", "notaflag", "--int_flag", "-666", + "--float_flag", "-12E10", "-string-flag=foo-bar" }; + CHECK_EQ(0, FlagList::SetFlagsFromCommandLine(&argc, + const_cast<char **>(argv), + true)); + CHECK_EQ(2, argc); + CHECK(FLAG_bool_flag); + CHECK_EQ(-666, FLAG_int_flag); + CHECK_EQ(-12E10, FLAG_float_flag); + CHECK_EQ(0, strcmp(FLAG_string_flag, "foo-bar")); +} + + +TEST(Flags3b) { + SetFlagsToDefault(); + const char* str = + "--bool_flag notaflag --int_flag -666 --float_flag -12E10 " + "-string-flag=foo-bar"; + CHECK_EQ(0, FlagList::SetFlagsFromString(str, strlen(str))); + CHECK(FLAG_bool_flag); + CHECK_EQ(-666, FLAG_int_flag); + CHECK_EQ(-12E10, FLAG_float_flag); + CHECK_EQ(0, strcmp(FLAG_string_flag, "foo-bar")); +} + + +TEST(Flags4) { + SetFlagsToDefault(); + int argc = 3; + const char* argv[] = { "Test4", "--bool_flag", "--foo" }; + CHECK_EQ(0, FlagList::SetFlagsFromCommandLine(&argc, + const_cast<char **>(argv), + true)); + CHECK_EQ(2, argc); +} + + +TEST(Flags4b) { + SetFlagsToDefault(); + const char* str = "--bool_flag --foo"; + CHECK_EQ(2, FlagList::SetFlagsFromString(str, strlen(str))); +} + + +TEST(Flags5) { + SetFlagsToDefault(); + int argc = 2; + const char* argv[] = { "Test5", "--int_flag=\"foobar\"" }; + CHECK_EQ(1, FlagList::SetFlagsFromCommandLine(&argc, + const_cast<char **>(argv), + true)); + CHECK_EQ(2, argc); +} + + +TEST(Flags5b) { + SetFlagsToDefault(); + const char* str = " --int_flag=\"foobar\""; + CHECK_EQ(1, FlagList::SetFlagsFromString(str, strlen(str))); +} + + +TEST(Flags6) { + SetFlagsToDefault(); + int argc = 4; + const char* argv[] = { "Test5", "--int-flag", "0", "--float_flag" }; + CHECK_EQ(3, FlagList::SetFlagsFromCommandLine(&argc, + const_cast<char **>(argv), + true)); + CHECK_EQ(4, argc); +} + + +TEST(Flags6b) { + SetFlagsToDefault(); + const char* str = " --int-flag 0 --float_flag "; + CHECK_EQ(3, FlagList::SetFlagsFromString(str, strlen(str))); +} diff --git a/pool/shard007/C++/0092523_sk_picture_rasterizer.cc b/pool/shard007/C++/0092523_sk_picture_rasterizer.cc new file mode 100644 index 0000000000000000000000000000000000000000..7087a1369bd0b705218c1edcff9122dbc2a7630a --- /dev/null +++ b/pool/shard007/C++/0092523_sk_picture_rasterizer.cc @@ -0,0 +1,90 @@ +// Copyright (c) 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. + +#include "gpu/skia_runner/sk_picture_rasterizer.h" + +#include <iostream> + +#include "third_party/skia/include/core/SkCanvas.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/core/SkSurfaceProps.h" + +namespace skia_runner { + +SkPictureRasterizer::SkPictureRasterizer(skia::RefPtr<GrContext> gr_context, + int max_texture_size) + : use_lcd_text_(false), + use_distance_field_text_(false), + msaa_sample_count_(0), + max_texture_size_(max_texture_size), + gr_context_(gr_context) { +} + +SkPictureRasterizer::~SkPictureRasterizer() { +} + +skia::RefPtr<SkImage> SkPictureRasterizer::RasterizeTile( + const SkPicture* picture, + const SkRect& rect) const { + DCHECK(gr_context_); + + SkImageInfo info = SkImageInfo::MakeN32Premul(rect.width(), rect.height()); + uint32_t flags = 0; + if (use_distance_field_text_) + flags = SkSurfaceProps::kUseDistanceFieldFonts_Flag; + + SkSurfaceProps surface_props = + use_lcd_text_ + ? SkSurfaceProps(flags, SkSurfaceProps::kLegacyFontHost_InitType) + : SkSurfaceProps(flags, kUnknown_SkPixelGeometry); + + skia::RefPtr<SkSurface> sk_surface(skia::AdoptRef( + SkSurface::NewRenderTarget(gr_context_.get(), SkSurface::kYes_Budgeted, + info, msaa_sample_count_, &surface_props))); + if (sk_surface) { + SkCanvas* canvas = sk_surface->getCanvas(); + canvas->translate(-rect.left(), -rect.top()); + canvas->drawPicture(picture); + + return skia::AdoptRef(sk_surface->newImageSnapshot()); + } + return nullptr; +} + +skia::RefPtr<SkImage> SkPictureRasterizer::Rasterize( + const SkPicture* picture) const { + if (!gr_context_) + return nullptr; + + SkRect picture_rect = picture->cullRect(); + if (picture_rect.width() <= max_texture_size_ && + picture_rect.height() <= max_texture_size_) + return RasterizeTile(picture, picture_rect); + + SkImageInfo info = + SkImageInfo::MakeN32Premul(picture_rect.width(), picture_rect.height()); + + skia::RefPtr<SkSurface> sk_surface( + skia::AdoptRef(SkSurface::NewRaster(info))); + SkCanvas* canvas = sk_surface->getCanvas(); + + int num_tiles_x = picture_rect.width() / max_texture_size_ + 1; + int num_tiles_y = picture_rect.height() / max_texture_size_ + 1; + for (int y = 0; y < num_tiles_y; ++y) { + SkRect tile_rect; + tile_rect.fTop = picture_rect.top() + y * max_texture_size_; + tile_rect.fBottom = + std::min(tile_rect.fTop + max_texture_size_, picture_rect.bottom()); + for (int x = 0; x < num_tiles_x; ++x) { + tile_rect.fLeft = picture_rect.left() + x * max_texture_size_; + tile_rect.fRight = + std::min(tile_rect.fLeft + max_texture_size_, picture_rect.right()); + skia::RefPtr<SkImage> tile(RasterizeTile(picture, tile_rect)); + canvas->drawImage(tile.get(), tile_rect.left(), tile_rect.top()); + } + } + return skia::AdoptRef(sk_surface->newImageSnapshot()); +} + +} // namepsace skia_runner diff --git a/pool/shard007/C++/0092533_StatsLogger.cpp b/pool/shard007/C++/0092533_StatsLogger.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f713fa633cefc9a6973509f06acf8e27db193591 --- /dev/null +++ b/pool/shard007/C++/0092533_StatsLogger.cpp @@ -0,0 +1,71 @@ +/* + * StatsLogger.cpp + * + */ + +#include <iostream> +#include <fstream> +#include <vector> +#include <chrono> +#include <string> +#include <ctime> + + +#include "StatsLogger.h" + + + +StatsLogger::LoggingColumn::LoggingColumn(std::string name, std::function<std::string()> callback) : name(name), callback(callback){ +} + +StatsLogger::StatsLogger(){ +} + +void StatsLogger::registerLoggingColumn(std::string columnName, std::function<std::string()> callback){ + columns.push_back(LoggingColumn(columnName, callback)); +} + +void StatsLogger::initLog(std::string file){ + std::ofstream statsFile; + statsFile.open(file); + + statsFile << columns[0].name; + + for(int i=1;i<columns.size();i++){ + statsFile << ";" << columns[i].name; + } + + statsFile << std::endl; +} + +void StatsLogger::log(std::string file){ + //Log stats + std::ofstream statsFile; + + statsFile.open(file, std::ios_base::app);//Append + + statsFile << columns[0].callback(); + + for(int i=1;i<columns.size();i++){ + statsFile << ";" << columns[i].callback(); + } + + statsFile << std::endl; +} + +void StatsLogger::archiveLog(std::string file){ + std::string nameAndPath = (file.substr(0, file.find_last_of(".") - 1)); + std::string extension = (file.substr(0, file.find_last_of(".") + 1)); + + std::time_t rawtime; + std::tm* timeinfo; + char buffer [20]; + + std::time(&rawtime); + timeinfo = std::localtime(&rawtime); + + std::strftime(buffer, 20, "%Y-%m-%d-%H-%M", timeinfo); + std::puts(buffer); + + rename(file.c_str(), (nameAndPath + "-" + std::string(buffer) + extension).c_str()); +} diff --git a/pool/shard007/C++/0092538_ios.cpp b/pool/shard007/C++/0092538_ios.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b8fe7227e06e43b0cefe50fda24f91c810ce06b7 --- /dev/null +++ b/pool/shard007/C++/0092538_ios.cpp @@ -0,0 +1,130 @@ +// SPDX-License-Identifier: GPL-2.0 +/* implements iOS specific functions */ +#include <stdlib.h> +#include <dirent.h> +#include <fnmatch.h> +#include "dive.h" +#include "file.h" +#include "display.h" +#include "core/qthelper.h" +#include <CoreFoundation/CoreFoundation.h> +#if !defined(__IPHONE_5_0) +#include <CoreServices/CoreServices.h> +#endif +#include <mach-o/dyld.h> +#include <sys/syslimits.h> +#include <stdio.h> +#include <fcntl.h> +#include <unistd.h> +#include <zip.h> + +#include <QStandardPaths> + +extern "C" { + +const char mac_system_divelist_default_font[] = "Arial"; +const char *system_divelist_default_font = mac_system_divelist_default_font; +double system_divelist_default_font_size = -1.0; + +void subsurface_OS_pref_setup(void) +{ + // nothing +} + +bool subsurface_ignore_font(const char*) +{ + // there are no old default fonts that we would want to ignore + return false; +} + +static const char *system_default_path_append(const char *append) +{ + // Qt appears to find a working path for us - let's just go with that + QString path = QStandardPaths::standardLocations(QStandardPaths::DataLocation).first(); + + if (append) + path += QString("/%1").arg(append); + + return copy_qstring(path); +} + +const char *system_default_directory(void) +{ + static const char *path = NULL; + if (!path) + path = system_default_path_append(NULL); + return path; +} + +const char *system_default_filename(void) +{ + static const char *filename = "subsurface.xml"; + static const char *path = NULL; + if (!path) + path = system_default_path_append(filename); + return path; +} + +int enumerate_devices(device_callback_t, void *, unsigned int) +{ + // we can't read from devices on iOS + return -1; +} + +/* NOP wrappers to comform with windows.c */ +int subsurface_rename(const char *path, const char *newpath) +{ + return rename(path, newpath); +} + +int subsurface_open(const char *path, int oflags, mode_t mode) +{ + return open(path, oflags, mode); +} + +FILE *subsurface_fopen(const char *path, const char *mode) +{ + return fopen(path, mode); +} + +void *subsurface_opendir(const char *path) +{ + return (void *)opendir(path); +} + +int subsurface_access(const char *path, int mode) +{ + return access(path, mode); +} + +int subsurface_stat(const char* path, struct stat* buf) +{ + return stat(path, buf); +} + +struct zip *subsurface_zip_open_readonly(const char *path, int flags, int *errorp) +{ + return zip_open(path, flags, errorp); +} + +int subsurface_zip_close(struct zip *zip) +{ + return zip_close(zip); +} + +/* win32 console */ +void subsurface_console_init(void) +{ + /* NOP */ +} + +void subsurface_console_exit(void) +{ + /* NOP */ +} + +bool subsurface_user_is_root() +{ + return false; +} +} diff --git a/pool/shard007/C++/0092545_gpu_command_buffer_traits.cc b/pool/shard007/C++/0092545_gpu_command_buffer_traits.cc new file mode 100644 index 0000000000000000000000000000000000000000..1de3b414d77d2d2ead7edb58da5f138cbfbb15a9 --- /dev/null +++ b/pool/shard007/C++/0092545_gpu_command_buffer_traits.cc @@ -0,0 +1,126 @@ +// Copyright (c) 2012 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 "gpu/ipc/gpu_command_buffer_traits.h" + +#include "gpu/command_buffer/common/mailbox_holder.h" +#include "gpu/command_buffer/common/value_state.h" + +// Generate param traits write methods. +#include "ipc/param_traits_write_macros.h" +namespace IPC { +#include "gpu/ipc/gpu_command_buffer_traits_multi.h" +} // namespace IPC + +// Generate param traits read methods. +#include "ipc/param_traits_read_macros.h" +namespace IPC { +#include "gpu/ipc/gpu_command_buffer_traits_multi.h" +} // namespace IPC + +// Generate param traits log methods. +#include "ipc/param_traits_log_macros.h" +namespace IPC { +#include "gpu/ipc/gpu_command_buffer_traits_multi.h" +} // namespace IPC + +namespace IPC { + +void ParamTraits<gpu::CommandBuffer::State> ::Write(Message* m, + const param_type& p) { + WriteParam(m, p.get_offset); + WriteParam(m, p.token); + WriteParam(m, static_cast<int32>(p.error)); + WriteParam(m, p.generation); +} + +bool ParamTraits<gpu::CommandBuffer::State> ::Read(const Message* m, + PickleIterator* iter, + param_type* p) { + int32 temp; + if (ReadParam(m, iter, &p->get_offset) && + ReadParam(m, iter, &p->token) && + ReadParam(m, iter, &temp) && + ReadParam(m, iter, &p->generation)) { + p->error = static_cast<gpu::error::Error>(temp); + return true; + } else { + return false; + } +} + +void ParamTraits<gpu::CommandBuffer::State> ::Log(const param_type& p, + std::string* l) { + l->append("<CommandBuffer::State>"); +} + +void ParamTraits<gpu::Mailbox>::Write(Message* m, const param_type& p) { + m->WriteBytes(p.name, sizeof(p.name)); +} + +bool ParamTraits<gpu::Mailbox>::Read(const Message* m, + PickleIterator* iter, + param_type* p) { + const char* bytes = NULL; + if (!iter->ReadBytes(&bytes, sizeof(p->name))) + return false; + DCHECK(bytes); + memcpy(p->name, bytes, sizeof(p->name)); + return true; +} + +void ParamTraits<gpu::Mailbox>::Log(const param_type& p, std::string* l) { + for (size_t i = 0; i < sizeof(p.name); ++i) + *l += base::StringPrintf("%02x", p.name[i]); +} + +void ParamTraits<gpu::MailboxHolder>::Write(Message* m, const param_type& p) { + WriteParam(m, p.mailbox); + WriteParam(m, p.texture_target); + WriteParam(m, p.sync_point); +} + +bool ParamTraits<gpu::MailboxHolder>::Read(const Message* m, + PickleIterator* iter, + param_type* p) { + if (!ReadParam(m, iter, &p->mailbox) || + !ReadParam(m, iter, &p->texture_target) || + !ReadParam(m, iter, &p->sync_point)) + return false; + return true; +} + +void ParamTraits<gpu::MailboxHolder>::Log(const param_type& p, std::string* l) { + ParamTraits<gpu::Mailbox>::Log(p.mailbox, l); + *l += base::StringPrintf(":%04x@%d", p.texture_target, p.sync_point); +} + +void ParamTraits<gpu::ValueState>::Write(Message* m, const param_type& p) { + m->WriteData(reinterpret_cast<const char*>(&p), + sizeof(gpu::ValueState)); +} + +bool ParamTraits<gpu::ValueState>::Read(const Message* m, + PickleIterator* iter, + param_type* p) { + int length; + const char* data = NULL; + if (!iter->ReadData(&data, &length) || length != sizeof(gpu::ValueState)) + return false; + DCHECK(data); + memcpy(p, data, sizeof(gpu::ValueState)); + return true; +} + +void ParamTraits<gpu::ValueState>::Log(const param_type& p, std::string* l) { + l->append("<ValueState ("); + for (size_t i = 0; i < sizeof(p.int_value); ++i) + *l += base::StringPrintf("%i ", p.int_value[i]); + l->append(" int values "); + for (size_t i = 0; i < sizeof(p.float_value); ++i) + *l += base::StringPrintf("%f ", p.float_value[i]); + l->append(" float values)>"); +} + +} // namespace IPC diff --git a/pool/shard007/C++/0092554_ExtenedTimer.cpp b/pool/shard007/C++/0092554_ExtenedTimer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6dd5a6e441bec123b7fb46d6bc2088ef71bb8c60 --- /dev/null +++ b/pool/shard007/C++/0092554_ExtenedTimer.cpp @@ -0,0 +1,105 @@ +/* + ============================================================================== + + ExtenedTimer.cpp + Created: 24 Jan 2016 1:36:45pm + Author: David Gunnarsson + + ============================================================================== +*/ + +#include "ExtenedTimer.h" +#include "debug.h" +#include "windowshacks.h" + +ExtendedTimer::~ExtendedTimer() { + const ScopedLock sl (ETlock); + stopTimer(); + clearTimerCallback(); + while(runningCallbacks > 0) { + int nr = runningCallbacks; + DBUG(("WARNING: runningCallbacks %i", nr)); + ::usleep(100000); + } +} + +void ExtendedTimer::setTimeout(function<void()> cb_in, const int64_t timeMs, const int id) { + const ScopedLock sl (ETlock); + int i = 0; + if (id != 0) { + for(auto && cb : callbacks) { + if(cb.caller == this && cb.id == id) { + const ScopedLock arl(addRemoveLock); + callbacks.erase(callbacks.begin() + i); + //DBUG(("clear out old callback")); + break; + } + } + } + + //DBUG(("timeMs %lld", timeMs)); + + int64_t now = Time::currentTimeMillis(); + //DBUG(("now %lld", now)); + int64_t then = now+timeMs; + //DBUG(("then %lld", then)); + + CB c; + c.id = id; + c.cb = cb_in; + c.time = then; + c.caller = this; + const ScopedLock arl(addRemoveLock); + callbacks.push_back(c); +} + +void ExtendedTimer::runAsync(function<void()>&& cb) { + setTimeout(cb, 0); +} + +void ExtendedTimer::triggerTimeouts() { + if(callbacks.empty()) { + return; + } + + vector<CB> callNowCallbacks;//to prevent timer to be locked for new setTimeouts while calling callbacks. + { + const ScopedLock sl (ETlock); + + int64_t now = Time::currentTimeMillis(); + int i = 0; + for(auto && callback : callbacks) { + if(callback.time < now) { + callNowCallbacks.push_back(callback); + callbacks.erase(callbacks.begin() + i); + triggerTimeouts(); + break; + } + i++; + } + } + + for(auto && cb : callNowCallbacks) { + runningCallbacks++; + cb.cb(); + runningCallbacks--; + } +} + +void ExtendedTimer::clearTimerCallback() { + const ScopedLock arl(addRemoveLock); + callbacks.clear(); +} + +void ExtendedTimer::removeTimeoutWithID(const int idToRemove) { + const ScopedLock sl (ETlock); + int i = 0; + for(auto && callback : callbacks) { + if(callback.id == idToRemove) { + callbacks.erase(callbacks.begin() + i); + return; + } + } + DBUG(("no matching callback to remove")); +} + diff --git a/pool/shard007/C++/0092560_kv_expiry_manager.cpp b/pool/shard007/C++/0092560_kv_expiry_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d21231464e082bf490812c238e62fc0ec826a4ba --- /dev/null +++ b/pool/shard007/C++/0092560_kv_expiry_manager.cpp @@ -0,0 +1,234 @@ +//---------------------------------------------------------------------------- +// NVMKV +// |- Copyright 2012-2013 Fusion-io, Inc. + +// This program is free software; you can redistribute it and/or modify it under +// the terms of the GNU General Public License version 2 as published by the Free +// Software Foundation; +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +// FOR A PARTICULAR PURPOSE. See the GNU General +// Public License v2 for more details. +// A copy of the GNU General Public License v2 is provided with this package and +// can also be found at: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +// You should have received a copy of the GNU General Public License along with +// this program; if not, write to the Free Software Foundation, Inc., 59 Temple +// Place, Suite 330, Boston, MA 02111-1307 USA. +//---------------------------------------------------------------------------- +#include <stdio.h> +#include <new> +#include <sys/time.h> +#include "src/kv_store_mgr.h" +#include "src/kv_expiry_manager.h" +// +//initialize expiry manager +// +NVM_KV_Expiry_Manager::NVM_KV_Expiry_Manager(int num_threads, + NVM_KV_Store *kv_store) : NVM_KV_Scanner(num_threads, kv_store) +{ + m_last_seen_capacity = 0.0; + m_no_expire_count = 0; +} +// +//destroys expiry manager +// +NVM_KV_Expiry_Manager::~NVM_KV_Expiry_Manager() +{ +} +// +//routine that starts the scanner pass and discards +//key-value pair that are expired +// +void* NVM_KV_Expiry_Manager::start_thread() +{ + pthread_mutex_t *glb_mtx = + get_store()->get_pool_mgr()->get_glb_mutex(); + bool expiry = true; + + set_cancel_state(); + //register function that needs to be called on thread cancellation + pthread_cleanup_push(&NVM_KV_Scanner::scanner_cancel_routine, glb_mtx); + //Global mutex is used to protect expiry manager + //and pool delete manager from not deleting same addresses + pthread_mutex_lock(glb_mtx); + while (expiry) + { + //cancellation point + pthread_testcancel(); + while (get_store()->get_pool_mgr()->check_pool_del_status() + || !expire_keys()) + { + wait_for_trigger(); + } + start_expiry(); + } + pthread_mutex_unlock(glb_mtx); + pthread_cleanup_pop(0); + return NULL; +} +// +//start traversing through the complete range of keys +//delete kv pairs that are expired +// +int NVM_KV_Expiry_Manager::start_expiry() +{ + uint64_t key_loc = 0; + uint64_t read_len = 0; + uint64_t discard_len = 0; + uint32_t iov_count = 0; + nvm_iovec_t *iovec = get_iovec(); + int ret_code = 0; + NVM_KV_Store *kv_store = get_store(); + nvm_kv_store_capabilities_t capabilities; + uint64_t max_trim_size_per_iov = 0; + + capabilities = kv_store->get_store_device()->capabilities; + max_trim_size_per_iov = + capabilities.nvm_atomic_write_multiplicity * + capabilities.nvm_max_trim_size_per_iov; + + while (!kv_store->get_pool_mgr()->check_pool_del_status() && + ((ret_code = perform_scan(&key_loc, &read_len)) == NVM_SUCCESS)) + { + if (get_iter_type() != KV_GLB_EXP_ITER) + { + //check key if expired + ret_code = is_valid_for_del(key_loc, NULL); + if (ret_code < 0) + { + break; + } + else if (ret_code == 0) + { + continue; + } + } + //check if read_len is greater than max_trim_size_per_iov + discard_len = read_len * capabilities.nvm_sector_size; + if (discard_len > max_trim_size_per_iov) + { + //there is some problem with length of key + fprintf(stderr, "Error: Corrupted key\n"); + ret_code = -NVM_ERR_INTERNAL_FAILURE; + break; + } + else + { + //if expired, put in batch for discarding + iovec[iov_count].iov_base = 0; + iovec[iov_count].iov_len = discard_len; + iovec[iov_count].iov_lba = key_loc; + iovec[iov_count].iov_opcode = NVM_IOV_TRIM; + iov_count++; + } + if (iov_count == capabilities.nvm_max_num_iovs) + { + if ((ret_code = kv_store->batch_delete_sync(iovec, iov_count)) + != NVM_SUCCESS) + { + break; + } + iov_count = 0; + } + } + + if (ret_code == -NVM_ERR_OBJECT_NOT_FOUND) + { + ret_code = NVM_SUCCESS; + } + + //issue discards on any of the keys in buffer + //only when the end is reached + if (iov_count && ret_code == NVM_SUCCESS) + { + ret_code = kv_store->batch_delete_sync(iovec, iov_count); + } + + reset_iterator(); + return ret_code; +} +// +//expiry scanner checks for the heuristics to make sure expiry pass +//needs to be started, if heuristics is met returns true else returns +//false +// +bool NVM_KV_Expiry_Manager::expire_keys() +{ + nvm_capacity_t capacity_info; + int ret_code = 0; + bool ret_val = false; + double percent_used = 0; + + //check the % used of the physical capacity + ret_code = nvm_get_capacity(get_store()->get_store_device()->nvm_handle, + &capacity_info); + if (ret_code >= 0) + { + percent_used = ((double)capacity_info.used_phys_capacity/ + (double)capacity_info.total_phys_capacity) * 100; + if (m_last_seen_capacity && (percent_used > m_last_seen_capacity)) + { + m_no_expire_count = 0; + //if percentage is greater than M_TRIGGER_NEXT of last + //triggering percentage, return true + if ((percent_used - m_last_seen_capacity) > M_TRIGGER_NEXT) + { + ret_val = true; + } + } + else if (percent_used == m_last_seen_capacity) + { + if (m_no_expire_count > M_NO_EXPIRY_LIMIT) + { + m_no_expire_count = 0; + ret_val = false; + } + else + { + m_no_expire_count++; + ret_val = true; + } + } + else if (percent_used >= M_TRIGGER_PERCENT) + { + m_no_expire_count = 0; + //if percentage is > M_TRIGGER_PERCENT + ret_val = true; + } + } + m_last_seen_capacity = percent_used; + return ret_val; +} +// +//expiry scanner goes on timed wait, it will be either +//triggered by pool deletion manager or when it completes +//sleep +// +void NVM_KV_Expiry_Manager::wait_for_trigger() +{ + struct timespec ts; + struct timeval tp; + pthread_mutex_t *glb_mtx = get_store()->get_pool_mgr()-> + get_glb_mutex(); + pthread_cond_t *glb_cond_var = get_store()->get_pool_mgr()-> + get_glb_cond_var(); + + gettimeofday(&tp, NULL); + //convert from timeval to timespec + ts.tv_sec = tp.tv_sec; + ts.tv_nsec = tp.tv_usec * 1000; + ts.tv_sec += M_TIME_INTERVAL; + pthread_cond_timedwait(glb_cond_var, glb_mtx, &ts); + return; +} +// +//restarts expiry scanner if it is sleeping +//on the conditional variable. +// +void NVM_KV_Expiry_Manager::restart_scanner_if_asleep() +{ + pthread_cond_t *glb_cond_var = get_store()->get_pool_mgr()-> + get_glb_cond_var(); + + pthread_cond_broadcast(glb_cond_var); +} diff --git a/pool/shard007/C++/0092563_qml_generator_test.cpp b/pool/shard007/C++/0092563_qml_generator_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d0d651e2def25176ad771518de7dc2504239e1a3 --- /dev/null +++ b/pool/shard007/C++/0092563_qml_generator_test.cpp @@ -0,0 +1,22 @@ +#include "protobuf/qml/qml_generator.h" +#include "protobuf/qml/compiler_util.h" + +#include <google/protobuf/any.pb.h> +#include <google/protobuf/io/zero_copy_stream_impl.h> + +#include <iostream> +#include <memory> + +using namespace protobuf::qml; +using namespace google::protobuf; + +int main() { + auto file = google::protobuf::Any::descriptor()->file(); + + std::unique_ptr<io::ZeroCopyOutputStream> out( + new io::OstreamOutputStream(&std::cout)); + io::Printer p(out.get(), '$'); + FileGenerator g(file); + g.generateJsFile(p); + return 0; +} diff --git a/pool/shard007/C++/0092564_ob_inner_table_operator.cpp b/pool/shard007/C++/0092564_ob_inner_table_operator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..80a0d2604437eb7d8271d7263e207bd42e28246c --- /dev/null +++ b/pool/shard007/C++/0092564_ob_inner_table_operator.cpp @@ -0,0 +1,181 @@ +/* + * (C) 2007-2012 Taobao Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * + * Version: ob_inner_table_operator.h, 03/01/2013 17:27:08 PM zhidong Exp $ + * + * Author: + * xielun.szd <xielun.szd@alipay.com> + * Description: + * Util for inner Table + * + */ + +#include "ob_define.h" +#include "ob_string.h" +#include "ob_server.h" +#include "ob_obi_role.h" +#include "ob_inner_table_operator.h" + +using namespace oceanbase::common; + +int ObInnerTableOperator::update_all_cluster(ObString & sql, const int64_t cluster_id, + const ObServer & server, const ObiRole role, const int64_t flow_percent) +{ + int ret = OB_SUCCESS; + if ((sql.ptr() == NULL) || (0 == sql.size())) + { + ret = OB_INVALID_ARGUMENT; + TBSYS_LOG(WARN, "Check SQL buffer size failed! ptr[%p], size[%d]", sql.ptr(), sql.size()); + } + else + { + char buf[OB_MAX_SERVER_ADDR_SIZE]; + memset(buf, 0 , sizeof(buf)); + if (server.ip_to_string(buf, sizeof(buf)) != true) + { + ret = OB_CONVERT_ERROR; + TBSYS_LOG(ERROR, "server ip is invalid, ret=%d", ret); + } + else + { + const char * format = "REPLACE INTO %s" + "(cluster_id, cluster_role, cluster_vip, cluster_flow_percent, read_strategy, rootserver_port) " + "VALUES(%d,%d,'%s',%d,%d,%d);"; + // random read read_strategy + int size = snprintf(sql.ptr(), sql.size(), format, OB_ALL_CLUSTER, cluster_id, + role.get_role() == ObiRole::MASTER ? 1 : 2, buf, flow_percent, 0, server.get_port()); + if (size >= sql.size()) + { + TBSYS_LOG(ERROR, "SQL buffer size not enough! size: [%d], need: [%d], sql: [%.*s]", + sql.size(), size, sql.length(), sql.ptr()); + ret = OB_SIZE_OVERFLOW; + } + else + { + sql.assign_ptr(sql.ptr(), size); + TBSYS_LOG(INFO, "XXX=%.*s", sql.length(), sql.ptr()); + } + } + } + return ret; +} + +int ObInnerTableOperator::update_all_trigger_event(ObString & sql, const int64_t timestamp, + const ObServer & server, const int64_t type, const int64_t param) +{ + UNUSED(param); + int ret = OB_SUCCESS; + if ((sql.ptr() == NULL) || (0 == sql.size())) + { + TBSYS_LOG(WARN, "Check SQL buffer size failed! ptr[%p], size[%d]", sql.ptr(), sql.size()); + ret = OB_INVALID_ARGUMENT; + } + else + { + char buf[OB_MAX_SERVER_ADDR_SIZE] = ""; + if (server.ip_to_string(buf, sizeof(buf)) != true) + { + ret = OB_CONVERT_ERROR; + } + else + { + const char * format = "REPLACE INTO %s" + "(event_ts, src_ip, event_type, event_param) " + "values (%ld, '%s', %ld, %ld);"; + int size = snprintf(sql.ptr(), sql.size(), format, + OB_ALL_TRIGGER_EVENT_TABLE_NAME, timestamp, buf, type, param); + if (size >= sql.size()) + { + TBSYS_LOG(ERROR, "SQL buffer size not enough! size: [%d], need: [%d], sql: [%.*s]", + sql.size(), size, sql.length(), sql.ptr()); + ret = OB_SIZE_OVERFLOW; + } + else + { + sql.assign_ptr(sql.ptr(), size); + } + } + } + return ret; +} + +int ObInnerTableOperator::update_all_server(ObString & sql, const int64_t cluster_id, + const char * server_type, const ObServer & server, const uint32_t inner_port, const char * version) +{ + int ret = OB_SUCCESS; + if ((sql.ptr() == NULL) || (0 == sql.size())) + { + TBSYS_LOG(WARN, "Check SQL buffer size failed! ptr[%p], size[%d]", sql.ptr(), sql.size()); + ret = OB_INVALID_ARGUMENT; + } + else + { + char buf[OB_MAX_SERVER_ADDR_SIZE] = ""; + if (server.ip_to_string(buf, sizeof(buf)) != true) + { + ret = OB_CONVERT_ERROR; + } + else + { + const char * format = "REPLACE INTO %s" + "(cluster_id, svr_type, svr_ip, svr_port, inner_port, svr_role, svr_version) " + "values (%d, '%s', '%s', %u, %u, %d, '%s');"; + int size = snprintf(sql.ptr(), sql.size(), format, OB_ALL_SERVER, cluster_id, + server_type, buf, server.get_port(), inner_port, 0, version); + if (size >= sql.size()) + { + TBSYS_LOG(ERROR, "SQL buffer size not enough! size: [%d], need: [%d], sql: [%.*s]", + sql.size(), size, sql.length(), sql.ptr()); + ret = OB_SIZE_OVERFLOW; + } + else + { + sql.assign_ptr(sql.ptr(), size); + } + } + } + return ret; +} + +int ObInnerTableOperator::delete_all_server(ObString & sql, const int64_t cluster_id, + const char * server_type, const ObServer & server) +{ + int ret = OB_SUCCESS; + if ((sql.ptr() == NULL) || (0 == sql.size())) + { + TBSYS_LOG(WARN, "Check SQL buffer size failed! ptr[%p], size[%d]", sql.ptr(), sql.size()); + ret = OB_INVALID_ARGUMENT; + } + else + { + char buf[OB_MAX_SERVER_ADDR_SIZE] = ""; + if (server.ip_to_string(buf, sizeof (buf)) != true) + { + ret = OB_CONVERT_ERROR; + } + else + { + const char * format = "DELETE FROM %s WHERE cluster_id = %d AND svr_type = '%s' " + "AND svr_ip = '%s' AND svr_port = %u;"; + int size = snprintf(sql.ptr(), sql.size(), format, OB_ALL_SERVER, + cluster_id, server_type, buf, server.get_port()); + if (size >= sql.size()) + { + TBSYS_LOG(ERROR, "SQL buffer size not enough! size: [%d], need: [%d], sql: [%.*s]", + sql.size(), size, sql.length(), sql.ptr()); + ret = OB_SIZE_OVERFLOW; + } + else + { + sql.assign_ptr(sql.ptr(), size); + } + } + } + return ret; +} + diff --git a/pool/shard007/C++/0092567_cpu_dyn_shape_test.cc b/pool/shard007/C++/0092567_cpu_dyn_shape_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..ce892ad34ae123dfd52c4fcb55e9982d36910f88 --- /dev/null +++ b/pool/shard007/C++/0092567_cpu_dyn_shape_test.cc @@ -0,0 +1,62 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include <memory> + +#include "tensorflow/compiler/xla/service/cpu/cpu_compiler.h" +#include "tensorflow/compiler/xla/service/cpu/test_target_triple_helper.h" +#include "tensorflow/compiler/xla/service/cpu/tests/cpu_codegen_test.h" + +namespace xla { +namespace cpu { +namespace { + +using CpuDynamicShapeTest = CpuCodegenTest; + +TEST_F(CpuDynamicShapeTest, DynamicShapeR2) { + HloComputation::Builder builder(TestName()); + + xla::Shape dyn_input_shape = xla::ShapeUtil::MakeShape(xla::F32, {2, 4}); + dyn_input_shape.set_dynamic_dimension(0, true); + HloInstruction* param_x = builder.AddInstruction( + HloInstruction::CreateParameter(0, dyn_input_shape, "x")); + + builder.AddInstruction(HloInstruction::CreateUnary( + dyn_input_shape, HloOpcode::kNegate, param_x)); + auto hlo_module = CreateNewVerifiedModule(); + hlo_module->AddEntryComputation(builder.Build()); + + string filecheck_pattern = R"( +; CHECK: %[[dyn_dim_size:.*]] = load i32, i32* +; CHECK: %[[i64_dyn_dim_size:.*]] = sext i32 %[[dyn_dim_size:.*]] to i64 +; CHECK: icmp uge i64 %[[custom:.*]], %[[i64_dyn_dim_size:.*]] +; CHECK: %[[multiplier:.*]] = mul i64 1, %[[i64_dyn_dim_size:.*]] +; CHECK: mul nuw nsw i64 %[[custom:.*]], %[[multiplier:.*]] +)"; + + CpuAotCompilationOptions options{ + /*triple=*/kTargetTripleForHost, /*cpu_name=*/kTargetCpuForHost, + /*features=*/"", + /*entry_point_name=*/"entry", + /*relocation_model=*/CpuAotCompilationOptions::RelocationModel::Static}; + + CompileAheadOfTimeAndVerifyIr(std::move(hlo_module), options, + filecheck_pattern, + /*match_optimized_ir=*/false); +} + +} // namespace +} // namespace cpu +} // namespace xla diff --git a/pool/shard007/C++/0092575_DataSource.cpp b/pool/shard007/C++/0092575_DataSource.cpp new file mode 100644 index 0000000000000000000000000000000000000000..43e3c26bca33f0b29da0346a85fc9d0f7c739b11 --- /dev/null +++ b/pool/shard007/C++/0092575_DataSource.cpp @@ -0,0 +1,220 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "include/AMRExtractor.h" + +#if CHROMIUM_AVAILABLE +#include "include/chromium_http_stub.h" +#endif + +#include "include/AACExtractor.h" +#include "include/DRMExtractor.h" +#include "include/FLACExtractor.h" +#include "include/FragmentedMP4Extractor.h" +#include "include/HTTPBase.h" +#include "include/MP3Extractor.h" +#include "include/MPEG2PSExtractor.h" +#include "include/MPEG2TSExtractor.h" +#include "include/MPEG4Extractor.h" +#include "include/NuCachedSource2.h" +#include "include/OggExtractor.h" +#include "include/WAVExtractor.h" +#include "include/WVMExtractor.h" +#include "include/ASFExtractor.h" +#include "include/NVAVIExtractor.h" + +#include "matroska/MatroskaExtractor.h" + +#include <media/stagefright/foundation/AMessage.h> +#include <media/stagefright/DataSource.h> +#include <media/stagefright/FileSource.h> +#include <media/stagefright/MediaErrors.h> +#include <utils/String8.h> + +#include <cutils/properties.h> + +namespace android { + +bool DataSource::getUInt16(off64_t offset, uint16_t *x) { + *x = 0; + + uint8_t byte[2]; + if (readAt(offset, byte, 2) != 2) { + return false; + } + + *x = (byte[0] << 8) | byte[1]; + + return true; +} + +status_t DataSource::getSize(off64_t *size) { + *size = 0; + + return ERROR_UNSUPPORTED; +} + +//////////////////////////////////////////////////////////////////////////////// + +Mutex DataSource::gSnifferMutex; +List<DataSource::SnifferFunc> DataSource::gSniffers; + +bool DataSource::sniff( + String8 *mimeType, float *confidence, sp<AMessage> *meta) { + *mimeType = ""; + *confidence = 0.0f; + meta->clear(); + + Mutex::Autolock autoLock(gSnifferMutex); + for (List<SnifferFunc>::iterator it = gSniffers.begin(); + it != gSniffers.end(); ++it) { + if (mCancelSniff) { + return false; + } + String8 newMimeType; + float newConfidence; + sp<AMessage> newMeta; + if ((*it)(this, &newMimeType, &newConfidence, &newMeta)) { + if (newConfidence > *confidence) { + *mimeType = newMimeType; + *confidence = newConfidence; + *meta = newMeta; + } + } + } + + return *confidence > 0.0; +} + +// static +void DataSource::RegisterSniffer(SnifferFunc func) { + Mutex::Autolock autoLock(gSnifferMutex); + + for (List<SnifferFunc>::iterator it = gSniffers.begin(); + it != gSniffers.end(); ++it) { + if (*it == func) { + return; + } + } + + gSniffers.push_back(func); +} + +// static +void DataSource::RegisterDefaultSniffers() { + RegisterSniffer(SniffMPEG4); + RegisterSniffer(SniffFragmentedMP4); + RegisterSniffer(SniffMatroska); + RegisterSniffer(SniffOgg); + RegisterSniffer(SniffWAV); + RegisterSniffer(SniffFLAC); + RegisterSniffer(SniffAMR); + RegisterSniffer(SniffMPEG2TS); + RegisterSniffer(SniffMP3); + RegisterSniffer(SniffAAC); + RegisterSniffer(SniffMPEG2PS); + RegisterSniffer(SniffWVM); + + char value[PROPERTY_VALUE_MAX]; + if (property_get("drm.service.enabled", value, NULL) + && (!strcmp(value, "1") || !strcasecmp(value, "true"))) { + RegisterSniffer(SniffDRM); + } + RegisterSniffer(SniffASF); + RegisterSniffer(SniffNVAVI); +} + +// static +sp<DataSource> DataSource::CreateFromURI( + const char *uri, const KeyedVector<String8, String8> *headers) { + return CreateCachedSourceFromURI(uri, headers); +} + +sp<DataSource> DataSource::CreateCachedSourceFromURI( + const char *uri, const KeyedVector<String8, String8> *headers, + uint64_t flags) { + bool isCached = (flags & kNoPreCache); + bool isWidevine = !strncasecmp("widevine://", uri, 11); + + sp<DataSource> source; + if (!strncasecmp("file://", uri, 7)) { + if (isCached) { + sp<DataSource> fileSource = new FileSource(uri + 7); + source = new NuCachedSource2(fileSource); + } else { + source = new FileSource(uri + 7); + } + } else if (!strncasecmp("http://", uri, 7) + || !strncasecmp("https://", uri, 8) + || isWidevine) { + sp<HTTPBase> httpSource = HTTPBase::Create(); + + String8 tmp; + if (isWidevine) { + tmp = String8("http://"); + tmp.append(uri + 11); + + uri = tmp.string(); + } + + if (httpSource->connect(uri, headers) != OK) { + return NULL; + } + + if (!isWidevine) { + String8 cacheConfig; + bool disconnectAtHighwatermark; + if (headers != NULL) { + KeyedVector<String8, String8> copy = *headers; + NuCachedSource2::RemoveCacheSpecificHeaders( + ©, &cacheConfig, &disconnectAtHighwatermark); + } + + source = new NuCachedSource2( + httpSource, + cacheConfig.isEmpty() ? NULL : cacheConfig.string()); + } else { + // We do not want that prefetching, caching, datasource wrapper + // in the widevine:// case. + source = httpSource; + } + +# if CHROMIUM_AVAILABLE + } else if (!strncasecmp("data:", uri, 5)) { + source = createDataUriSource(uri); +#endif + } else { + // Assume it's a filename. + if (isCached) { + sp<DataSource> fileSource = new FileSource(uri); + source = new NuCachedSource2(fileSource); + } else { + source = new FileSource(uri); + } + } + + if (source == NULL || source->initCheck() != OK) { + return NULL; + } + + return source; +} + +String8 DataSource::getMIMEType() const { + return String8("application/octet-stream"); +} + +} // namespace android diff --git a/pool/shard007/C++/0092580_qmlrefactoring.cpp b/pool/shard007/C++/0092580_qmlrefactoring.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c0f9cf4dc4f0336d08cda474e3e0d26cd4cf8a52 --- /dev/null +++ b/pool/shard007/C++/0092580_qmlrefactoring.cpp @@ -0,0 +1,173 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing +** +** This file is part of Qt Creator. +** +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms and +** conditions see http://www.qt.io/terms-conditions. For further information +** use the contact form at http://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPLv3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +****************************************************************************/ + +#include "qmlrefactoring.h" + +#include <QDebug> + +#include "addarraymembervisitor.h" +#include "addobjectvisitor.h" +#include "addpropertyvisitor.h" +#include "changeimportsvisitor.h" +#include "changeobjecttypevisitor.h" +#include "changepropertyvisitor.h" +#include "moveobjectvisitor.h" +#include "moveobjectbeforeobjectvisitor.h" +#include "removepropertyvisitor.h" +#include "removeuiobjectmembervisitor.h" + +using namespace QmlJS; +using namespace QmlDesigner; +using namespace QmlDesigner::Internal; + +QmlRefactoring::QmlRefactoring(const Document::Ptr &doc, TextModifier &modifier, const PropertyNameList &propertyOrder): + qmlDocument(doc), + textModifier(&modifier), + m_propertyOrder(propertyOrder) +{ +} + +bool QmlRefactoring::reparseDocument() +{ + const QString newSource = textModifier->text(); + +// qDebug() << "QmlRefactoring::reparseDocument() new QML source:" << newSource; + + Document::MutablePtr tmpDocument(Document::create("<ModelToTextMerger>", Dialect::Qml)); + tmpDocument->setSource(newSource); + + if (tmpDocument->parseQml()) { + qmlDocument = tmpDocument; + return true; + } else { + qWarning() << "*** Possible problem: QML file wasn't parsed correctly."; + qDebug() << "*** QML text:" << textModifier->text(); + return false; + } +} + +bool QmlRefactoring::addImport(const Import &import) +{ + ChangeImportsVisitor visitor(*textModifier, qmlDocument->source()); + return visitor.add(qmlDocument->qmlProgram(), import); +} + +bool QmlRefactoring::removeImport(const Import &import) +{ + ChangeImportsVisitor visitor(*textModifier, qmlDocument->source()); + return visitor.remove(qmlDocument->qmlProgram(), import); +} + +bool QmlRefactoring::addToArrayMemberList(int parentLocation, const PropertyName &propertyName, const QString &content) +{ + if (parentLocation < 0) + return false; + + AddArrayMemberVisitor visit(*textModifier, (quint32) parentLocation, propertyName, content); + visit.setConvertObjectBindingIntoArrayBinding(true); + return visit(qmlDocument->qmlProgram()); +} + +bool QmlRefactoring::addToObjectMemberList(int parentLocation, const QString &content) +{ + if (parentLocation < 0) + return false; + + AddObjectVisitor visit(*textModifier, (quint32) parentLocation, content, m_propertyOrder); + return visit(qmlDocument->qmlProgram()); +} + +bool QmlRefactoring::addProperty(int parentLocation, + const PropertyName &name, + const QString &value, + PropertyType propertyType, + const TypeName &dynamicTypeName) +{ + if (parentLocation < 0) + return false; + + AddPropertyVisitor visit(*textModifier, (quint32) parentLocation, name, value, propertyType, m_propertyOrder, dynamicTypeName); + return visit(qmlDocument->qmlProgram()); +} + +bool QmlRefactoring::changeProperty(int parentLocation, const PropertyName &name, const QString &value, PropertyType propertyType) +{ + if (parentLocation < 0) + return false; + + ChangePropertyVisitor visit(*textModifier, (quint32) parentLocation, name, value, propertyType); + return visit(qmlDocument->qmlProgram()); +} + +bool QmlRefactoring::changeObjectType(int nodeLocation, const QString &newType) +{ + if (nodeLocation < 0 || newType.isEmpty()) + return false; + + ChangeObjectTypeVisitor visit(*textModifier, (quint32) nodeLocation, newType); + return visit(qmlDocument->qmlProgram()); +} + +bool QmlRefactoring::moveObject(int objectLocation, const PropertyName &targetPropertyName, bool targetIsArrayBinding, int targetParentObjectLocation) +{ + if (objectLocation < 0 || targetParentObjectLocation < 0) + return false; + + MoveObjectVisitor visit(*textModifier, (quint32) objectLocation, targetPropertyName, targetIsArrayBinding, (quint32) targetParentObjectLocation, m_propertyOrder); + return visit(qmlDocument->qmlProgram()); +} + +bool QmlRefactoring::moveObjectBeforeObject(int movingObjectLocation, int beforeObjectLocation, bool inDefaultProperty) +{ + if (movingObjectLocation < 0 || beforeObjectLocation < -1) + return false; + + if (beforeObjectLocation == -1) { + MoveObjectBeforeObjectVisitor visit(*textModifier, movingObjectLocation, inDefaultProperty); + return visit(qmlDocument->qmlProgram()); + } else { + MoveObjectBeforeObjectVisitor visit(*textModifier, movingObjectLocation, beforeObjectLocation, inDefaultProperty); + return visit(qmlDocument->qmlProgram()); + } + return false; +} + +bool QmlRefactoring::removeObject(int nodeLocation) +{ + if (nodeLocation < 0) + return false; + + RemoveUIObjectMemberVisitor visit(*textModifier, (quint32) nodeLocation); + return visit(qmlDocument->qmlProgram()); +} + +bool QmlRefactoring::removeProperty(int parentLocation, const PropertyName &name) +{ + if (parentLocation < 0 || name.isEmpty()) + return false; + + RemovePropertyVisitor visit(*textModifier, (quint32) parentLocation, name); + return visit(qmlDocument->qmlProgram()); +} diff --git a/pool/shard007/C++/0092586_Method.cpp b/pool/shard007/C++/0092586_Method.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d636e4c8d6dab75509dd301b5b257763dce9937e --- /dev/null +++ b/pool/shard007/C++/0092586_Method.cpp @@ -0,0 +1,253 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include <aws/apigateway/model/Method.h> +#include <aws/core/utils/json/JsonSerializer.h> + +#include <utility> + +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +namespace Aws +{ +namespace APIGateway +{ +namespace Model +{ + +Method::Method() : + m_httpMethodHasBeenSet(false), + m_authorizationTypeHasBeenSet(false), + m_authorizerIdHasBeenSet(false), + m_apiKeyRequired(false), + m_apiKeyRequiredHasBeenSet(false), + m_requestValidatorIdHasBeenSet(false), + m_operationNameHasBeenSet(false), + m_requestParametersHasBeenSet(false), + m_requestModelsHasBeenSet(false), + m_methodResponsesHasBeenSet(false), + m_methodIntegrationHasBeenSet(false), + m_authorizationScopesHasBeenSet(false) +{ +} + +Method::Method(JsonView jsonValue) : + m_httpMethodHasBeenSet(false), + m_authorizationTypeHasBeenSet(false), + m_authorizerIdHasBeenSet(false), + m_apiKeyRequired(false), + m_apiKeyRequiredHasBeenSet(false), + m_requestValidatorIdHasBeenSet(false), + m_operationNameHasBeenSet(false), + m_requestParametersHasBeenSet(false), + m_requestModelsHasBeenSet(false), + m_methodResponsesHasBeenSet(false), + m_methodIntegrationHasBeenSet(false), + m_authorizationScopesHasBeenSet(false) +{ + *this = jsonValue; +} + +Method& Method::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("httpMethod")) + { + m_httpMethod = jsonValue.GetString("httpMethod"); + + m_httpMethodHasBeenSet = true; + } + + if(jsonValue.ValueExists("authorizationType")) + { + m_authorizationType = jsonValue.GetString("authorizationType"); + + m_authorizationTypeHasBeenSet = true; + } + + if(jsonValue.ValueExists("authorizerId")) + { + m_authorizerId = jsonValue.GetString("authorizerId"); + + m_authorizerIdHasBeenSet = true; + } + + if(jsonValue.ValueExists("apiKeyRequired")) + { + m_apiKeyRequired = jsonValue.GetBool("apiKeyRequired"); + + m_apiKeyRequiredHasBeenSet = true; + } + + if(jsonValue.ValueExists("requestValidatorId")) + { + m_requestValidatorId = jsonValue.GetString("requestValidatorId"); + + m_requestValidatorIdHasBeenSet = true; + } + + if(jsonValue.ValueExists("operationName")) + { + m_operationName = jsonValue.GetString("operationName"); + + m_operationNameHasBeenSet = true; + } + + if(jsonValue.ValueExists("requestParameters")) + { + Aws::Map<Aws::String, JsonView> requestParametersJsonMap = jsonValue.GetObject("requestParameters").GetAllObjects(); + for(auto& requestParametersItem : requestParametersJsonMap) + { + m_requestParameters[requestParametersItem.first] = requestParametersItem.second.AsBool(); + } + m_requestParametersHasBeenSet = true; + } + + if(jsonValue.ValueExists("requestModels")) + { + Aws::Map<Aws::String, JsonView> requestModelsJsonMap = jsonValue.GetObject("requestModels").GetAllObjects(); + for(auto& requestModelsItem : requestModelsJsonMap) + { + m_requestModels[requestModelsItem.first] = requestModelsItem.second.AsString(); + } + m_requestModelsHasBeenSet = true; + } + + if(jsonValue.ValueExists("methodResponses")) + { + Aws::Map<Aws::String, JsonView> methodResponsesJsonMap = jsonValue.GetObject("methodResponses").GetAllObjects(); + for(auto& methodResponsesItem : methodResponsesJsonMap) + { + m_methodResponses[methodResponsesItem.first] = methodResponsesItem.second.AsObject(); + } + m_methodResponsesHasBeenSet = true; + } + + if(jsonValue.ValueExists("methodIntegration")) + { + m_methodIntegration = jsonValue.GetObject("methodIntegration"); + + m_methodIntegrationHasBeenSet = true; + } + + if(jsonValue.ValueExists("authorizationScopes")) + { + Array<JsonView> authorizationScopesJsonList = jsonValue.GetArray("authorizationScopes"); + for(unsigned authorizationScopesIndex = 0; authorizationScopesIndex < authorizationScopesJsonList.GetLength(); ++authorizationScopesIndex) + { + m_authorizationScopes.push_back(authorizationScopesJsonList[authorizationScopesIndex].AsString()); + } + m_authorizationScopesHasBeenSet = true; + } + + return *this; +} + +JsonValue Method::Jsonize() const +{ + JsonValue payload; + + if(m_httpMethodHasBeenSet) + { + payload.WithString("httpMethod", m_httpMethod); + + } + + if(m_authorizationTypeHasBeenSet) + { + payload.WithString("authorizationType", m_authorizationType); + + } + + if(m_authorizerIdHasBeenSet) + { + payload.WithString("authorizerId", m_authorizerId); + + } + + if(m_apiKeyRequiredHasBeenSet) + { + payload.WithBool("apiKeyRequired", m_apiKeyRequired); + + } + + if(m_requestValidatorIdHasBeenSet) + { + payload.WithString("requestValidatorId", m_requestValidatorId); + + } + + if(m_operationNameHasBeenSet) + { + payload.WithString("operationName", m_operationName); + + } + + if(m_requestParametersHasBeenSet) + { + JsonValue requestParametersJsonMap; + for(auto& requestParametersItem : m_requestParameters) + { + requestParametersJsonMap.WithBool(requestParametersItem.first, requestParametersItem.second); + } + payload.WithObject("requestParameters", std::move(requestParametersJsonMap)); + + } + + if(m_requestModelsHasBeenSet) + { + JsonValue requestModelsJsonMap; + for(auto& requestModelsItem : m_requestModels) + { + requestModelsJsonMap.WithString(requestModelsItem.first, requestModelsItem.second); + } + payload.WithObject("requestModels", std::move(requestModelsJsonMap)); + + } + + if(m_methodResponsesHasBeenSet) + { + JsonValue methodResponsesJsonMap; + for(auto& methodResponsesItem : m_methodResponses) + { + methodResponsesJsonMap.WithObject(methodResponsesItem.first, methodResponsesItem.second.Jsonize()); + } + payload.WithObject("methodResponses", std::move(methodResponsesJsonMap)); + + } + + if(m_methodIntegrationHasBeenSet) + { + payload.WithObject("methodIntegration", m_methodIntegration.Jsonize()); + + } + + if(m_authorizationScopesHasBeenSet) + { + Array<JsonValue> authorizationScopesJsonList(m_authorizationScopes.size()); + for(unsigned authorizationScopesIndex = 0; authorizationScopesIndex < authorizationScopesJsonList.GetLength(); ++authorizationScopesIndex) + { + authorizationScopesJsonList[authorizationScopesIndex].AsString(m_authorizationScopes[authorizationScopesIndex]); + } + payload.WithArray("authorizationScopes", std::move(authorizationScopesJsonList)); + + } + + return payload; +} + +} // namespace Model +} // namespace APIGateway +} // namespace Aws diff --git a/pool/shard007/C++/0092591_i2c_rtc8563_test.cpp b/pool/shard007/C++/0092591_i2c_rtc8563_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b4b8b31e73222376204b66d30f7e0fc8ddb34c36 --- /dev/null +++ b/pool/shard007/C++/0092591_i2c_rtc8563_test.cpp @@ -0,0 +1,222 @@ +/* +Smooth - A C++ framework for embedded programming on top of Espressif's ESP-IDF +Copyright 2019 Per Malmberg (https://gitbub.com/PerMalmberg) +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. +*/ + +/**************************************************************************************** + * Typical results from running program on M5StickC + * + * I (605) cpu_start: Starting scheduler on PRO CPU. + * I (0) cpu_start: Starting scheduler on APP CPU. + * I (669) FSLock: Max number of open files set to: 5 + * I (688) APP: Scanning for BM8563 ---- device found + * cI (702) APP: BM8563 initialization --- Succeeded + * I (702) APP: ********** Setting Time ********* + * I (703) APP: ********** Setting Alarm ********* + * W (60709) APP: ============ APP TICK TICK ============= + * I (60710) MemStat: Mem type | 8-bit free | Smallest block | Minimum free | 32-bit free | Smallest block | Minimum free + * I (60716) MemStat: INTERNAL | 217260 | 113804 | 216088 | 273816 | 113804 | 272636 + * I (60727) MemStat: DMA | 217260 | 113804 | 216088 | 217260 | 113804 | 216088 + * I (60739) MemStat: SPIRAM | 0 | 0 | 0 | 0 | 0 | 0 + * I (60750) MemStat: + * I (60753) MemStat: Name | Stack | Min free stack | Max used stack + * I (60761) MemStat: MainTask | 16384 | 13980 | 2404 + * I (60770) MemStat: SocketDispatcher | 20480 | 18384 | 2096 + * I (60778) APP: ........................................ + * I (60785) APP: Time = Tue 25 Feb 2020 - 1:09:00 PM + * I (60790) APP: Alarm set for -> 1:12:00 PM + * + * + * W (240967) APP: ============ APP TICK TICK ============= + * I (240967) MemStat: Mem type | 8-bit free | Smallest block | Minimum free | 32-bit free | Smallest block | Minimum free + * I (240974) MemStat: INTERNAL | 217260 | 113804 | 216088 | 273816 | 113804 | 272636 + * I (240985) MemStat: DMA | 217260 | 113804 | 216088 | 217260 | 113804 | 216088 + * I (240997) MemStat: SPIRAM | 0 | 0 | 0 | 0 | 0 | 0 + * I (241008) MemStat: + * I (241011) MemStat: Name | Stack | Min free stack | Max used stack + * I (241019) MemStat: MainTask | 16384 | 13532 | 2852 + * I (241028) MemStat: SocketDispatcher | 20480 | 18384 | 2096 + * I (241036) APP: ........................................ + * I (241043) APP: Time = Tue 25 Feb 2020 - 1:12:00 PM + * I (241048) APP: Alarm set for -> 1:12:00 PM + * I (241052) APP: The Alarm Active Count = 1 + * + * + * I (3846334) APP: ........................................ + * I (3846341) APP: Time = Tue 25 Feb 2020 - 2:12:05 PM + * I (3846346) APP: Alarm set for -> 1:12:00 PM + * I (3846351) APP: The Alarm Active Count = 2 + ****************************************************************************************/ +#include <vector> +#include "i2c_rtc8563_test.h" +#include "smooth/core/logging/log.h" +#include "smooth/core/SystemStatistics.h" + +using namespace smooth::core; +using namespace std::chrono; +using namespace smooth::application::sensor; + +namespace i2c_rtc8563_test +{ + static const char* TAG = "APP"; + + App::App() : Application(APPLICATION_BASE_PRIO, seconds(60)), + i2c0_master(I2C_NUM_0, // I2C Port 0 + GPIO_NUM_22, // SCL pin + false, // SCL internal pullup NOT enabled + GPIO_NUM_21, // SDA pin + false, // SDA internal pullup NOT enabled + 400 * 1000) // clock frequency - 400kHz + { + } + + void App::init() + { + Application::init(); + + init_i2c_rtc8563(); + + if (rtc8563_initialized) + { + set_time(); + set_alarm(); + rtc8563->clear_alarm_flag(); + } + } + + void App::tick() + { + Log::warning(TAG, "============ APP TICK TICK ============="); + SystemStatistics::instance().dump(); + Log::info(TAG, "........................................" ); + + if (rtc8563_initialized) + { + get_time(); + get_alarm(); + + if (is_alarm_active()) + { + alarm_active_count += 1; + Log::info(TAG, "The Alarm Active Count = {}", alarm_active_count); + clear_alarm_active(); + } + } + } + + // Initialize the RTC8563 + void App::init_i2c_rtc8563() + { + auto device = i2c0_master.create_device<PCF8563>(0x51); // AXP i2c device address 0x51 + Log::info(TAG, "Scanning for BM8563 ---- {}", device->is_present() ? "device found" : "device NOT present"); + + if (device->is_present()) + { + rtc8563_initialized = true; + rtc8563 = std::move(device); + } + + Log::info(TAG, "BM8563 initialization --- {}", rtc8563_initialized ? "Succeeded" : "Failed"); + } + + // Set the time + void App::set_time() + { + Log::info(TAG, "********** Setting Time *********"); + PCF8563::RtcTime tm; + tm.seconds = 0; + tm.minutes = 8; + tm.hours24 = 13; + tm.days = 25; + tm.weekdays = PCF8563::DayOfWeek::Tuesday; + tm.months = PCF8563::Month::February; + tm.years = 2020; + + if (!rtc8563->set_rtc_time(tm)) + { + Log::error(TAG, "Error setting RTC time"); + } + } + + // Get the time + void App::get_time() + { + PCF8563::RtcTime tm; + + if (rtc8563->get_rtc_time(tm)) + { + // Tue 25 Feb 2020 - 1:08:00 PM + Log::info(TAG, "Time = {} {} {} {} - {} ", + PCF8563::DayOfWeekStrings[static_cast<int>(tm.weekdays)], + tm.days, + PCF8563::MonthStrings[static_cast<int>(tm.months)], + tm.years, + rtc8563->get_12hr_time_string(tm.hours24, tm.minutes, tm.seconds)); + } + else + { + Log::error(TAG, "Error reading RTC time"); + } + } + + // Set alarm - alarm will activate 12 minutes past any hour of any day of any month of any weekday. + void App::set_alarm() + { + Log::info(TAG, "********** Setting Alarm *********"); + PCF8563::AlarmTime tm; + tm.minute = 12; + tm.hour24 = 13; + tm.day = 25; + tm.weekday = PCF8563::DayOfWeek::Tuesday; + tm.ena_alrm_minute = true; + tm.ena_alrm_hour = false; + tm.ena_alrm_day = false; + tm.ena_alrm_weekday = false; + + if (!rtc8563->set_alarm_time(tm)) + { + Log::error(TAG, "Error setting ALARM time"); + } + } + + // Get Alarm + void App::get_alarm() + { + PCF8563::AlarmTime tm; + + if (rtc8563->get_alarm_time(tm)) + { + // Tue 25 - 1:12:00 PM + Log::info(TAG, "Alarm set for -> {} ", + rtc8563->get_12hr_time_string(tm.hour24, tm.minute, 0)); + } + else + { + Log::error(TAG, "Error reading ALARM time"); + } + } + + // Is alarm active + bool App::is_alarm_active() + { + bool is_active; + rtc8563->is_alarm_flag_active(is_active); + + return is_active; + } + + // Clear alarm + void App::clear_alarm_active() + { + rtc8563->clear_alarm_flag(); + } +} diff --git a/pool/shard007/C++/0092595_srcprojectwizardpage.cpp b/pool/shard007/C++/0092595_srcprojectwizardpage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0e7fa7445aaf305acab2a97df2f8a4fc3b51f172 --- /dev/null +++ b/pool/shard007/C++/0092595_srcprojectwizardpage.cpp @@ -0,0 +1,85 @@ +/**************************************************************************** +** +** Copyright (C) 2014 BlackBerry Limited. All rights reserved. +** Contact: BlackBerry Limited (blackberry-qt@qnx.com) +** +** This file is part of Qt Creator. +** +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +****************************************************************************/ + +#include "srcprojectwizardpage.h" +#include "ui_srcprojectwizardpage.h" + +#include <QDir> + +namespace Qnx { +namespace Internal { + +SrcProjectWizardPage::SrcProjectWizardPage(QWidget *parent) + : QWizardPage(parent), m_complete(false) +{ + ui = new Ui::SrcProjectWizardPage; + ui->setupUi(this); + + connect(ui->pathChooser, SIGNAL(pathChanged(QString)), this, SLOT(onPathChooserPathChanged(QString))); + + setPath(QDir::homePath()); +} + +SrcProjectWizardPage::~SrcProjectWizardPage() +{ + delete ui; +} + +void SrcProjectWizardPage::onPathChooserPathChanged(const QString &newPath) +{ + bool newComplete = ui->pathChooser->isValid(); + if (newComplete != m_complete) { + m_complete = newComplete; + emit completeChanged(); + } + if (newComplete) emit validPathChanged(newPath); +} + +QString SrcProjectWizardPage::projectName() const +{ + return path().section(QLatin1Char('/'), -1); +} + +QString SrcProjectWizardPage::path() const +{ + return Utils::FileName::fromUserInput(ui->pathChooser->path()).toString(); +} + +void SrcProjectWizardPage::setPath(const QString &path) +{ + ui->pathChooser->setPath(path); +} + +bool SrcProjectWizardPage::isComplete() const +{ + return m_complete; +} + +} // namespace Internal +} // namespace Qnx diff --git a/pool/shard007/C++/0092600_main3.cpp b/pool/shard007/C++/0092600_main3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7e71f1e4e0a2a1845dc712500c470c93e629a57b --- /dev/null +++ b/pool/shard007/C++/0092600_main3.cpp @@ -0,0 +1,344 @@ +/******************************************************* + + ¡¾µ¥¸ö3DÈý½ÇÐεÄäÖȾ¡¿ + 1.¼ÓÔØµÄÎïÌå: ÊÖ¹¤´´½¨Ò»¸ö¶à±ßÐÎ + 2.Ïà»úÀàÐÍ: Å·À­Ïà»ú£¬Î»Öù̶¨£¬ÊÓҰΪ90¶È£¬ÊÓÆ½ÃæÊǹéÒ»»¯µÄ + 3.ͶӰÀàÐÍ: ÏȽøÐÐ͸Êӱ任£¬È»ºó½øÐÐÊӿڱ任 + 4.3DÁ÷Ë®ÏßʹÓõļÆËã·½·¨: ËùÒÔ·½·¨¶¼Ê¹ÓÃÊÖ¹¤¼ÆËã·½·¨£¬²»»ùÓÚ¾ØÕó + 5.±³ÃæÏû³ý:ûÓÐÖ´ÐÐ + 6.ÎïÌåÌÞ³ý: ûÓÐÖ´ÐÐ + 7.äÖȾ·½Ê½: °üº¬µ¥¸ö¶à±ßÐεÄäÖȾÁбí + + +*********************************************************/ + +#define WIN32_LEAN_AND_MEAN //²»°üÀ¨ MFCÏà¹ØµÄ + +#pragma comment (lib,"dxguid.lib")//GUIDµÄ¶¨Òå°üÀ¨ + +#include "HCLib\HCDXBuilder.h" +#include "HCLib\HCInput.h" +#include "HCLib\HCMacros.h" +#include "HCLib\HCUtility.h" +#include "ObjectDef.h" +#include "PLGLoader.h" +#include "RenderPipeline3DV1.h" +#include "Draw3DV1.h" +#include "Math3D.h" +#include "Material.h" +#include "Light.h" + + +#define WINDOW_WIDTH 800 +#define WINDOW_HEIGHT 600 +#define SCREEN_BPP16 16 + +// object defines +#define NUM_OBJECTS 16 +#define OBJECT_SPACING 250 + +#define APP_CLASS_NAME "hebiduClass" + +#define WINDOW_TITLE "3DÏß¿òÒýÇæ²âÊÔ2" //´°¿ÚµÄ±êÌâ + +//functions declaration +int App_Init(void *params = NULL,int num_params=0); +int App_Main(void *params = NULL,int num_params=0); +int App_Shutdown(void *params = NULL,int num_params=0); + + +//variable +HCDXBuilder hcdxBuilder; +HCInput hcInput; +HCLog hcLog; +CMath3D math3d; +float sin_look[361]; +float cos_look[361]; +bool bClosed = false; +bool pausing = false; + +/// +//²âÊÔÊý¾Ý +// +/////////////////////////////////////////////////////////////////// + +//3D±ØÐëµÄÀà +CCamera4DV1 cam; +CRenderList4DV1 rendList; +CDraw3DV1 draw3d; +CRenderPipeline3DV1 rpl3d; +//³õʼ»¯Á¿ +CPoint4D cam_pos; +CPoint4D cam_target; +CVector4D cam_dir; +CVector4D vscale,vpos,vrot;// + + + +//ÓÃÓÚÁ¢·½Ìå +CPlgLoader plgloader; +CObject4DV1 tank; + +/////////////////////////////////////////////////////////////////////////// +LRESULT CALLBACK WindowProc(HWND hwnd,UINT uMsg,WPARAM wparam,LPARAM lparam) +{ + switch(uMsg) + { + case WM_DESTROY: + { + PostQuitMessage(0); + return 0; + }break; + default:break; + } + return DefWindowProc(hwnd,uMsg,wparam,lparam); +} + +int WINAPI WinMain(HINSTANCE hinstance , HINSTANCE hpreinstance, + LPSTR lpcmdline,int ncmdshow) +{ + +#ifndef TO_FILE_HBD + freopen("d:\\test2_out.txt", "w", stdout); + freopen("d:\\test2_err.txt", "w", stderr); +#endif + + hcLog.Open_Error_File(); + if(hcdxBuilder.RegisterWndClassEx(WindowProc,hinstance,APP_CLASS_NAME,CS_DBLCLKS | CS_OWNDC | + CS_HREDRAW | CS_VREDRAW) == FALSE) + { + hcLog.Write_Error("\n WinMain::hcdxBuilder.RegisterWndClassEx Failed"); + return 0; + } + if(hcdxBuilder.CreateWndClassEx(WINDOW_TITLE,SCREEN_FULLSCREEN,0,0,WINDOW_WIDTH,WINDOW_HEIGHT) == FALSE) + { + hcLog.Write_Error("\n WinMain::hcdxBuilder.CreateWndClassEx Failed"); + return 0; + } + + if(App_Init() != 1) + { + + hcLog.Write_Error("\n WinMain::hcdxBuilder Failed"); + return 0; + } + MSG msg; + + while(TRUE) + { + if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)) + { + if(msg.message == WM_QUIT) + { + break; + } + TranslateMessage(&msg); + + DispatchMessage(&msg); + } + App_Main(); + + } + + App_Shutdown(); + hcLog.Close_Error_File(); + return msg.wParam; +} +char buffer[2048]; +int App_Init(void *params ,int num_params) +{ + + // seed random number generator + srand(Start_Clock()); + math3d.Build_Sin_Cos_Tables(cos_look,sin_look); + if(FAILED(hcdxBuilder.DDraw_Init(WINDOW_WIDTH,WINDOW_HEIGHT,SCREEN_BPP16,SCREEN_FULLSCREEN))) + { + hcLog.Write_Error("\n App_Init FAILED!"); + return 0; + } + if(FAILED(hcInput.DInput_Init(hcdxBuilder.main_instance))) + { + hcLog.Write_Error("\n App_Init hcInput.DInput_Init FAILED!"); + return 0; + } + if(FAILED(hcInput.DInput_Init_Keyboard(hcdxBuilder.main_hwnd))) + { + hcLog.Write_Error("\n App_Init hcInput.DInput_Init_Keyboard Failed!"); + return 0; + } + + RECT screen_rect = + {0,0,hcdxBuilder.screen_width - 1,hcdxBuilder.screen_height-1}; + hcdxBuilder.lpddclipper = hcdxBuilder.DDraw_Attach_Clipper(hcdxBuilder.lpddsback,1,&screen_rect); + draw3d.SetClipRect(0,0,hcdxBuilder.screen_width- 1 ,hcdxBuilder.screen_height-1); + + + cam_pos.SetXYZW(0,0,0,1); + cam_target.SetXYZW(0,0,0,1); + cam_dir.SetXYZW(0,0,0,1); + + + vscale.SetXYZW(5,25,5,1); + vpos.SetXYZW(0,0,0,1); + vrot.SetXYZW(0,0,0,1); + + + + + + cam.Init(CAM_MODEL_UVN, + cam_pos,cam_dir,NULL, + 50.0,8000.0,90.0,WINDOW_WIDTH,WINDOW_HEIGHT); + + +// plgloader.Load_Object4DV1_PLG(tank,"asset\\tank1.plg",vscale,vpos,vrot,hcdxBuilder.dd_pixel_format); + + plgloader.Load_Object4DV1_PLG(tank,"asset\\cube2.plg",vscale,vpos,vrot,hcdxBuilder.dd_pixel_format); + + tank.m_world_pos.SetX(0); + tank.m_world_pos.SetY(0); + tank.m_world_pos.SetZ(0); + return 1; +} +int App_Shutdown(void *params,int num_params) +{ + hcdxBuilder.DDraw_Shutdown(); + hcInput.DInput_Release_Keyboard(); + hcInput.DInput_Shutdown(); + return 1; +} + +float view_angle = 0; + +int App_Main(void *params ,int num_params) +{ + + + static CMatrix44 mrot;//Ðýת + + static float ang_x = 0,ang_y = 5,ang_z = 0; + + // ÓÃÓÚÐýתÏà»ú + static float camera_distance = 1750; + + char work_string[256]; // temp string + Start_Clock(); + + + hcdxBuilder.DDraw_Fill_Surface(hcdxBuilder.lpddsback,0); + + if(hcInput.DInput_Read_Keyboard() != 1) + { + hcLog.Write_Error("\n App_Main::hcInput.DInput_Read_Keyboard FAILED!"); + return 0; + } + + + rendList.Reset_RenderListV1(); + ang_x = 0; + ang_y = 1; + ang_z = 0; + + + //tank.Reset_Object(); + + rpl3d.Build_XYZ_Rotation_Matrix44(ang_x,ang_y,ang_z,mrot); + + rpl3d.Transform_Object(tank,mrot,TRANSFORM_LOCAL_ONLY,1); + + if(!pausing){ + cam.m_pos.SetX(camera_distance*math3d.Fast_Cos(view_angle)); + cam.m_pos.SetY(camera_distance*math3d.Fast_Sin(view_angle)); + cam.m_pos.SetZ(2*camera_distance*math3d.Fast_Sin(view_angle)); + + + if ((view_angle+=1)>=360) + view_angle = 0; + } + + cam.Buid_Cam4DV1_Matrix_UVN(UVN_MODE_SIMPLE); + + strcpy(buffer,"Objects Culled: "); + + + + for (int x=-NUM_OBJECTS/2; x < NUM_OBJECTS/2; x++) + + for (int z=-NUM_OBJECTS/2; z < NUM_OBJECTS/2; z++) + { + + tank.Reset_Object(); + + tank.m_world_pos.SetX( x*OBJECT_SPACING+OBJECT_SPACING/2); + tank.m_world_pos.SetY(0); + tank.m_world_pos.SetZ(z*OBJECT_SPACING+OBJECT_SPACING/2); + + + if (!rpl3d.Cull_Object(tank, cam, CULL_OBJECT_XYZ_PLANE)) + { + + // δ±»²Ã¼ô¾Í¿ÉÒÔäÖȾ£¬ + + rpl3d.Model_To_World_Object(tank); + rpl3d.Remove_Backfaces_Object(tank,cam); + rendList.Insert_Object(tank,0); + } // end if + else + { + + sprintf(work_string, "[%d, %d] ", x,z); + strcat(buffer, work_string); + } + + } // end for + + + draw3d.Draw_Text_GDI(buffer, 0, WINDOW_HEIGHT-20, RGB(0,255,0), hcdxBuilder.lpddsback); + + + rpl3d.Remove_Backfaces_Renderlist(rendList,cam); + rpl3d.World_To_Camera_RenderList(rendList,cam); + + + rpl3d.Camera_To_Perspective_Renderlist(rendList,cam); + + rpl3d.Perspective_To_Screen_Rendlist(rendList,cam); + + draw3d.Draw_Text_GDI("Press ESC to exit.", 0, 0, RGB(0,255,0), hcdxBuilder.lpddsback); + + + + //»æÖÆ + hcdxBuilder.DDraw_Lock_Back_Surface(); + + draw3d.Draw_RenderList4DV1_Wire16(rendList,hcdxBuilder.Get_Back_Buffer(),hcdxBuilder.Get_Back_lPitch()); + + hcdxBuilder.DDraw_Unlock_Back_Surface(); + + hcdxBuilder.DDraw_Flip(); + + Wait_Clock(30); + + + + + if (KEY_DOWN(VK_ESCAPE) || hcInput.keyboard_state[DIK_ESCAPE]) + { + PostMessage(hcdxBuilder.main_hwnd, WM_DESTROY,0,0); + + } + + + + + if (KEY_DOWN(VK_SPACE) || hcInput.keyboard_state[DIK_SPACE]) + { + + pausing = !pausing; + + } + + + + return 1; +} diff --git a/pool/shard007/C++/0092604_GradientStep.cpp b/pool/shard007/C++/0092604_GradientStep.cpp new file mode 100644 index 0000000000000000000000000000000000000000..acd7e929d8418ee9ea9ba6a79b1ed2b3b3474bd2 --- /dev/null +++ b/pool/shard007/C++/0092604_GradientStep.cpp @@ -0,0 +1,147 @@ +/* + * rele, + * + * + * Copyright (C) 2016 Davide Tateo & Matteo Pirotta + * Versione 1.0 + * + * This file is part of rele. + * + * rele is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * rele is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with rele. If not, see <http://www.gnu.org/licenses/>. + */ +#include "rele/algorithms/step_rules/GradientStep.h" + +using namespace arma; + +namespace ReLe +{ + +vec GradientStep::computeGradientInMetric(const vec& gradient, const mat& metric, bool inverse) +{ + vec g; + if(inverse) + { + g = metric*gradient; + } + else + { + if(rank(metric) == metric.n_rows) + g = solve(metric, gradient); + else + g = pinv(metric)*gradient; + } + + return g; +} + +ConstantGradientStep::ConstantGradientStep(double alpha): alpha(alpha) +{ + +} + +vec ConstantGradientStep::operator()(const vec& gradient) +{ + return alpha*gradient; +} + +vec ConstantGradientStep::operator()(const vec& gradient, + const vec& nat_gradient) +{ + auto& self = *this; + return self(nat_gradient); +} + +vec ConstantGradientStep::operator()(const vec& gradient, + const mat& metric, + bool inverse) +{ + auto& self = *this; + return self(computeGradientInMetric(gradient, metric, inverse)); +} + + + +void ConstantGradientStep::reset() +{ +} + + +VectorialGradientStep::VectorialGradientStep(const vec& alpha): alpha(alpha) +{ + +} + +vec VectorialGradientStep::operator()(const vec& gradient) +{ + return alpha%gradient; +} + +vec VectorialGradientStep::operator()(const vec& gradient, + const vec& nat_gradient) +{ + auto& self = *this; + return self(nat_gradient); +} + +vec VectorialGradientStep::operator()(const vec& gradient, + const mat& metric, + bool inverse) +{ + auto& self = *this; + return self(computeGradientInMetric(gradient, metric, inverse)); +} + + + +void VectorialGradientStep::reset() +{ +} + +AdaptiveGradientStep::AdaptiveGradientStep(double eps): stepValue(eps) +{ +} + +vec AdaptiveGradientStep::operator()(const vec& gradient) +{ + auto& self = *this; + return self(gradient, gradient); +} + +vec AdaptiveGradientStep::operator()(const vec& gradient, + const vec& nat_gradient) +{ + double tmp = as_scalar(gradient.t() * nat_gradient); + double lambda = sqrt(tmp / (4 * stepValue)); + lambda = std::max(lambda, 1e-8); // to avoid numerical problems + double step_length = 1.0 / (2.0 * lambda); + + return step_length*nat_gradient; +} + +vec AdaptiveGradientStep::operator()(const vec& gradient, + const mat& metric, + bool inverse) +{ + auto& self = *this; + mat nat_grad = computeGradientInMetric(gradient, metric, inverse); + return self(gradient, nat_grad); +} + + +void AdaptiveGradientStep::reset() +{ +} + + +} diff --git a/pool/shard007/C++/0092614_Inheritance.cpp b/pool/shard007/C++/0092614_Inheritance.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bf0e78f3e6e8206c75f893000510cb3899bde6ef --- /dev/null +++ b/pool/shard007/C++/0092614_Inheritance.cpp @@ -0,0 +1,29 @@ +#include <cprocessing/cprocessing.hpp> +#include "SpinArm.hpp" +#include "SpinSpots.hpp" + +/** + * Inheritance + * + * A class can be defined using another class as a foundation. In object-oriented + * programming terminology, one class can inherit fi elds and methods from another. + * An object that inherits from another is called a subclass, and the object it + * inherits from is called a superclass. A subclass extends the superclass. + */ + +SpinSpots * spots; +SpinArm * arm; + +void setup() { + size(640, 360); + arm = new SpinArm(width/2, height/2, 0.01); + spots = new SpinSpots(width/2, height/2, -0.02, 90.0); +} + +void draw() { + background(204); + arm->update(); + arm->display(); + spots->update(); + spots->display(); +} \ No newline at end of file diff --git a/pool/shard007/C++/0092635_engine_cpp.cpp b/pool/shard007/C++/0092635_engine_cpp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5fbf46759d331e84aedf64c63442ee76957314f2 --- /dev/null +++ b/pool/shard007/C++/0092635_engine_cpp.cpp @@ -0,0 +1,136 @@ +/* + Copyright (C) 2009 - 2017 by Yurii Chernyi <terraninfo@terraninfo.net> + Part of the Battle for Wesnoth Project http://www.wesnoth.org/ + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY. + + See the COPYING file for more details. +*/ + +/** + * CPP AI Support engine - creating specific ai components from config + * @file + */ + +#include "ai/composite/ai.hpp" +#include "ai/composite/aspect.hpp" +#include "ai/composite/goal.hpp" +#include "ai/composite/rca.hpp" +#include "ai/composite/stage.hpp" +#include "ai/default/engine_cpp.hpp" +#include "log.hpp" + +namespace ai { + +static lg::log_domain log_ai_engine_cpp("ai/engine/cpp"); +#define DBG_AI_ENGINE_CPP LOG_STREAM(debug, log_ai_engine_cpp) +#define LOG_AI_ENGINE_CPP LOG_STREAM(info, log_ai_engine_cpp) +#define ERR_AI_ENGINE_CPP LOG_STREAM(err, log_ai_engine_cpp) + +engine_cpp::engine_cpp( readonly_context &context, const config &cfg ) + : engine(context,cfg) +{ + name_ = "cpp"; +} + +engine_cpp::~engine_cpp() +{ +} + + +void engine_cpp::do_parse_aspect_from_config( const config &cfg, const std::string &id, std::back_insert_iterator<std::vector< aspect_ptr > > b ) +{ + const std::string aspect_factory_key = id+"*"+cfg["name"];//@note: hack which combines aspect id and name to get the std::string key of the aspect factory + aspect_factory::factory_map::iterator f = aspect_factory::get_list().find(aspect_factory_key); + if (f == aspect_factory::get_list().end()){ + ERR_AI_ENGINE_CPP << "side "<<ai_.get_side()<< " : UNKNOWN aspect["<<aspect_factory_key<<"]" << std::endl; + DBG_AI_ENGINE_CPP << "config snippet contains: " << std::endl << cfg << std::endl; + return; + } + aspect_ptr new_aspect = f->second->get_new_instance(ai_,cfg,id); + if (!new_aspect) { + ERR_AI_ENGINE_CPP << "side "<<ai_.get_side()<< " : UNABLE TO CREATE aspect, key=["<<aspect_factory_key<<"]"<< std::endl; + DBG_AI_ENGINE_CPP << "config snippet contains: " << std::endl << cfg << std::endl; + return; + } + *b = new_aspect; +} + + +void engine_cpp::do_parse_candidate_action_from_config( rca_context &context, const config &cfg, std::back_insert_iterator<std::vector< candidate_action_ptr > > b ){ + candidate_action_factory::factory_map::iterator f = candidate_action_factory::get_list().find(cfg["name"]); + if (f == candidate_action_factory::get_list().end()){ + ERR_AI_ENGINE_CPP << "side "<<ai_.get_side()<< " : UNKNOWN candidate_action["<<cfg["name"]<<"]"<< std::endl; + DBG_AI_ENGINE_CPP << "config snippet contains: " << std::endl << cfg << std::endl; + return; + } + candidate_action_ptr new_candidate_action = f->second->get_new_instance(context,cfg); + if (!new_candidate_action) { + ERR_AI_ENGINE_CPP << "side "<<ai_.get_side()<< " : UNABLE TO CREATE candidate_action["<<cfg["name"]<<"]"<< std::endl; + DBG_AI_ENGINE_CPP << "config snippet contains: " << std::endl << cfg << std::endl; + return; + } + *b = new_candidate_action; + +} + +void engine_cpp::do_parse_stage_from_config( ai_context &context, const config &cfg, std::back_insert_iterator<std::vector< stage_ptr > > b ) +{ + stage_factory::factory_map::iterator f = stage_factory::get_list().find(cfg["name"]); + if (f == stage_factory::get_list().end()){ + ERR_AI_ENGINE_CPP << "side "<<ai_.get_side()<< " : UNKNOWN stage["<<cfg["name"]<<"]"<< std::endl; + DBG_AI_ENGINE_CPP << "config snippet contains: " << std::endl << cfg << std::endl; + return; + } + stage_ptr new_stage = f->second->get_new_instance(context,cfg); + if (!new_stage) { + ERR_AI_ENGINE_CPP << "side "<<ai_.get_side()<< " : UNABLE TO CREATE stage["<<cfg["name"]<<"]"<< std::endl; + DBG_AI_ENGINE_CPP << "config snippet contains: " << std::endl << cfg << std::endl; + return; + } + *b = new_stage; +} + + +void engine_cpp::do_parse_goal_from_config(const config &cfg, std::back_insert_iterator<std::vector< goal_ptr > > b ) +{ + goal_factory::factory_map::iterator f = goal_factory::get_list().find(cfg["name"]); + if (f == goal_factory::get_list().end()){ + ERR_AI_ENGINE_CPP << "side "<<ai_.get_side()<< " : UNKNOWN goal["<<cfg["name"]<<"]"<< std::endl; + DBG_AI_ENGINE_CPP << "config snippet contains: " << std::endl << cfg << std::endl; + return; + } + goal_ptr new_goal = f->second->get_new_instance(ai_,cfg); + if (!new_goal || !new_goal->ok()) { + ERR_AI_ENGINE_CPP << "side "<<ai_.get_side()<< " : UNABLE TO CREATE goal["<<cfg["name"]<<"]"<< std::endl; + DBG_AI_ENGINE_CPP << "config snippet contains: " << std::endl << cfg << std::endl; + return; + } + *b = new_goal; +} + + +void engine_cpp::do_parse_engine_from_config(const config &cfg, std::back_insert_iterator<std::vector< engine_ptr > > b ) +{ + engine_factory::factory_map::iterator f = engine_factory::get_list().find(cfg["name"]); + if (f == engine_factory::get_list().end()){ + ERR_AI_ENGINE_CPP << "side "<<ai_.get_side()<< " : UNKNOWN engine["<<cfg["name"]<<"]"<< std::endl; + DBG_AI_ENGINE_CPP << "config snippet contains: " << std::endl << cfg << std::endl; + return; + } + engine_ptr new_engine = f->second->get_new_instance(ai_,cfg); + if (!new_engine) { + ERR_AI_ENGINE_CPP << "side "<<ai_.get_side()<< " : UNABLE TO CREATE engine["<<cfg["name"]<<"]"<< std::endl; + DBG_AI_ENGINE_CPP << "config snippet contains: " << std::endl << cfg << std::endl; + return; + } + *b = new_engine; +} + + +} //end of namespace ai diff --git a/pool/shard007/C++/0092637_NodeFactory.cpp b/pool/shard007/C++/0092637_NodeFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a7e86b72ab9169a14020c16951c4cf535113d009 --- /dev/null +++ b/pool/shard007/C++/0092637_NodeFactory.cpp @@ -0,0 +1,117 @@ +// Copyright (c) 2012-2015, The CryptoNote developers, The Bytecoin developers +// +// This file is part of Bytecoin. +// +// Bytecoin is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Bytecoin is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with Bytecoin. If not, see <http://www.gnu.org/licenses/>. + +// Copyright (c) 2012-2014, The CryptoNote developers, The Bytecoin developers +// +// This file is part of Bytecoin. +// +// Bytecoin is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Bytecoin is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with Bytecoin. If not, see <http://www.gnu.org/licenses/>. + +#include "NodeFactory.h" + +#include "node_rpc_proxy/NodeRpcProxy.h" +#include <memory> +#include <future> + +namespace PaymentService { + +class NodeRpcStub: public CryptoNote::INode { +public: + virtual ~NodeRpcStub() {} + virtual bool addObserver(CryptoNote::INodeObserver* observer) { return true; } + virtual bool removeObserver(CryptoNote::INodeObserver* observer) { return true; } + + virtual void init(const Callback& callback) { } + virtual bool shutdown() { return true; } + + virtual size_t getPeerCount() const { return 0; } + virtual uint64_t getLastLocalBlockHeight() const { return 0; } + virtual uint64_t getLastKnownBlockHeight() const { return 0; } + virtual uint64_t getLocalBlockCount() const override { return 0; } + virtual uint64_t getKnownBlockCount() const override { return 0; } + virtual uint64_t getLastLocalBlockTimestamp() const { return 0; } + + virtual void relayTransaction(const CryptoNote::Transaction& transaction, const Callback& callback) { callback(std::error_code()); } + virtual void getRandomOutsByAmounts(std::vector<uint64_t>&& amounts, uint64_t outsCount, + std::vector<CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount>& result, const Callback& callback) { callback(std::error_code()); } + virtual void getNewBlocks(std::list<crypto::hash>&& knownBlockIds, std::list<CryptoNote::block_complete_entry>& newBlocks, uint64_t& startHeight, const Callback& callback) { callback(std::error_code()); } + virtual void getTransactionOutsGlobalIndices(const crypto::hash& transactionHash, std::vector<uint64_t>& outsGlobalIndices, const Callback& callback) { callback(std::error_code()); } + + virtual void queryBlocks(std::list<crypto::hash>&& knownBlockIds, uint64_t timestamp, std::list<CryptoNote::BlockCompleteEntry>& newBlocks, + uint64_t& startHeight, const CryptoNote::INode::Callback& callback) { startHeight = 0; callback(std::error_code()); } + + virtual void getPoolSymmetricDifference(std::vector<crypto::hash>&& known_pool_tx_ids, crypto::hash known_block_id, + bool& is_bc_actual, std::vector<CryptoNote::Transaction>& new_txs, std::vector<crypto::hash>& deleted_tx_ids, + const Callback& callback) { callback(std::error_code()); } + +}; + + +class NodeInitObserver { +public: + NodeInitObserver() {} + + void initCompleted(std::error_code result) { + initPromise.set_value(result); + } + + void waitForInitEnd() { + auto future = initPromise.get_future(); + + std::error_code ec = future.get(); + if (ec) { + throw std::system_error(ec); + } + return; + } + +private: + std::promise<std::error_code> initPromise; +}; + +NodeFactory::NodeFactory() { +} + +NodeFactory::~NodeFactory() { +} + +CryptoNote::INode* NodeFactory::createNode(const std::string& daemonAddress, uint16_t daemonPort) { + std::unique_ptr<CryptoNote::INode> node(new CryptoNote::NodeRpcProxy(daemonAddress, daemonPort)); + + NodeInitObserver initObserver; + node->init(std::bind(&NodeInitObserver::initCompleted, &initObserver, std::placeholders::_1)); + initObserver.waitForInitEnd(); + + return node.release(); +} + +CryptoNote::INode* NodeFactory::createNodeStub() { + return new NodeRpcStub(); +} + +} diff --git a/pool/shard007/C++/0092643_bitchar.cpp b/pool/shard007/C++/0092643_bitchar.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bb3418b5760a8c20d0c05ccf54928fc1d2b93726 --- /dev/null +++ b/pool/shard007/C++/0092643_bitchar.cpp @@ -0,0 +1,43 @@ +#include "bitchar.h" + + +using namespace dog_engine_unit; + +void bitchar::set_bitchar(bitchar_type _bt){ + bt = _bt; + size = _bt.size; +} +bitchar_type bitchar::get_bitchar(){ + return bt; +} + +dog_point bitchar::get_size(){ + return size; +} + +void bitchar::update(){ + auto &de = get_dog_engine(); + //msg_box(string("size W:") + bt.size.x); + //msg_box(string("size H:") + bt.size.y); + bitchar_type::draw_bitchar_type(de,get_parent_pos_sum()+pos,bt); +} + +void bitchar::init(){ + node::init(); + + size = dog_point(0,0); +} + + + +bitchar *bitchar::create(bitchar_type _bt,dog_point _pos){ + auto b = new bitchar(); + b->init(); + b->set_bitchar(_bt); + b->set_pos(_pos); + return b; +} + +bitchar *bitchar::create(bitchar_type _bt){ + return bitchar::create(_bt,{0,0}); +} \ No newline at end of file diff --git a/pool/shard007/C++/0092650_workspace_event_handler.cc b/pool/shard007/C++/0092650_workspace_event_handler.cc new file mode 100644 index 0000000000000000000000000000000000000000..16d86ca6c423303663d7c6cefe755771557d528a --- /dev/null +++ b/pool/shard007/C++/0092650_workspace_event_handler.cc @@ -0,0 +1,177 @@ +// Copyright (c) 2012 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 "ash/wm/workspace/workspace_event_handler.h" + +#include "ash/screen_ash.h" +#include "ash/shell.h" +#include "ash/shell_delegate.h" +#include "ash/wm/property_util.h" +#include "ash/wm/window_util.h" +#include "ash/wm/workspace/workspace_window_resizer.h" +#include "ui/aura/client/aura_constants.h" +#include "ui/aura/window.h" +#include "ui/aura/window_delegate.h" +#include "ui/base/events/event.h" +#include "ui/base/events/event_utils.h" +#include "ui/base/hit_test.h" +#include "ui/compositor/scoped_layer_animation_settings.h" +#include "ui/gfx/screen.h" + +namespace ash { +namespace { + +void SingleAxisMaximize(aura::Window* window, const gfx::Rect& maximize_rect) { + gfx::Rect bounds_in_screen = + ScreenAsh::ConvertRectToScreen(window->parent(), window->bounds()); + + SetRestoreBoundsInScreen(window, bounds_in_screen); + window->SetBounds(maximize_rect); +} + +void SingleAxisUnmaximize(aura::Window* window, + const gfx::Rect& restore_bounds_in_screen) { + gfx::Rect restore_bounds = ScreenAsh::ConvertRectFromScreen( + window->parent(), restore_bounds_in_screen); + window->SetBounds(restore_bounds); + ClearRestoreBounds(window); +} + +void ToggleMaximizedState(aura::Window* window) { + if (GetRestoreBoundsInScreen(window)) { + if (window->GetProperty(aura::client::kShowStateKey) == + ui::SHOW_STATE_NORMAL) { + window->SetBounds(GetRestoreBoundsInParent(window)); + ClearRestoreBounds(window); + } else { + window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); + } + } else if (wm::CanMaximizeWindow(window)) { + window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); + } +} + +} // namespace + +namespace internal { + +WorkspaceEventHandler::WorkspaceEventHandler(aura::Window* owner) + : ToplevelWindowEventHandler(owner), + destroyed_(NULL) { +} + +WorkspaceEventHandler::~WorkspaceEventHandler() { + if (destroyed_) + *destroyed_ = true; +} + +void WorkspaceEventHandler::OnMouseEvent(ui::MouseEvent* event) { + aura::Window* target = static_cast<aura::Window*>(event->target()); + switch (event->type()) { + case ui::ET_MOUSE_MOVED: { + int component = + target->delegate()->GetNonClientComponent(event->location()); + multi_window_resize_controller_.Show(target, component, + event->location()); + break; + } + case ui::ET_MOUSE_ENTERED: + break; + case ui::ET_MOUSE_CAPTURE_CHANGED: + case ui::ET_MOUSE_EXITED: + break; + case ui::ET_MOUSE_PRESSED: { + // Maximize behavior is implemented as post-target handling so the target + // can cancel it. + if (ui::EventCanceledDefaultHandling(*event)) { + ToplevelWindowEventHandler::OnMouseEvent(event); + return; + } + + if (event->flags() & ui::EF_IS_DOUBLE_CLICK && + target->delegate()->GetNonClientComponent(event->location()) == + HTCAPTION && + !ash::Shell::IsForcedMaximizeMode()) { + bool destroyed = false; + destroyed_ = &destroyed; + ash::Shell::GetInstance()->delegate()->RecordUserMetricsAction( + ash::UMA_TOGGLE_MAXIMIZE_CAPTION_CLICK); + ToggleMaximizedState(target); + if (destroyed) + return; + destroyed_ = NULL; + } + multi_window_resize_controller_.Hide(); + HandleVerticalResizeDoubleClick(target, event); + break; + } + default: + break; + } + ToplevelWindowEventHandler::OnMouseEvent(event); +} + +void WorkspaceEventHandler::OnGestureEvent(ui::GestureEvent* event) { + aura::Window* target = static_cast<aura::Window*>(event->target()); + if (event->type() == ui::ET_GESTURE_TAP && + event->details().tap_count() == 2 && + target->delegate()->GetNonClientComponent(event->location()) == + HTCAPTION) { + ash::Shell::GetInstance()->delegate()->RecordUserMetricsAction( + ash::UMA_TOGGLE_MAXIMIZE_CAPTION_GESTURE); + ToggleMaximizedState(target); // |this| may be destroyed from here. + event->StopPropagation(); + return; + } + ToplevelWindowEventHandler::OnGestureEvent(event); +} + +void WorkspaceEventHandler::HandleVerticalResizeDoubleClick( + aura::Window* target, + ui::MouseEvent* event) { + gfx::Rect max_size(target->delegate()->GetMaximumSize()); + if (event->flags() & ui::EF_IS_DOUBLE_CLICK && + !wm::IsWindowMaximized(target)) { + int component = + target->delegate()->GetNonClientComponent(event->location()); + gfx::Rect work_area = + Shell::GetScreen()->GetDisplayNearestWindow(target).work_area(); + const gfx::Rect* restore_bounds = + GetRestoreBoundsInScreen(target); + if (component == HTBOTTOM || component == HTTOP) { + // Don't maximize vertically if the window has a max height defined. + if (max_size.height() != 0) + return; + if (restore_bounds && + (target->bounds().height() == work_area.height() && + target->bounds().y() == work_area.y())) { + SingleAxisUnmaximize(target, *restore_bounds); + } else { + SingleAxisMaximize(target, + gfx::Rect(target->bounds().x(), + work_area.y(), + target->bounds().width(), + work_area.height())); + } + } else if (component == HTLEFT || component == HTRIGHT) { + // Don't maximize horizontally if the window has a max width defined. + if (max_size.width() != 0) + return; + if (restore_bounds && + (target->bounds().width() == work_area.width() && + target->bounds().x() == work_area.x())) { + SingleAxisUnmaximize(target, *restore_bounds); + } else { + SingleAxisMaximize(target, + gfx::Rect(work_area.x(), + target->bounds().y(), + work_area.width(), + target->bounds().height())); + } + } + } +} + +} // namespace internal +} // namespace ash diff --git a/pool/shard007/C++/0092657_speechbubble.cpp b/pool/shard007/C++/0092657_speechbubble.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9bd85ad43589fa0dbc6adc2697d3fab097d62e93 --- /dev/null +++ b/pool/shard007/C++/0092657_speechbubble.cpp @@ -0,0 +1,95 @@ +/* + * Speech bubbles + * Copyright (C) 2008 The Legend of Mazzeroth Development Team + * Copyright (C) 2008-2009 The Mana World Development Team + * Copyright (C) 2009-2010 The Mana Developers + * Copyright (C) 2011-2013 The ManaPlus Developers + * + * This file is part of The ManaPlus Client. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "gui/speechbubble.h" + +#include "gui/gui.h" +#include "gui/sdlfont.h" + +#include "gui/widgets/label.h" +#include "gui/widgets/textbox.h" + +#include <guichan/font.hpp> + +#include "debug.h" + +SpeechBubble::SpeechBubble() : + Popup("Speech", "speechbubble.xml"), + mText(), + mCaption(new Label(this)), + mSpeechBox(new TextBox(this)) +{ + setContentSize(140, 46); + setMinWidth(29); + setMinHeight(29); + + mCaption->setFont(boldFont); + mSpeechBox->setEditable(false); + mSpeechBox->setOpaque(false); + mSpeechBox->setForegroundColorAll(getThemeColor(Theme::BUBBLE_TEXT), + getThemeColor(Theme::BUBBLE_TEXT_OUTLINE)); + + add(mCaption); + add(mSpeechBox); +} + +void SpeechBubble::setCaption(const std::string &name, + const gcn::Color *const color1, + const gcn::Color *const color2) +{ + mCaption->setCaption(name); + mCaption->adjustSize(); + mCaption->setForegroundColorAll(*color1, *color2); +} + +void SpeechBubble::setText(const std::string &text, const bool showName) +{ + if (text == mText && (mCaption->getWidth() <= mSpeechBox->getMinWidth())) + return; + + mSpeechBox->setForegroundColorAll(getThemeColor(Theme::BUBBLE_TEXT), + getThemeColor(Theme::BUBBLE_TEXT_OUTLINE)); + + int width = mCaption->getWidth() + 2 * getPadding(); + mSpeechBox->setTextWrapped(text, 130 > width ? 130 : width); + const int speechWidth = mSpeechBox->getMinWidth() + 2 * getPadding(); + + const int fontHeight = getFont()->getHeight(); + const int nameHeight = showName ? mCaption->getHeight() + + (getPadding() / 2) : 0; + const int numRows = mSpeechBox->getNumberOfRows(); + const int height = (numRows * fontHeight) + nameHeight + getPadding(); + + if (width < speechWidth) + width = speechWidth; + + width += 2 * getPadding(); + + setContentSize(width, height); + + const int xPos = ((getWidth() - width) / 2); + const int yPos = ((getHeight() - height) / 2) + nameHeight; + + mCaption->setPosition(xPos, getPadding()); + mSpeechBox->setPosition(xPos, yPos); +} diff --git a/pool/shard007/C++/0092662_2.cc b/pool/shard007/C++/0092662_2.cc new file mode 100644 index 0000000000000000000000000000000000000000..7561fbda35449a355527b06b87707089e276b2be --- /dev/null +++ b/pool/shard007/C++/0092662_2.cc @@ -0,0 +1,79 @@ +// 2010-12-19 Paolo Carlini <paolo.carlini@oracle.com> +// +// Copyright (C) 2010 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// <http://www.gnu.org/licenses/>. +// +// { dg-options "-std=gnu++0x" } +// { dg-require-string-conversions "" } + +#include <ext/vstring.h> +#include <testsuite_hooks.h> + +void test01() +{ + bool test __attribute__((unused)) = true; + using __gnu_cxx::__vstring; + using std::move; + + __vstring s01("abc"); + s01.reserve(30); + __vstring s02("def"); + s02.reserve(30); + VERIFY( move(s01) + move(s02) == __vstring("abcdef") ); + + __vstring s03("abcdefghijklmnopqrstuvw"); + __vstring s04("xyz"); + s04.reserve(30); + VERIFY( move(s03) + move(s04) == __vstring("abcdefghijklmnopqrstuvwxyz") ); + + __vstring s05("abc"); + s05.reserve(30); + __vstring s06("defghijklmnopqrstuvwxyz"); + VERIFY( move(s05) + move(s06) == __vstring("abcdefghijklmnopqrstuvwxyz") ); + + const __vstring sc1("abc"); + __vstring s07("def"); + s07.reserve(30); + VERIFY( sc1 + move(s07) == __vstring("abcdef") ); + + const __vstring sc2("def"); + __vstring s08("abc"); + s08.reserve(30); + VERIFY( move(s08) + sc2 == __vstring("abcdef") ); + + __vstring s09("abc"); + s09.reserve(30); + VERIFY( move(s09) + 'd' == __vstring("abcd") ); + + __vstring s10("abc"); + s10.reserve(30); + VERIFY( move(s10) + "def" == __vstring("abcdef") ); + + __vstring s11("bcd"); + s11.reserve(30); + VERIFY( 'a' + move(s11) == __vstring("abcd") ); + + __vstring s12("def"); + s12.reserve(30); + VERIFY( "abc" + move(s12) == __vstring("abcdef") ); +} + +int main() +{ + test01(); + return 0; +} diff --git a/pool/shard007/C++/0092663_scheduler_tests.cpp b/pool/shard007/C++/0092663_scheduler_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..16bf5f10558e50d44291e6041e0a4172100cdad3 --- /dev/null +++ b/pool/shard007/C++/0092663_scheduler_tests.cpp @@ -0,0 +1,119 @@ +// Copyright (c) 2012-2015 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "random.h" +#include "scheduler.h" + +#include "test/test_dankcoin.h" + +#include <boost/bind.hpp> +#include <boost/random/mersenne_twister.hpp> +#include <boost/random/uniform_int_distribution.hpp> +#include <boost/thread.hpp> +#include <boost/test/unit_test.hpp> + +BOOST_AUTO_TEST_SUITE(scheduler_tests) + +static void microTask(CScheduler& s, boost::mutex& mutex, int& counter, int delta, boost::chrono::system_clock::time_point rescheduleTime) +{ + { + boost::unique_lock<boost::mutex> lock(mutex); + counter += delta; + } + boost::chrono::system_clock::time_point noTime = boost::chrono::system_clock::time_point::min(); + if (rescheduleTime != noTime) { + CScheduler::Function f = boost::bind(µTask, boost::ref(s), boost::ref(mutex), boost::ref(counter), -delta + 1, noTime); + s.schedule(f, rescheduleTime); + } +} + +static void MicroSleep(uint64_t n) +{ +#if defined(HAVE_WORKING_BOOST_SLEEP_FOR) + boost::this_thread::sleep_for(boost::chrono::microseconds(n)); +#elif defined(HAVE_WORKING_BOOST_SLEEP) + boost::this_thread::sleep(boost::posix_time::microseconds(n)); +#else + //should never get here + #error missing boost sleep implementation +#endif +} + +BOOST_AUTO_TEST_CASE(manythreads) +{ + seed_insecure_rand(false); + + // Stress test: hundreds of microsecond-scheduled tasks, + // serviced by 10 threads. + // + // So... ten shared counters, which if all the tasks execute + // properly will sum to the number of tasks done. + // Each task adds or subtracts from one of the counters a + // random amount, and then schedules another task 0-1000 + // microseconds in the future to subtract or add from + // the counter -random_amount+1, so in the end the shared + // counters should sum to the number of initial tasks performed. + CScheduler microTasks; + + boost::mutex counterMutex[10]; + int counter[10] = { 0 }; + boost::random::mt19937 rng(insecure_rand()); + boost::random::uniform_int_distribution<> zeroToNine(0, 9); + boost::random::uniform_int_distribution<> randomMsec(-11, 1000); + boost::random::uniform_int_distribution<> randomDelta(-1000, 1000); + + boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now(); + boost::chrono::system_clock::time_point now = start; + boost::chrono::system_clock::time_point first, last; + size_t nTasks = microTasks.getQueueInfo(first, last); + BOOST_CHECK(nTasks == 0); + + for (int i = 0; i < 100; i++) { + boost::chrono::system_clock::time_point t = now + boost::chrono::microseconds(randomMsec(rng)); + boost::chrono::system_clock::time_point tReschedule = now + boost::chrono::microseconds(500 + randomMsec(rng)); + int whichCounter = zeroToNine(rng); + CScheduler::Function f = boost::bind(µTask, boost::ref(microTasks), + boost::ref(counterMutex[whichCounter]), boost::ref(counter[whichCounter]), + randomDelta(rng), tReschedule); + microTasks.schedule(f, t); + } + nTasks = microTasks.getQueueInfo(first, last); + BOOST_CHECK(nTasks == 100); + BOOST_CHECK(first < last); + BOOST_CHECK(last > now); + + // As soon as these are created they will start running and servicing the queue + boost::thread_group microThreads; + for (int i = 0; i < 5; i++) + microThreads.create_thread(boost::bind(&CScheduler::serviceQueue, µTasks)); + + MicroSleep(600); + now = boost::chrono::system_clock::now(); + + // More threads and more tasks: + for (int i = 0; i < 5; i++) + microThreads.create_thread(boost::bind(&CScheduler::serviceQueue, µTasks)); + for (int i = 0; i < 100; i++) { + boost::chrono::system_clock::time_point t = now + boost::chrono::microseconds(randomMsec(rng)); + boost::chrono::system_clock::time_point tReschedule = now + boost::chrono::microseconds(500 + randomMsec(rng)); + int whichCounter = zeroToNine(rng); + CScheduler::Function f = boost::bind(µTask, boost::ref(microTasks), + boost::ref(counterMutex[whichCounter]), boost::ref(counter[whichCounter]), + randomDelta(rng), tReschedule); + microTasks.schedule(f, t); + } + + // Drain the task queue then exit threads + microTasks.stop(true); + microThreads.join_all(); // ... wait until all the threads are done + + int counterSum = 0; + for (int i = 0; i < 10; i++) { + BOOST_CHECK(counter[i] != 0); + counterSum += counter[i]; + } + BOOST_CHECK_EQUAL(counterSum, 200); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/pool/shard007/C++/0092674_mo.cpp b/pool/shard007/C++/0092674_mo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bb7b7e308291a148346fe600b2d18754faab302b --- /dev/null +++ b/pool/shard007/C++/0092674_mo.cpp @@ -0,0 +1,86 @@ +/* +* Copyright 2012 The MO 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 <stdlib.h> +#include "mo.h" +#include "mo_logger.h" +#include "mo_tick.h" +#include "mo_timer.h" +#include "mo_event.h" +#include "mo_process.h" +#include "mo_pipe.h" +#include "mo_tcp.h" +#include "mo_udp.h" +#include "mo_fs.h" +#include "mo_tty.h" +#include "mo_module.h" + +namespace Mo { + +SCM Main::Run(){ + int r = uv_run(uv_default_loop()); + if(r) { + Logger::Err("uv_run failed! : %d", r); + return SCM_BOOL_F; + } + return SCM_BOOL_T; +} + +void Main::RegisterSCMFunctions(){ + scm_c_define_gsubr("run-mo", 0, 0, 0, (void *)Run); + + Logger::RegisterSCMFunctions(); + Event::RegisterSCMFunctions(); + + Tick::RegisterSCMFunctions(); + Timer::RegisterSCMFunctions(); + Process::RegisterSCMFunctions(); + Pipe::RegisterSCMFunctions(); + TCP::RegisterSCMFunctions(); + UDP::RegisterSCMFunctions(); + FS::RegisterSCMFunctions(); + TTY::RegisterSCMFunctions(); + + Module::RegisterSCMFunctions(); + +} + +void Main::Init(){ + + init_mo_object_type(); + + // logger and event should be initialized first + Logger::Init(); + Event::Init(); + + uv_loop_t * loop = uv_loop_new(); + assert(loop!=NULL); + + Tick::Init(); + Timer::Init(); + Process::Init(); + Pipe::Init(); + TCP::Init(); + UDP::Init(); + FS::Init(); + TTY::Init(); + + Module::Init(); + +} + +} diff --git a/pool/shard007/C++/0092680_CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_loop_72a.cpp b/pool/shard007/C++/0092680_CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_loop_72a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7b9e90b541bb8c229212dccb1c067c931ecb6002 --- /dev/null +++ b/pool/shard007/C++/0092680_CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_loop_72a.cpp @@ -0,0 +1,110 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_loop_72a.cpp +Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE805.string.label.xml +Template File: sources-sink-72a.tmpl.cpp +*/ +/* + * @description + * CWE: 121 Stack Based Buffer Overflow + * BadSource: Set data pointer to the bad buffer + * GoodSource: Set data pointer to the good buffer + * Sinks: loop + * BadSink : Copy string to data using a loop + * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files + * + * */ + +#include "std_testcase.h" +#include <vector> + +#include <wchar.h> + +using namespace std; + +namespace CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_loop_72 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink(vector<wchar_t *> dataVector); + +void bad() +{ + wchar_t * data; + vector<wchar_t *> dataVector; + wchar_t * dataBadBuffer = (wchar_t *)ALLOCA(50*sizeof(wchar_t)); + wchar_t * dataGoodBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t)); + /* FLAW: Set a pointer to a "small" buffer. This buffer will be used in the sinks as a destination + * buffer in various memory copying functions using a "large" source buffer. */ + data = dataBadBuffer; + data[0] = L'\0'; /* null terminate */ + /* Put data in a vector */ + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + badSink(dataVector); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good function declarations */ + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(vector<wchar_t *> dataVector); + +static void goodG2B() +{ + wchar_t * data; + vector<wchar_t *> dataVector; + wchar_t * dataBadBuffer = (wchar_t *)ALLOCA(50*sizeof(wchar_t)); + wchar_t * dataGoodBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t)); + /* FIX: Set a pointer to a "large" buffer, thus avoiding buffer overflows in the sinks. */ + data = dataGoodBuffer; + data[0] = L'\0'; /* null terminate */ + /* Put data in a vector */ + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + goodG2BSink(dataVector); +} + +void good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +using namespace CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_loop_72; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard007/C++/0092690_exceptions_badbit_throw.cc b/pool/shard007/C++/0092690_exceptions_badbit_throw.cc new file mode 100644 index 0000000000000000000000000000000000000000..08eefdb732cd2ce1dc7a912ff833adf8ec9f4959 --- /dev/null +++ b/pool/shard007/C++/0092690_exceptions_badbit_throw.cc @@ -0,0 +1,74 @@ +// 2003-03-08 Jerry Quinn <jlquinn@optonline.net> + +// Copyright (C) 2003-2021 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// <http://www.gnu.org/licenses/>. + +#include <locale> +#include <sstream> +#include <testsuite_hooks.h> +#include <testsuite_io.h> + +// libstdc++/9561 +template<typename T> +void test_badbit() +{ + using namespace std; + + locale loc(locale::classic(), new __gnu_test::fail_num_get_char); + istringstream stream("jaylib - champion sound"); + stream.imbue(loc); + + stream.exceptions(ios_base::badbit); + VERIFY( stream.rdstate() == ios_base::goodbit ); + + try + { + T i; + stream >> i; + VERIFY( false ); + } + catch (const __gnu_test::facet_error&) + { + // stream should set badbit and rethrow facet_error. + VERIFY( stream.bad() ); + VERIFY( (stream.rdstate() & ios_base::failbit) == 0 ); + VERIFY( !stream.eof() ); + } + catch (...) + { + VERIFY(false); + } +} + + +int main() +{ + test_badbit<bool>(); + test_badbit<short>(); + test_badbit<unsigned short>(); + test_badbit<int>(); + test_badbit<unsigned int>(); + test_badbit<long>(); + test_badbit<unsigned long>(); + + test_badbit<float>(); + test_badbit<double>(); + + test_badbit<void*>(); + + return 0; +} diff --git a/pool/shard007/C++/0092692_put_file_request.cc b/pool/shard007/C++/0092692_put_file_request.cc new file mode 100644 index 0000000000000000000000000000000000000000..602b420ba09d5e0e05cf839c2bcb1a0132a26dff --- /dev/null +++ b/pool/shard007/C++/0092692_put_file_request.cc @@ -0,0 +1,283 @@ +/* + + Copyright (c) 2013, 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 <algorithm> +#include "application_manager/commands/mobile/put_file_request.h" + +#include "application_manager/policies/policy_handler.h" +#include "application_manager/application_impl.h" + +#include "utils/file_system.h" + +namespace application_manager { + +namespace commands { + +PutFileRequest::PutFileRequest(const MessageSharedPtr& message, + ApplicationManager& application_manager) + : CommandRequestImpl(message, application_manager) + , offset_(0) + , sync_file_name_() + , length_(0) + , file_type_(mobile_apis::FileType::INVALID_ENUM) + , is_persistent_file_(false) {} + +PutFileRequest::~PutFileRequest() {} + +void PutFileRequest::Run() { + LOG4CXX_AUTO_TRACE(logger_); + + ApplicationSharedPtr application = + application_manager_.application(connection_key()); + smart_objects::SmartObject response_params = + smart_objects::SmartObject(smart_objects::SmartType_Map); + + if (!application) { + LOG4CXX_ERROR(logger_, "Application is not registered"); + SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED); + return; + } + + if (mobile_api::HMILevel::HMI_NONE == application->hmi_level() && + application_manager_.get_settings().put_file_in_none() <= + application->put_file_in_none_count()) { + // If application is in the HMI_NONE level the quantity of allowed + // PutFile request is limited by the configuration profile + LOG4CXX_ERROR(logger_, + "Too many requests from the app with HMILevel HMI_NONE "); + SendResponse(false, + mobile_apis::Result::REJECTED, + "Too many requests from the app with HMILevel HMI_NONE", + &response_params); + return; + } + + if (!(*message_)[strings::params].keyExists(strings::binary_data)) { + LOG4CXX_ERROR(logger_, "Binary data empty"); + SendResponse(false, + mobile_apis::Result::INVALID_DATA, + "Binary data empty", + &response_params); + return; + } + + if (!(*message_)[strings::msg_params].keyExists(strings::sync_file_name)) { + LOG4CXX_ERROR(logger_, "No file name"); + SendResponse(false, + mobile_apis::Result::INVALID_DATA, + "No file name", + &response_params); + return; + } + + if (!(*message_)[strings::msg_params].keyExists(strings::file_type)) { + LOG4CXX_ERROR(logger_, "No file type"); + SendResponse(false, + mobile_apis::Result::INVALID_DATA, + "No file type", + &response_params); + return; + } + sync_file_name_ = + (*message_)[strings::msg_params][strings::sync_file_name].asString(); + + if (!file_system::IsFileNameValid(sync_file_name_)) { + const std::string err_msg = "Sync file name contains forbidden symbols."; + LOG4CXX_ERROR(logger_, err_msg); + SendResponse(false, + mobile_apis::Result::INVALID_DATA, + err_msg.c_str(), + &response_params); + return; + } + + file_type_ = static_cast<mobile_apis::FileType::eType>( + (*message_)[strings::msg_params][strings::file_type].asInt()); + const std::vector<uint8_t> binary_data = + (*message_)[strings::params][strings::binary_data].asBinary(); + + // Policy table update in json format is currently to be received via PutFile + // TODO(PV): after latest discussion has to be changed + if (mobile_apis::FileType::JSON == file_type_) { + application_manager_.GetPolicyHandler().ReceiveMessageFromSDK( + sync_file_name_, binary_data); + } + + offset_ = 0; + is_persistent_file_ = false; + bool is_system_file = false; + length_ = binary_data.size(); + bool is_download_compleate = true; + bool offset_exist = + (*message_)[strings::msg_params].keyExists(strings::offset); + + if (offset_exist) { + offset_ = (*message_)[strings::msg_params][strings::offset].asInt(); + } + + if ((*message_)[strings::msg_params].keyExists(strings::persistent_file)) { + is_persistent_file_ = + (*message_)[strings::msg_params][strings::persistent_file].asBool(); + } + if ((*message_)[strings::msg_params].keyExists(strings::system_file)) { + is_system_file = + (*message_)[strings::msg_params][strings::system_file].asBool(); + } + + std::string file_path; + + if (is_system_file) { + response_params[strings::space_available] = 0; + file_path = application_manager_.get_settings().system_files_path(); + } else { + file_path = application_manager_.get_settings().app_storage_folder(); + file_path += "/" + application->folder_name(); + + uint32_t space_available = application->GetAvailableDiskSpace(); + + if (binary_data.size() > space_available) { + response_params[strings::space_available] = + static_cast<uint32_t>(space_available); + + LOG4CXX_ERROR(logger_, "Out of memory"); + SendResponse(false, + mobile_apis::Result::OUT_OF_MEMORY, + "Out of memory", + &response_params); + return; + } + } + + if (!file_system::CreateDirectoryRecursively(file_path)) { + LOG4CXX_ERROR(logger_, "Can't create folder"); + SendResponse(false, + mobile_apis::Result::GENERIC_ERROR, + "Can't create folder.", + &response_params); + return; + } + const std::string full_path = file_path + "/" + sync_file_name_; + UNUSED(full_path); + LOG4CXX_DEBUG(logger_, + "Wrtiting " << binary_data.size() << "bytes to " << full_path + << " (current size is" + << file_system::FileSize(full_path) << ")"); + + mobile_apis::Result::eType save_result = application_manager_.SaveBinary( + binary_data, file_path, sync_file_name_, offset_); + + LOG4CXX_DEBUG(logger_, + "New size of " << full_path << " is " + << file_system::FileSize(full_path) << " bytes"); + if (!is_system_file) { + response_params[strings::space_available] = + static_cast<uint32_t>(application->GetAvailableDiskSpace()); + } + + sync_file_name_ = file_path + "/" + sync_file_name_; + switch (save_result) { + case mobile_apis::Result::SUCCESS: { + LOG4CXX_INFO(logger_, "PutFile is successful"); + if (!is_system_file) { + AppFile file(sync_file_name_, + is_persistent_file_, + is_download_compleate, + file_type_); + + if (0 == offset_) { + LOG4CXX_INFO(logger_, "New file downloading"); + if (!application->AddFile(file)) { + LOG4CXX_INFO(logger_, + "Couldn't add file to application (File already Exist" + << " in application and was rewritten on FS)"); + /* It can be first part of new big file, so we need to update + information about it's downloading status and persistence */ + if (!application->UpdateFile(file)) { + LOG4CXX_ERROR(logger_, "Couldn't update file"); + /* If it is impossible to update file, application doesn't + know about existing this file */ + SendResponse(false, + mobile_apis::Result::INVALID_DATA, + "Couldn't update file", + &response_params); + return; + } + } else { + /* if file added - increment it's count + ( may be application->AddFile have to incapsulate it? ) + Any way now this method evals not only in "none"*/ + application->increment_put_file_in_none_count(); + } + } + } + + SendResponse(true, save_result, "File was downloaded", &response_params); + if (is_system_file) { + SendOnPutFileNotification(); + } + break; + } + default: + LOG4CXX_WARN(logger_, + "PutFile is unsuccessful. Result = " << save_result); + SendResponse(false, save_result, "Can't save file", &response_params); + break; + } +} + +void PutFileRequest::SendOnPutFileNotification() { + LOG4CXX_INFO(logger_, "SendOnPutFileNotification"); + smart_objects::SmartObjectSPtr notification = + new smart_objects::SmartObject(smart_objects::SmartType_Map); + + smart_objects::SmartObject& message = *notification; + message[strings::params][strings::function_id] = + hmi_apis::FunctionID::BasicCommunication_OnPutFile; + + message[strings::params][strings::message_type] = MessageType::kNotification; + message[strings::msg_params][strings::app_id] = connection_key(); + message[strings::msg_params][strings::sync_file_name] = sync_file_name_; + message[strings::msg_params][strings::offset] = offset_; + if (0 == offset_) { + message[strings::msg_params][strings::file_size] = + (*message_)[strings::msg_params][strings::length]; + } + message[strings::msg_params][strings::length] = length_; + message[strings::msg_params][strings::persistent_file] = is_persistent_file_; + message[strings::msg_params][strings::file_type] = file_type_; + application_manager_.ManageHMICommand(notification); +} + +} // namespace commands + +} // namespace application_manager diff --git a/pool/shard007/C++/0092694_D.cpp b/pool/shard007/C++/0092694_D.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5b302c3e44ddfd33d1c2e45d83d51619d642531e --- /dev/null +++ b/pool/shard007/C++/0092694_D.cpp @@ -0,0 +1,109 @@ +#include <iostream> +#include <iomanip> // << fixed << setprecision(xxx) +#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; +#include <vector> +#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) +#include <complex> +#include <tuple> // get<n>(xxx) +#include <queue> +#include <stack> +#include <map> // if (M.find(key) != M.end()) { } +#include <set> // S.insert(M); +// if (S.find(key) != S.end()) { } +// for (auto it=S.begin(); it != S.end(); it++) { } +// auto it = S.lower_bound(M); +#include <random> // random_device rd; mt19937 mt(rd()); +#include <cctype> +#include <cassert> +#include <cmath> +#include <cstdio> +#include <cstdlib> // atoi(xxx) +using namespace std; + +#define DEBUG 0 // change 0 -> 1 if we need debug. +// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end + +typedef long long ll; + +// const int dx[4] = {1, 0, -1, 0}; +// const int dy[4] = {0, 1, 0, -1}; + +// const int C = 1e6+10; +// const ll M = 1000000007; + +vector<int> V[100010]; +bool visited[100010]; +int parents[100010]; + +typedef tuple<int, int, int> state; // now, d, from + +int main () { + int N; + cin >> N; + for (auto i = 0; i < N-1; ++i) { + int a, b; + cin >> a >> b; + a--; + b--; + V[a].push_back(b); + V[b].push_back(a); + } + stack<state> S; + S.push(state(0, 0, -1)); + int cut; + int D; + fill(visited, visited+N, false); + while (!S.empty()) { + int now = get<0>(S.top()); + int d = get<1>(S.top()); + int from = get<2>(S.top()); + S.pop(); + if (!visited[now]) { + // cerr << "now = " << now << ", d = " << d << endl; + visited[now] = true; + parents[now] = from; + if (now == N-1) { + D = d; + break; + } + for (auto x : V[now]) { + if (!visited[x]) { + S.push(state(x, d+1, now)); + } + } + } + } + stack<state> SS; + SS.push(state(N-1, 0, parents[N-1])); + int cnt = 0; + cut = N-1; + for (auto i = 0; i < (D-1)/2; ++i) { + cut = parents[cut]; + } + fill(visited, visited+N, false); + while (!SS.empty()) { + int now = get<0>(SS.top()); + int d = get<1>(SS.top()); + SS.pop(); + if (!visited[now]) { + visited[now] = true; + cnt++; + for (auto x : V[now]) { + if (!visited[x] && x != parents[cut]) { + SS.push(state(x, d+1, now)); + } + } + } + } + int su = cnt - 1; + int fa = N - 2 - su; + cerr << "D = " << D << endl; + cerr << "cut = " << cut << endl; + cerr << "cnt = " << cnt << endl; + cerr << "su = " << su << ", fa = " << fa << endl; + if (fa > su) { + cout << "Fennec" << endl; + } else { + cout << "Snuke" << endl; + } +} diff --git a/pool/shard007/C++/0092695_spring.cc b/pool/shard007/C++/0092695_spring.cc new file mode 100644 index 0000000000000000000000000000000000000000..312b2ed00f49644598966832b50d1598396eae3b --- /dev/null +++ b/pool/shard007/C++/0092695_spring.cc @@ -0,0 +1,216 @@ +/* + This file is part of LilyPond, the GNU music typesetter. + + Copyright (C) 2007--2012 Joe Neeman <joeneeman@gmail.com> + + LilyPond is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + LilyPond is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with LilyPond. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "spring.hh" + +Spring::Spring () +{ + distance_ = 1.0; + min_distance_ = 1.0; + inverse_stretch_strength_ = 1.0; + inverse_compress_strength_ = 1.0; + + update_blocking_force (); +} + +Spring::Spring (Real dist, Real min_dist) +{ + distance_ = 1.0; + min_distance_ = 1.0; + inverse_stretch_strength_ = 1.0; + inverse_compress_strength_ = 1.0; + + set_distance (dist); + set_min_distance (min_dist); + set_default_strength (); + update_blocking_force (); +} + +void +Spring::update_blocking_force () +{ + // blocking_force_ is the value of force + // below which length(force) is constant, and + // above which length(force) varies according to inverse_*_strength. + // Simple_spacer::compress_line() depends on the condition above. + // We assume inverse_*_strength are non-negative. + if (min_distance_ > distance_) + if (inverse_stretch_strength_ > 0.0) + blocking_force_ = (min_distance_ - distance_) / inverse_stretch_strength_; + else + // Conceptually, this should be +inf, but 0.0 meets the requirements + // of Simple_spacer and creates fewer cases of 0.0*inf to handle. + blocking_force_ = 0.0; + else if (inverse_compress_strength_ > 0.0) + blocking_force_ = (min_distance_ - distance_) / inverse_compress_strength_; + else + blocking_force_ = 0.0; +} + +/* scale a spring, but in a way that doesn't violate min_distance */ +void +Spring::operator *= (Real r) +{ + distance_ = max (min_distance_, distance_ * r); + inverse_compress_strength_ = max (0.0, distance_ - min_distance_); + inverse_stretch_strength_ *= 0.8; + update_blocking_force (); +} + +bool +Spring::operator > (Spring const &other) const +{ + return blocking_force_ > other.blocking_force_; +} + +/* merge springs, basically by averaging them, but leave a little headroom + above the largest minimum distance so that things don't get too cramped */ +Spring +merge_springs (vector<Spring> const &springs) +{ + Real avg_distance = 0; + Real min_distance = 0; + Real avg_stretch = 0; + Real avg_compress = 0; + + for (vsize i = 0; i < springs.size (); i++) + { + avg_distance += springs[i].distance (); + avg_stretch += springs[i].inverse_stretch_strength (); + avg_compress += 1 / springs[i].inverse_compress_strength (); + min_distance = max (springs[i].min_distance (), min_distance); + } + + avg_stretch /= Real (springs.size ()); + avg_compress /= Real (springs.size ()); + avg_distance /= Real (springs.size ()); + avg_distance = max (min_distance + 0.3, avg_distance); + + Spring ret = Spring (avg_distance, min_distance); + ret.set_inverse_stretch_strength (avg_stretch); + ret.set_inverse_compress_strength (1 / avg_compress); + + return ret; +} + +void +Spring::set_distance (Real d) +{ + if (d < 0 || isinf (d) || isnan (d)) + programming_error ("insane spring distance requested, ignoring it"); + else + { + distance_ = d; + update_blocking_force (); + } +} + +void +Spring::set_min_distance (Real d) +{ + if (d < 0 || isinf (d) || isnan (d)) + programming_error ("insane spring min_distance requested, ignoring it"); + else + { + min_distance_ = d; + update_blocking_force (); + } +} + +void +Spring::ensure_min_distance (Real d) +{ + set_min_distance (max (d, min_distance_)); +} + +void +Spring::set_inverse_stretch_strength (Real f) +{ + if (isinf (f) || isnan (f) || f < 0) + programming_error ("insane spring constant"); + else + inverse_stretch_strength_ = f; + + update_blocking_force (); +} + +void +Spring::set_inverse_compress_strength (Real f) +{ + if (isinf (f) || isnan (f) || f < 0) + programming_error ("insane spring constant"); + else + inverse_compress_strength_ = f; + + update_blocking_force (); +} + +void +Spring::set_blocking_force (Real f) +{ + if (isinf (f) || isnan (f)) + { + programming_error ("insane blocking force"); + return; + } + + blocking_force_ = -infinity_f; + min_distance_ = length (f); + distance_ = max (distance_, min_distance_); + update_blocking_force (); +} + +void +Spring::set_default_strength () +{ + set_default_stretch_strength (); + set_default_compress_strength (); +} + +void +Spring::set_default_compress_strength () +{ + inverse_compress_strength_ = (distance_ >= min_distance_) ? distance_ - min_distance_ : 0; + update_blocking_force (); +} + +void +Spring::set_default_stretch_strength () +{ + inverse_stretch_strength_ = distance_; +} + +Real +Spring::length (Real f) const +{ + Real force = max (f, blocking_force_); + Real inv_k = force < 0.0 ? inverse_compress_strength_ : inverse_stretch_strength_; + + if (isinf (force)) + { + programming_error ("cruelty to springs"); + force = 0.0; + } + + // There is a corner case here: if min_distance_ is larger than + // distance_ but the spring is fixed, then inv_k will be zero + // and we need to make sure that we return min_distance_. + return max (min_distance_, distance_ + force * inv_k); +} + diff --git a/pool/shard007/C++/0092698_Terminal.cpp b/pool/shard007/C++/0092698_Terminal.cpp new file mode 100644 index 0000000000000000000000000000000000000000..63bc25055b1cefb058beb03bdc5ad493961dd523 --- /dev/null +++ b/pool/shard007/C++/0092698_Terminal.cpp @@ -0,0 +1,25 @@ +#include "Terminal.hpp" + +#include <curses.h> + +#include <memory> + +namespace MORL { + void SetColor(TerminalColor color) { + attron(COLOR_PAIR((int)color)); + } + + std::string ReadString() { + nodelay(stdscr, false); + echo(); + + std::unique_ptr<char[]> buf(new char[ReadStringBufferSize]); + getnstr(buf.get(), ReadStringBufferSize - 1); + buf[ReadStringBufferSize - 1] = 0; + std::string str{buf.get()}; + + noecho(); + nodelay(stdscr, true); + return str; + } +} diff --git a/pool/shard007/C++/0092706_frame_path.cc b/pool/shard007/C++/0092706_frame_path.cc new file mode 100644 index 0000000000000000000000000000000000000000..2335d0bc2443507aba3bbfb73d4fc546e4e9b604 --- /dev/null +++ b/pool/shard007/C++/0092706_frame_path.cc @@ -0,0 +1,75 @@ +// Copyright (c) 2011 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 "chrome/test/webdriver/frame_path.h" + +#include "base/string_split.h" + +namespace webdriver { + +FramePath::FramePath() : path_("") {} + +FramePath::FramePath(const FramePath& other) : path_(other.path_) {} + +FramePath::FramePath(const std::string& path) : path_(path) {} + +FramePath::~FramePath() {} + +FramePath& FramePath::operator=(const FramePath& other) { + path_ = other.path_; + return *this; +} + +bool FramePath::operator==(const FramePath& other) const { + return path_ == other.path_; +} + +FramePath FramePath::Append(const FramePath& path) const { + return Append(path.path_); +} + +FramePath FramePath::Append(const std::string& path) const { + // An empty path refers to the root frame, so just return it. + if (path.empty()) + return *this; + + // Don't append a separator if the current path is empty. + std::string new_path = path_; + if (path_.length()) + new_path += "\n"; + return FramePath(new_path + path); +} + +FramePath FramePath::Parent() const { + size_t i = path_.find_last_of("\n"); + if (i != std::string::npos) + return FramePath(path_.substr(0, i)); + return FramePath(); +} + +FramePath FramePath::BaseName() const { + size_t i = path_.find_last_of("\n"); + if (i != std::string::npos) + return FramePath(path_.substr(i + 1)); + return *this; +} + +void FramePath::GetComponents(std::vector<std::string>* components) const { + if (IsSubframe()) + base::SplitString(path_, '\n', components); +} + +bool FramePath::IsRootFrame() const { + return path_.empty(); +} + +bool FramePath::IsSubframe() const { + return path_.length(); +} + +const std::string& FramePath::value() const { + return path_; +} + +} // namespace webdriver diff --git a/pool/shard007/C++/0092708_MergeMouse.cpp b/pool/shard007/C++/0092708_MergeMouse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb8355b24b9698af5fa295863a1d25342118701c --- /dev/null +++ b/pool/shard007/C++/0092708_MergeMouse.cpp @@ -0,0 +1,111 @@ +/* +Copyright_License { + + XCSoar Glide Computer - http://www.xcsoar.org/ + Copyright (C) 2000-2013 The XCSoar Project + A detailed list of copyright holders can be found in the file "AUTHORS". + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +} +*/ + +#include "MergeMouse.hpp" +#include "Event/Shared/Event.hpp" +#include "IO/Async/IOLoop.hpp" + +void +MergeMouse::SetScreenSize(unsigned width, unsigned height) +{ + if (width != rotate.GetWidth()) + x = width / 2; + + if (height != rotate.GetHeight()) + y = height / 2; + + rotate.SetSize(width, height); +} + +void +MergeMouse::SetDown(bool new_down) +{ + if (new_down != down) { + down = new_down; + if (down) + pressed = true; + else + released = true; + } +} + +void +MergeMouse::MoveAbsolute(int new_x, int new_y) +{ + rotate.DoAbsolute(new_x, new_y); + + const unsigned screen_width = rotate.GetWidth(); + if (screen_width > 0) { + if (new_x < 0) + new_x = 0; + else if (unsigned(new_x) > screen_width) + new_x = screen_width - 1; + + if (unsigned(new_x) != x) { + x = new_x; + moved = true; + } + } + + const unsigned screen_height = rotate.GetHeight(); + if (screen_height > 0) { + if (new_y < 0) + new_y = 0; + else if (unsigned(new_y) > screen_height) + new_y = screen_height - 1; + + if (unsigned(new_y) != y) { + y = new_y; + moved = true; + } + } +} + +void +MergeMouse::MoveRelative(int dx, int dy) +{ + rotate.DoRelative(dx, dy); + + MoveAbsolute(x + dx, y + dy); +} + +Event +MergeMouse::Generate() +{ + if (moved) { + moved = false; + return Event(Event::MOUSE_MOTION, x, y); + } + + if (pressed) { + pressed = false; + return Event(Event::MOUSE_DOWN, x, y); + } + + if (released) { + released = false; + return Event(Event::MOUSE_UP, x, y); + } + + return Event(Event::Type::NOP); +} diff --git a/pool/shard007/C++/0092709_wall-clock-synchronizer.cc b/pool/shard007/C++/0092709_wall-clock-synchronizer.cc new file mode 100644 index 0000000000000000000000000000000000000000..ba469b45c25e030717f6744044535ee302b55a78 --- /dev/null +++ b/pool/shard007/C++/0092709_wall-clock-synchronizer.cc @@ -0,0 +1,422 @@ +/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2008 University of Washington + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation; + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + + +#include <ctime> // clock_t +#include <sys/time.h> // gettimeofday + // clock_getres: glibc < 2.17, link with librt + +#include "log.h" +#include "system-condition.h" + +#include "wall-clock-synchronizer.h" + +/** + * \file + * \ingroup realtime + * ns3::WallClockSynchronizer implementation. + */ + +namespace ns3 { + +NS_LOG_COMPONENT_DEFINE ("WallClockSynchronizer"); + +NS_OBJECT_ENSURE_REGISTERED (WallClockSynchronizer); + +TypeId +WallClockSynchronizer::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::WallClockSynchronizer") + .SetParent<Synchronizer> () + ; + return tid; +} + +WallClockSynchronizer::WallClockSynchronizer () +{ + NS_LOG_FUNCTION (this); +// +// In Linux, the basic timekeeping unit is derived from a variable called HZ +// HZ is the frequency in hertz of the system timer. The system timer fires +// every 1/HZ seconds and a counter, called the jiffies counter is incremented +// at each tick. The time between ticks is called a jiffy (American slang for +// a short period of time). The ticking of the jiffies counter is how the +// the kernel tells time. +// +// Now, the shortest time the kernel can sleep is one jiffy since a timer +// has to be set to expire and trigger the process to be made ready. The +// Posix clock CLOCK_REALTIME is defined as a 1/HZ clock, so by doing a +// clock_getres () on the realtime clock we can infer the scheduler quantum +// and the minimimum sleep time for the system. This is most certainly NOT +// going to be one nanosecond even though clock_nanosleep () pretends it is. +// +// The reason this number is important is that we are going to schedule lots +// of waits for less time than a jiffy. The clock_nanosleep function is +// going to guarantee that it will sleep for AT LEAST the time specified. +// The least time that it will sleep is a jiffy. +// +// In order to deal with this, we are going to do a spin-wait if the simulator +// requires a delay less than a jiffy. This is on the order of one millisecond +// (999848 ns) on the ns-regression machine. +// +// If the underlying OS does not support posix clocks, we'll just assume a +// one millisecond quantum and deal with this as best we can + +#ifdef CLOCK_REALTIME + struct timespec ts; + clock_getres (CLOCK_REALTIME, &ts); + m_jiffy = ts.tv_sec * NS_PER_SEC + ts.tv_nsec; + NS_LOG_INFO ("Jiffy is " << m_jiffy << " ns"); +#else + m_jiffy = 1000000; +#endif +} + +WallClockSynchronizer::~WallClockSynchronizer () +{ + NS_LOG_FUNCTION (this); +} + +bool +WallClockSynchronizer::DoRealtime (void) +{ + NS_LOG_FUNCTION (this); + return true; +} + +uint64_t +WallClockSynchronizer::DoGetCurrentRealtime (void) +{ + NS_LOG_FUNCTION (this); + return GetNormalizedRealtime (); +} + +void +WallClockSynchronizer::DoSetOrigin (uint64_t ns) +{ + NS_LOG_FUNCTION (this << ns); +// +// In order to make sure we're really locking the simulation time to some +// wall-clock time, we need to be able to compare that simulation time to +// that wall-clock time. The wall clock will have been running for some +// long time and will probably have a huge count of nanoseconds in it. We +// save the real time away so we can subtract it from "now" later and get +// a count of nanoseconds in real time since the simulation started. +// + m_realtimeOriginNano = GetRealtime (); + NS_LOG_INFO ("origin = " << m_realtimeOriginNano); +} + +int64_t +WallClockSynchronizer::DoGetDrift (uint64_t ns) +{ + NS_LOG_FUNCTION (this << ns); +// +// In order to make sure we're really locking the simulation time to some +// wall-clock time, we need to be able to compare that simulation time to +// that wall-clock time. In DoSetOrigin we saved the real time at the start +// of the simulation away. This is the place where we subtract it from "now" +// to a count of nanoseconds in real time since the simulation started. We +// then subtract the current real time in normalized nanoseconds we just got +// from the normalized simulation time in nanoseconds that is passed in as +// the parameter ns. We return an integer difference, but in reality all of +// the mechanisms that cause wall-clock to simuator time drift cause events +// to be late. That means that the wall-clock will be higher than the +// simulation time and drift will be positive. I would be astonished to +// see a negative drift, but the possibility is admitted for other +// implementations; and we'll use the ability to report an early result in +// DoSynchronize below. +// + uint64_t nsNow = GetNormalizedRealtime (); + + if (nsNow > ns) + { +// +// Real time (nsNow) is larger/later than the simulator time (ns). We are +// behind real time and the difference (drift) is positive. +// + return (int64_t)(nsNow - ns); + } + else + { +// +// Real time (nsNow) is smaller/earlier than the simulator time (ns). We are +// ahead of real time and the difference (drift) is negative. +// + return -(int64_t)(ns - nsNow); + } +} + +bool +WallClockSynchronizer::DoSynchronize (uint64_t nsCurrent, uint64_t nsDelay) +{ + NS_LOG_FUNCTION (this << nsCurrent << nsDelay); +// +// This is the belly of the beast. We have received two parameters from the +// simulator proper -- a current simulation time (nsCurrent) and a simulation +// time to delay which identifies the time the next event is supposed to fire. +// +// The first thing we need to do is to (try and) correct for any realtime +// drift that has happened in the system. In this implementation, we realize +// that all mechanisms for drift will cause the drift to be such that the +// realtime is greater than the simulation time. This typically happens when +// our process is put to sleep for a given time, but actually sleeps for +// longer. So, what we want to do is to "catch up" to realtime and delay for +// less time than we are actually asked to delay. DriftCorrect will return a +// number from 0 to nsDelay corresponding to the amount of catching-up we +// need to do. If we are more than nsDelay behind, we do not wait at all. +// +// Note that it will be impossible to catch up if the amount of drift is +// cumulatively greater than the amount of delay between events. The method +// GetDrift () is available to clients of the syncrhonizer to keep track of +// the cumulative drift. The client can assert if the drift gets out of +// hand, print warning messages, or just ignore the situation and hope it will +// go away. +// + uint64_t ns = DriftCorrect (nsCurrent, nsDelay); + NS_LOG_INFO ("Synchronize ns = " << ns); +// +// Once we've decided on how long we need to delay, we need to split this +// time into sleep waits and busy waits. The reason for this is described +// in the comments for the constructor where jiffies and jiffy resolution is +// explained. +// +// Here, I'll just say that we need that the jiffy is the minimum resolution +// of the system clock. It can only sleep in blocks of time equal to a jiffy. +// If we want to be more accurate than a jiffy (we do) then we need to sleep +// for some number of jiffies and then busy wait for any leftover time. +// + uint64_t numberJiffies = ns / m_jiffy; + NS_LOG_INFO ("Synchronize numberJiffies = " << numberJiffies); +// +// This is where the real world interjects its very ugly head. The code +// immediately below reflects the fact that a sleep is actually quite probably +// going to end up sleeping for some number of jiffies longer than you wanted. +// This is because your system is going to be off doing other unimportant +// stuff during that extra time like running file systems and networks. What +// we want to do is to ask the system to sleep enough less than the requested +// delay so that it comes back early most of the time (coming back early is +// fine, coming back late is bad). If we can convince the system to come back +// early (most of the time), then we can busy-wait until the requested +// completion time actually comes around (most of the time). +// +// The tradeoff here is, of course, that the less time we spend sleeping, the +// more accurately we will sync up; but the more CPU time we will spend busy +// waiting (doing nothing). +// +// I'm not really sure about this number -- a boss of mine once said, "pick +// a number and it'll be wrong." But this works for now. +// +// \todo Hardcoded tunable parameter below. +// + if (numberJiffies > 3) + { + NS_LOG_INFO ("SleepWait for " << numberJiffies * m_jiffy << " ns"); + NS_LOG_INFO ("SleepWait until " << nsCurrent + numberJiffies * m_jiffy + << " ns"); +// +// SleepWait is interruptible. If it returns true it meant that the sleep +// went until the end. If it returns false, it means that the sleep was +// interrupted by a Signal. In this case, we need to return and let the +// simulator re-evaluate what to do. +// + if (SleepWait ((numberJiffies - 3) * m_jiffy) == false) + { + NS_LOG_INFO ("SleepWait interrupted"); + return false; + } + } + NS_LOG_INFO ("Done with SleepWait"); +// +// We asked the system to sleep for some number of jiffies, but that doesn't +// mean we actually did. Let's re-evaluate what we need to do here. Maybe +// we're already late. Probably the "real" delay time left has little to do +// with what we would calculate it to be naively. +// +// We are now at some Realtime. The important question now is not, "what +// would we calculate in a mathematicians paradise," it is, "how many +// nanoseconds do we need to busy-wait until we get to the Realtime that +// corresponds to nsCurrent + nsDelay (in simulation time). We have a handy +// function to do just that -- we ask for the time the realtime clock has +// drifted away from the simulation clock. That's our answer. If the drift +// is negative, we're early and we need to busy wait for that number of +// nanoseconds. The place were we want to be is described by the parameters +// we were passed by the simulator. +// + int64_t nsDrift = DoGetDrift (nsCurrent + nsDelay); +// +// If the drift is positive, we are already late and we need to just bail out +// of here as fast as we can. Return true to indicate that the requested time +// has, in fact, passed. +// + if (nsDrift >= 0) + { + NS_LOG_INFO ("Back from SleepWait: IML8 " << nsDrift); + return true; + } +// +// There are some number of nanoseconds left over and we need to wait until +// the time defined by nsDrift. We'll do a SpinWait since the usual case +// will be that we are doing this Spinwait after we've gotten a rough delay +// using the SleepWait above. If SpinWait completes to the end, it will +// return true; if it is interrupted by a signal it will return false. +// + NS_LOG_INFO ("SpinWait until " << nsCurrent + nsDelay); + return SpinWait (nsCurrent + nsDelay); +} + +void +WallClockSynchronizer::DoSignal (void) +{ + NS_LOG_FUNCTION (this); + + m_condition.SetCondition (true); + m_condition.Signal (); +} + +void +WallClockSynchronizer::DoSetCondition (bool cond) +{ + NS_LOG_FUNCTION (this << cond); + m_condition.SetCondition (cond); +} + +void +WallClockSynchronizer::DoEventStart (void) +{ + NS_LOG_FUNCTION (this); + m_nsEventStart = GetNormalizedRealtime (); +} + +uint64_t +WallClockSynchronizer::DoEventEnd (void) +{ + NS_LOG_FUNCTION (this); + return GetNormalizedRealtime () - m_nsEventStart; +} + +bool +WallClockSynchronizer::SpinWait (uint64_t ns) +{ + NS_LOG_FUNCTION (this << ns); +// We just sit here and spin, wasting CPU cycles until we get to the right +// time or are told to leave. + for (;;) + { + if (GetNormalizedRealtime () >= ns) + { + return true; + } + if (m_condition.GetCondition ()) + { + return false; + } + } +// Quiet compiler + return true; +} + +bool +WallClockSynchronizer::SleepWait (uint64_t ns) +{ + NS_LOG_FUNCTION (this << ns); + return m_condition.TimedWait (ns); +} + +uint64_t +WallClockSynchronizer::DriftCorrect (uint64_t nsNow, uint64_t nsDelay) +{ + NS_LOG_FUNCTION (this << nsNow << nsDelay); + int64_t drift = DoGetDrift (nsNow); +// +// If we're running late, drift will be positive and we need to correct by +// delaying for less time. If we're early for some bizarre reason, we don't +// do anything since we'll almost instantly self-correct. +// + if (drift < 0) + { + return nsDelay; + } +// +// If we've drifted out of sync by less than the requested delay, then just +// subtract the drift from the delay and fix up the drift in one go. If we +// have more drift than delay, then we just play catch up as fast as possible +// by not delaying at all. +// + uint64_t correction = (uint64_t)drift; + if (correction <= nsDelay) + { + return nsDelay - correction; + } + else + { + return 0; + } +} + +uint64_t +WallClockSynchronizer::GetRealtime (void) +{ + NS_LOG_FUNCTION (this); + struct timeval tvNow; + gettimeofday (&tvNow, NULL); + return TimevalToNs (&tvNow); +} + +uint64_t +WallClockSynchronizer::GetNormalizedRealtime (void) +{ + NS_LOG_FUNCTION (this); + return GetRealtime () - m_realtimeOriginNano; +} + +void +WallClockSynchronizer::NsToTimeval (int64_t ns, struct timeval *tv) +{ + NS_LOG_FUNCTION (this << ns << tv); + NS_ASSERT ((ns % US_PER_NS) == 0); + tv->tv_sec = ns / NS_PER_SEC; + tv->tv_usec = (ns % NS_PER_SEC) / US_PER_NS; +} + +uint64_t +WallClockSynchronizer::TimevalToNs (struct timeval *tv) +{ + NS_LOG_FUNCTION (this << tv); + uint64_t nsResult = tv->tv_sec * NS_PER_SEC + tv->tv_usec * US_PER_NS; + NS_ASSERT ((nsResult % US_PER_NS) == 0); + return nsResult; +} + +void +WallClockSynchronizer::TimevalAdd ( + struct timeval *tv1, + struct timeval *tv2, + struct timeval *result) +{ + NS_LOG_FUNCTION (this << tv1 << tv2 << result); + result->tv_sec = tv1->tv_sec + tv2->tv_sec; + result->tv_usec = tv1->tv_usec + tv2->tv_usec; + if (result->tv_usec > (int64_t)US_PER_SEC) + { + ++result->tv_sec; + result->tv_usec %= US_PER_SEC; + } +} + +} // namespace ns3 diff --git a/pool/shard007/C++/0092717_trimline.cc b/pool/shard007/C++/0092717_trimline.cc new file mode 100644 index 0000000000000000000000000000000000000000..26948b2bccac4bfab7230afbe2893c98e777705a --- /dev/null +++ b/pool/shard007/C++/0092717_trimline.cc @@ -0,0 +1,223 @@ +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +*/ + +/* + * trimline.c++ + * + */ + +//#include "glimports.h" +//#include "myassert.h" +//#include "mystdio.h" +#include "trimline.h" +#include "backend.h" + +Trimline::Trimline() +{ + size = 0; pts = 0; numverts = 0; + tinterp = &t; binterp = &b; +} + +Trimline::~Trimline() +{ + if( pts ) delete[] pts; +} + +void +Trimline::init( TrimVertex *v ) +{ + reset(); + grow(1); + append(v); +} + +inline void +Trimline::grow( long npts ) +{ + if( size < npts ) { + size = 2 * npts; + if( pts ) delete[] pts; + pts = new TrimVertex_p[size]; + } +} + +inline void +Trimline::append( TrimVertex *v ) +{ + assert( numverts != size ); + pts[numverts++] = v; +} + +void +Trimline::init( long npts, Arc_ptr jarc, long last ) +{ + jarcl.init( jarc, 0, last ); + grow( npts + 2 ); +} + +inline void +Trimline::swap() +{ + TrimVertex *tmp=tinterp; + tinterp=binterp; + binterp=tmp; +} + +void +Trimline::getNextPt() +{ + *binterp = *jarcl.getnextpt(); +} + +void +Trimline::getPrevPt() +{ + *binterp = *jarcl.getprevpt(); +} + +/*---------------------------------------------------------------------- + * getNextPts - make arrays of pointers to trim points on left and right + * hulls of trim strip. + *---------------------------------------------------------------------- + */ +void +Trimline::getNextPts( REAL vval, Backend& backend ) +{ + reset(); swap(); append( tinterp ); + assert( tinterp->param[1] >= vval ); + + register TrimVertex *p; + for( p=jarcl.getnextpt() ; p->param[1] >= vval; p=jarcl.getnextpt() ) { + append( p ); + } + + /* compute and copy pointer to final point on left hull */ + if( interpvert( last(), p, binterp, vval ) ) { + binterp->nuid = p->nuid; + backend.triangle( p, binterp, last() ); + append( binterp ); + } + jarcl.reverse(); + (void) jarcl.getprevpt(); /* reset jarcl to proper position */ + jarcl.reverse(); +} + +void +Trimline::getPrevPts( REAL vval, Backend& backend ) +{ + reset(); swap(); append( tinterp ); + assert( tinterp->param[1] >= vval ); + + register TrimVertex *q; + for( q=jarcl.getprevpt(); q->param[1] >= vval; q=jarcl.getprevpt() ) { + append( q ); + } + + /* compute and copy pointer to final point on right hull */ + if( interpvert( q, last(), binterp, vval ) ) { + binterp->nuid = q->nuid; + backend.triangle( last(), binterp, q ); + append( binterp ); + } + jarcl.reverse(); + (void) jarcl.getnextpt(); /* reset jarcl to proper position */ + jarcl.reverse(); +} + +void +Trimline::getNextPts( Arc_ptr botarc ) +{ + reset(); swap(); append( tinterp ); + +#ifndef NDEBUG + PwlArc *lastpwl = botarc->prev->pwlArc; + TrimVertex *lastpt1 = &lastpwl->pts[lastpwl->npts-1]; +#endif + TrimVertex *lastpt2 = botarc->pwlArc->pts; + register TrimVertex *p = jarcl.getnextpt(); + for( append( p ); p != lastpt2; append( p ) ) { + assert( p != lastpt1 ); + p = jarcl.getnextpt(); + } +} + +void +Trimline::getPrevPts( Arc_ptr botarc ) +{ + reset(); swap(); append( tinterp ); + + PwlArc *lastpwl = botarc->prev->pwlArc; + TrimVertex *lastpt1 = &lastpwl->pts[lastpwl->npts-1]; +#ifndef NDEBUG + TrimVertex *lastpt2 = botarc->pwlArc->pts; +#endif + + register TrimVertex *q = jarcl.getprevpt(); + for( append( q ); q != lastpt1; append( q ) ) { + assert( q != lastpt2 ); + q = jarcl.getprevpt(); + } +} + + +long +Trimline::interpvert( TrimVertex *a, TrimVertex *b, TrimVertex *c, REAL vval ) +{ + REAL denom = a->param[1] - b->param[1]; + + if(denom != 0) { + if( vval == a->param[1] ) { + c->param[0] = a->param[0]; + c->param[1] = a->param[1]; + c->nuid = a->nuid; + return 0; + } else if( vval == b->param[1] ) { + c->param[0] = b->param[0]; + c->param[1] = b->param[1]; + c->nuid = b->nuid; + return 0; + } else { + REAL r = (a->param[1] - vval)/denom; + c->param[0] = a->param[0] - r * (a->param[0] - b->param[0]); + c->param[1] = vval; + return 1; + } + } else { + c->param[0] = a->param[0]; + c->param[1] = a->param[1]; + c->nuid = a->nuid; + return 0; + } +} + diff --git a/pool/shard007/C++/0092728_symboltable.cpp b/pool/shard007/C++/0092728_symboltable.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fc43f7dc8f6fc68ee8574bdbe8ebaaf97ed39f1c --- /dev/null +++ b/pool/shard007/C++/0092728_symboltable.cpp @@ -0,0 +1,223 @@ +#include "vm/symboltable.hpp" +#include "vm/exception.hpp" +#include "configuration.hpp" + +#include "builtin/array.hpp" +#include "builtin/exception.hpp" +#include "builtin/string.hpp" +#include "builtin/symbol.hpp" + +#include <iostream> +#include <iomanip> + +namespace rubinius { + + SymbolTable::Kind SymbolTable::detect_kind(const char* str, int size) { + const char one = str[0]; + + // A constant begins with an uppercase letter. + if(one >= 'A' && one <= 'Z') { + // Make sure that the rest of it is only alphanumerics + for(int i = 1; i < size; i++) { + if((isalnum(str[i]) || str[i] == '_') == false) + return SymbolTable::Normal; + } + return SymbolTable::Constant; + } + + if(one == '@') { + // A class variable begins with @@ + if(size > 1 && str[1] == '@') { + return SymbolTable::CVar; + } + + // An instance variable begins with @ + return SymbolTable::IVar; + } + + // A system variable begins with __ + if(size > 2 && one == '_' && str[1] == '_') { + return SymbolTable::System; + } + + // Everything else is normal + return SymbolTable::Normal; + } + + SymbolTable::Kind SymbolTable::kind(STATE, const Symbol* sym) { + return kinds[sym->index()]; + } + + size_t SymbolTable::add(std::string str) { + bytes_used_ += (str.size() + sizeof(str)); + + strings.push_back(str); + kinds.push_back(detect_kind(str.data(), str.size())); + return strings.size() - 1; + } + + Symbol* SymbolTable::lookup(STATE, const char* str, size_t length) { + if(length == 0 && LANGUAGE_18_ENABLED(state)) { + Exception::argument_error(state, "Cannot create a symbol from an empty string"); + return NULL; + } + + return lookup(str, length, state->hash_seed()); + } + + struct SpecialOperator { + const char* name; + const char* symbol; + }; + + // These are a set of special operators that MRI + // changes the symbol value of. + static SpecialOperator SpecialOperators[] = { + {"+(binary)", "+"}, + {"-(binary)", "-"}, + {"+(unary)", "+@"}, + {"-(unary)", "-@"}, + {"!(unary)", "!"}, + {"~(unary)", "~"}, + {"!@", "!"}, + {"~@", "~"} + }; + + const static int cNumSpecialOperators = 8; + + static const char* find_special(const char* check, size_t length) { + for(int i = 0; i < cNumSpecialOperators; i++) { + SpecialOperator* op = &SpecialOperators[i]; + if(*op->name == *check && strncmp(op->name, check, length) == 0) { + return op->symbol; + } + } + + return 0; + } + + Symbol* SymbolTable::lookup(SharedState* shared, std::string str) { + return lookup(str.data(), str.size(), shared->hash_seed); + } + + Symbol* SymbolTable::lookup(STATE, std::string str) { + return lookup(str.data(), str.size(), state->hash_seed()); + } + + Symbol* SymbolTable::lookup(const char* str, size_t length, uint32_t seed) { + size_t sym; + + if(const char* op = find_special(str, length)) { + str = op; + length = strlen(str); + } + + hashval hash = String::hash_str((unsigned char*)str, length, seed); + + // Symbols can be looked up by multiple threads at the same time. + // This is fast operation, so we protect this with a spinlock. + { + thread::SpinLock::LockGuard guard(lock_); + SymbolMap::iterator entry = symbols.find(hash); + if(entry == symbols.end()) { + sym = add(std::string(str, length)); + SymbolIds v(1, sym); + symbols[hash] = v; + } else { + SymbolIds& v = entry->second; + for(SymbolIds::iterator i = v.begin(); i != v.end(); ++i) { + std::string& s = strings[*i]; + + if(!strncmp(s.data(), str, length)) return Symbol::from_index(*i); + } + sym = add(std::string(str, length)); + v.push_back(sym); + } + } + + return Symbol::from_index(sym); + } + + Symbol* SymbolTable::lookup(STATE, String* str) { + if(str->nil_p()) { + Exception::argument_error(state, "Cannot look up Symbol from nil"); + return NULL; + } + + // Since we also explicitly use the size, we can safely + // use byte_address() here. + const char* bytes = (const char*) str->byte_address(); + size_t size = str->byte_size(); + + if(LANGUAGE_18_ENABLED(state)) { + for(size_t i = 0; i < size; i++) { + if(bytes[i] == 0) { + Exception::argument_error(state, + "cannot create a symbol from a string containing `\\0'"); + return NULL; + } + } + } + + return lookup(state, bytes, size); + } + + String* SymbolTable::lookup_string(STATE, const Symbol* sym) { + if(sym->nil_p()) { + Exception::argument_error(state, "Cannot look up Symbol from nil"); + return NULL; + } + + std::string& str = strings[sym->index()]; + return String::create(state, str.data(), str.size()); + } + + std::string& SymbolTable::lookup_cppstring(const Symbol* sym) { + return strings[sym->index()]; + } + + std::string SymbolTable::lookup_debug_string(const Symbol* sym) { + std::string str = lookup_cppstring(sym); + std::ostringstream os; + unsigned char* cstr = (unsigned char*) str.data(); + size_t size = str.size(); + for(size_t i = 0; i < size; ++i) { + if(isprint(cstr[i]) && isascii(cstr[i])) { + os << cstr[i]; + } else { + os << "\\x" << std::setw(2) << std::setfill('0') << std::hex << (unsigned int)cstr[i]; + } + } + return os.str(); + } + + size_t SymbolTable::size() { + return strings.size(); + } + + int SymbolTable::byte_size() { + int total = 0; + + for(SymbolStrings::iterator i = strings.begin(); + i != strings.end(); + ++i) { + total += i->size(); + total += sizeof(std::string); + } + + return total; + } + + Array* SymbolTable::all_as_array(STATE) { + size_t idx = 0; + Array* ary = Array::create(state, this->size()); + + for(SymbolMap::iterator s = symbols.begin(); s != symbols.end(); ++s) { + for(SymbolIds::iterator i = s->second.begin(); i != s->second.end(); ++i) { + ary->set(state, idx++, (Object*)Symbol::from_index(state, *i)); + } + } + + return ary; + } +} diff --git a/pool/shard007/C++/0092730_textquickitem.cpp b/pool/shard007/C++/0092730_textquickitem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bed1899f28b760f33197bb67bc0f11f396799ea0 --- /dev/null +++ b/pool/shard007/C++/0092730_textquickitem.cpp @@ -0,0 +1,132 @@ +///////////////////////////////////////////////////////////////////////////// +// Name: textquickitem.cpp +// Author: Jonathan Schluessler +// Created: 2017 +// Copyright (c) Authors and others. All rights reserved. +///////////////////////////////////////////////////////////////////////////// + +#include "vrvqt/textquickitem.h" + +//---------------------------------------------------------------------------- + +#include <QPainter> + +//#define DRAW_DEBUG_BOUNDING_BOXES + +namespace vrvQt { + +TextQuickItem::TextQuickItem() +{ + // TODO: Try following optimization hints on different platforms + // setRenderTarget(QQuickPaintedItem::FramebufferObject); + // setPerformanceHint(QQuickPaintedItem::FastFBOResizing); + // setAntialiasing(true); + // setMipmap(true); +} + +void TextQuickItem::appendText(QString text, QFont font) +{ + m_textParts.append(TextWithFont(text, font)); +} + +void TextQuickItem::calcPos() +{ + // Note: It is not possible to re-use the existing bounding-box of the verovio-object because the stored + // values may be out-of-date. Thus we have to recalculate the correct position and baseline by examining the font. + + int textWidth = 0; + int textAscent = 0; + int textDescent = 0; + int textXShift = 0; + + bool hasBoldFont = false; + bool hasItalicFont = false; + + bool firstLoop = true; + for (TextWithFont &textWithFont : m_textParts) { + + // Note: Initial construction of QFontMetrics is expensive (This function takes ~95% of first updatePaintNode + // call - e.g 48,5 of 51 ms)! Subsequent calls are much faster, so Qt seems to already have a caching mechanism + // in place. There is no significant difference between using tightBoundingRect, boundingRect or merely + // height/width. + QFontMetrics fm(textWithFont.font); + + // QFontMetrics::boundingRect(QChar) is more accurate than the QString overload, thus we prefer it if we only + // have 1 symbol (which is often the case, e.g. for music text). Using tightBoundingRect would result in many + // bounding boxes that are too narrow. + QRect boundingRect; + if (textWithFont.text.size() == 1) + boundingRect = fm.boundingRect(textWithFont.text.front()); + else + boundingRect = fm.boundingRect(textWithFont.text); + + textWithFont.offset = textWidth; + textWidth += boundingRect.right() - boundingRect.left(); + textAscent = std::max(textAscent, boundingRect.top() * -1); + textDescent = std::max(textDescent, boundingRect.bottom()); + if (firstLoop) { + // Note that the bounding rect can start at a negative x (e.g. italic font) + textXShift = boundingRect.left(); + if (textXShift < 0) textWidth -= textXShift; + firstLoop = false; + } + + if (textWithFont.font.bold()) hasBoldFont = true; + if (textWithFont.font.italic()) hasItalicFont = true; + } + + // Security margin for bold/italic fonts because the bounding rects are sometimes too narrow + if (hasBoldFont || hasItalicFont) { + textWidth += 4; + textAscent += 4; + textDescent += 1; + } + + qreal newX = x() + textXShift; + if (m_alignment == Qt::AlignRight) { + setX(newX - textWidth); + } + else if (m_alignment == Qt::AlignHCenter) { + setX(newX - textWidth / 2); + } + else { + setX(newX); + } + setY(y() - textAscent); + + m_paintOffsetY = textAscent; + m_paintOffsetX = -textXShift; + + int textHeight = textDescent + textAscent + 1; + + setImplicitWidth(textWidth); + setImplicitHeight(textHeight); +} + +void TextQuickItem::setColor(QColor color) +{ + m_color = color; + update(); +} + +bool TextQuickItem::isEmpty() +{ + return m_textParts.empty(); +} + +void TextQuickItem::paint(QPainter *painter) +{ + painter->setPen(m_color); + + for (TextWithFont textWithFont : m_textParts) { + painter->setFont(textWithFont.font); + painter->drawText(m_paintOffsetX + textWithFont.offset, m_paintOffsetY, textWithFont.text); + } + +#ifdef DRAW_DEBUG_BOUNDING_BOXES + painter->setPen(QColor(Qt::red)); + painter->setBrush(QColor(255, 0, 0, 100)); + painter->drawRect(0, 0, implicitWidth(), implicitHeight()); +#endif +} +} // namespace vrvQt diff --git a/pool/shard007/C++/0092739_plane-binding.cpp b/pool/shard007/C++/0092739_plane-binding.cpp new file mode 100644 index 0000000000000000000000000000000000000000..626b7d763acbecd6092d7c18953b190b6f56076e --- /dev/null +++ b/pool/shard007/C++/0092739_plane-binding.cpp @@ -0,0 +1,77 @@ +/* +** plane-binding.cpp +** +** This file is part of mkxp. +** +** Copyright (C) 2013 Jonas Kulla <Nyocurio@gmail.com> +** +** mkxp is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** mkxp is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have received a copy of the GNU General Public License +** along with mkxp. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "plane.h" +#include "disposable-binding.h" +#include "viewportelement-binding.h" +#include "binding-util.h" +#include "binding-types.h" + +DEF_TYPE(Plane); + +RB_METHOD(planeInitialize) +{ + Plane *p = viewportElementInitialize<Plane>(argc, argv, self); + + setPrivateData(self, p); + + p->initDynAttribs(); + + wrapProperty(self, &p->getColor(), "color", ColorType); + wrapProperty(self, &p->getTone(), "tone", ToneType); + + return self; +} + +DEF_PROP_OBJ_REF(Plane, Bitmap, Bitmap, "bitmap") +DEF_PROP_OBJ_VAL(Plane, Color, Color, "color") +DEF_PROP_OBJ_VAL(Plane, Tone, Tone, "tone") + +DEF_PROP_I(Plane, OX) +DEF_PROP_I(Plane, OY) +DEF_PROP_I(Plane, Opacity) +DEF_PROP_I(Plane, BlendType) + +DEF_PROP_F(Plane, ZoomX) +DEF_PROP_F(Plane, ZoomY) + + +void +planeBindingInit() +{ + VALUE klass = rb_define_class("Plane", rb_cObject); + rb_define_alloc_func(klass, classAllocate<&PlaneType>); + + disposableBindingInit<Plane> (klass); + viewportElementBindingInit<Plane>(klass); + + _rb_define_method(klass, "initialize", planeInitialize); + + INIT_PROP_BIND( Plane, Bitmap, "bitmap" ); + INIT_PROP_BIND( Plane, OX, "ox" ); + INIT_PROP_BIND( Plane, OY, "oy" ); + INIT_PROP_BIND( Plane, ZoomX, "zoom_x" ); + INIT_PROP_BIND( Plane, ZoomY, "zoom_y" ); + INIT_PROP_BIND( Plane, Opacity, "opacity" ); + INIT_PROP_BIND( Plane, BlendType, "blend_type" ); + INIT_PROP_BIND( Plane, Color, "color" ); + INIT_PROP_BIND( Plane, Tone, "tone" ); +} diff --git a/pool/shard007/C++/0092740_lru.cpp b/pool/shard007/C++/0092740_lru.cpp new file mode 100644 index 0000000000000000000000000000000000000000..94349a2220bc650c87e6b3835cc4791ffdd96954 --- /dev/null +++ b/pool/shard007/C++/0092740_lru.cpp @@ -0,0 +1,240 @@ +#include <fstream> +#include <functional> +#include "lru.h" + +struct Num_match: public std::binary_function< Pair_num_size, int, bool > { + bool operator () ( const Pair_num_size item, const int &number ) const { + return item.first == number; + } +}; + +Lru::Lru() { + m_quota = 0; + m_size = 0; +} + +void Lru::init_home(string homedir) { + m_homedir = homedir; + return; +} + +void Lru::init_quota(unsigned long q) { + m_quota = q * 1024; // q is in KB +} + +unsigned long Lru::get_quota() { + return m_quota; +} + +unsigned long Lru::get_size() { + return m_size; +} + + +// function push +// Push a new item or update an existing one's position. +// In both cases, it will be the most recently used one. +// return +// true if item pushed or updated. +// false if disk quota exceeds. +bool Lru::push(int num, unsigned long size, vector<int>& victims) { + + if (size > m_quota) { + return false; + } + + list<Pair_num_size>::iterator it = find_if(m_list.begin(), m_list.end(), std::bind2nd(Num_match(), size)); + Pair_num_size new_item(num, size); + + if(it == m_list.end()) { // Not found + while(m_size + size > m_quota) { + // Evacuate occupants. + Pair_num_size victim = m_list.front(); + m_list.pop_front(); + + m_size -= victim.second; + victims.push_back(victim.first); + } + + // Push it. + m_list.push_back(new_item); + m_size += size; + return true; + } + else { // found + // Just update order ONLY. + list<Pair_num_size>::iterator it1 = it; + it1++; + m_list.splice(it, m_list, it1, m_list.end()); + return true; + } +} + + +// function pop +// Pop the least recently used (LRU) item. +// return +// true if success +// note +// item will be updated only when popping succeeded +// +bool Lru::pop(int& num, unsigned long& size) { + if(m_list.empty()) { + return false; + } + else { + Pair_num_size pair = m_list.front(); + num = pair.first; + size = pair.second; + m_size -= pair.second; + m_list.pop_front(); + return true; + } +} + +bool Lru::erase(int num) { + if(m_list.empty()) { + return false; + } + else { + list<Pair_num_size>::iterator itr; + for(itr = m_list.begin(); itr != m_list.end(); itr++) { + if (itr->first == num) { + m_size -= itr->second; + m_list.erase(itr); + return true; + } + } + } + return false; +} + +void Lru::print() { + list<Pair_num_size>::iterator it; + + for(it = m_list.begin(); it != m_list.end(); it++) { + cout << it->first << ":" << it->second << " "; + } + cout << "size: " << get_size(); + cout << endl; +} + +int Lru::write_lru_file() { + int err = 0; + FILE* fp = NULL; + + char file_name[200] = ""; + sprintf(file_name, "%slru.txt", m_homedir.c_str()); + fp = fopen(file_name, "w"); + if(!fp) { + return -1; + } + + fprintf(fp, "%d", m_list.size()); + + list<Pair_num_size>::iterator itr; + for(itr = m_list.begin(); itr != m_list.end(); itr++) { + fprintf(fp, " %d %lu", itr->first, itr->second); + } + fprintf(fp, "\n"); + + fclose(fp); + return err; +} + +int Lru::read_lru_file() { + int err = 0; + char file_name[200] = ""; + + sprintf(file_name, "%slru.txt", m_homedir.c_str()); + + ifstream file (file_name); + if (file.is_open()) { + while(!file.eof()) + { + int num = 0; + int file_no = 0; + unsigned long file_size = 0; + vector<int> victims; + + file >> num; + for(int i = 0; i < num; i++) { + file >> file_no; + file >> file_size; + push(file_no, file_size, victims); + } + } + file.close(); + } + else { + err = -1; + } + + return err; + +} + + +/* +int main() { + Lru lru; + lru.init_quota(10); + + int num = -99; + unsigned long size = 0; + + lru.push(1, 1); + lru.print(); + + lru.push(2, 2); + lru.print(); + + lru.push(3, 3); + lru.print(); + + lru.push(4, 4); + lru.print(); + + lru.push(1, 1); + lru.print(); + + lru.push(5, 5); + lru.print(); + + lru.push(3, 3); + lru.print(); + + if(lru.pop(num, size)) { + cout << "popping LRU: " << num << endl; + lru.print(); + } + + lru.push(5, 5); + lru.print(); + + if(lru.pop(num, size)) { + cout << "popping LRU: " << num << endl; + lru.print(); + } + + lru.push(5, 5); + lru.print(); + + if(lru.pop(num, size)) { + cout << "popping LRU: " << num << endl; + lru.print(); + } + + if(lru.pop(num, size)) { + cout << "popping LRU: " << num << endl; + lru.print(); + } + + if(lru.pop(num, size)) { + cout << "popping LRU: " << num << endl; + lru.print(); + } + + return 0; +} +*/ diff --git a/pool/shard007/C++/0092744_tcp-rtt-estimation.cc b/pool/shard007/C++/0092744_tcp-rtt-estimation.cc new file mode 100644 index 0000000000000000000000000000000000000000..639196235e400c98ceda670a61f4242d99e73626 --- /dev/null +++ b/pool/shard007/C++/0092744_tcp-rtt-estimation.cc @@ -0,0 +1,303 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2016 Natale Patriciello <natale.patriciello@gmail.com> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation; + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +#include "tcp-general-test.h" +#include "ns3/node.h" +#include "ns3/log.h" +#include "ns3/rtt-estimator.h" +#include "tcp-error-model.h" + +using namespace ns3; + +NS_LOG_COMPONENT_DEFINE ("TcpRttEstimationTestSuite"); + +/** + * \ingroup internet-test + * \ingroup tests + * + * \brief Check Rtt calculations + * + * First check is that, for each ACK, we have a valid estimation of the RTT. + * The second check is that, when updating RTT history, we should consider + * retransmission only segments which sequence number is lower than the highest + * already transmitted. + */ +class TcpRttEstimationTest : public TcpGeneralTest +{ +public: + /** + * \brief Constructor. + * \param desc Test description. + * \param enableTs Enable TimeStamp option. + * \param pktCount Packet number. + */ + TcpRttEstimationTest (const std::string &desc, bool enableTs, uint32_t pktCount); + +protected: + virtual Ptr<TcpSocketMsgBase> CreateReceiverSocket (Ptr<Node> node); + virtual Ptr<TcpSocketMsgBase> CreateSenderSocket (Ptr<Node> node); + + virtual void Rx (const Ptr<const Packet> p, const TcpHeader&h, SocketWho who); + virtual void Tx (const Ptr<const Packet> p, const TcpHeader&h, SocketWho who); + virtual void UpdatedRttHistory (const SequenceNumber32 & seq, uint32_t sz, + bool isRetransmission, SocketWho who); + virtual void RttTrace (Time oldTime, Time newTime); + void FinalChecks (); + + virtual void ConfigureEnvironment (); + +private: + bool m_enableTs; //!< Enable TimeStamp option + bool m_rttChanged; //!< True if RTT has changed. + SequenceNumber32 m_highestTxSeq; //!< Highest sequence number sent. + uint32_t m_pktCount; //!< Packet counter. + uint32_t m_dataCount; //!< Data counter. +}; + +TcpRttEstimationTest::TcpRttEstimationTest (const std::string &desc, bool enableTs, + uint32_t pktCount) + : TcpGeneralTest (desc), + m_enableTs (enableTs), + m_rttChanged (false), + m_highestTxSeq (0), + m_pktCount (pktCount), + m_dataCount (0) +{ +} + +void +TcpRttEstimationTest::ConfigureEnvironment () +{ + TcpGeneralTest::ConfigureEnvironment (); + SetAppPktCount (m_pktCount); + SetPropagationDelay (MilliSeconds (50)); + SetTransmitStart (Seconds (2.0)); + SetMTU (500); +} + +Ptr<TcpSocketMsgBase> +TcpRttEstimationTest::CreateReceiverSocket (Ptr<Node> node) +{ + Ptr<TcpSocketMsgBase> s = TcpGeneralTest::CreateReceiverSocket (node); + if (!m_enableTs) + { + s->SetAttribute ("Timestamp", BooleanValue (false)); + } + + return s; +} + +Ptr<TcpSocketMsgBase> +TcpRttEstimationTest::CreateSenderSocket (Ptr<Node> node) +{ + Ptr<TcpSocketMsgBase> s = TcpGeneralTest::CreateSenderSocket (node); + if (!m_enableTs) + { + s->SetAttribute ("Timestamp", BooleanValue (false)); + } + + return s; +} + +void +TcpRttEstimationTest::Tx (const Ptr<const Packet> p, const TcpHeader &h, SocketWho who) +{ + if (who == SENDER && h.GetFlags () != TcpHeader::SYN) + { + if (m_highestTxSeq < h.GetSequenceNumber ()) + { + m_highestTxSeq = h.GetSequenceNumber (); + m_dataCount = 0; + } + + Ptr<RttEstimator> rttEstimator = GetRttEstimator (SENDER); + NS_ASSERT (rttEstimator != 0); + NS_LOG_DEBUG ("S Tx: seq=" << h.GetSequenceNumber () << " ack=" << h.GetAckNumber ()); + NS_TEST_ASSERT_MSG_NE (rttEstimator->GetEstimate (), Seconds (1), + "Default Estimate for the RTT"); + } +} + +void +TcpRttEstimationTest::Rx (const Ptr<const Packet> p, const TcpHeader &h, SocketWho who) +{ + if (who == RECEIVER) + { + NS_LOG_DEBUG ("R Rx: seq=" << h.GetSequenceNumber () << " ack=" << h.GetAckNumber ()); + } +} + +void +TcpRttEstimationTest::UpdatedRttHistory (const SequenceNumber32 & seq, uint32_t sz, + bool isRetransmission, SocketWho who) +{ + if (sz == 0) + { + return; + } + + if (seq < m_highestTxSeq) + { + NS_TEST_ASSERT_MSG_EQ (isRetransmission, true, + "A retransmission is not flagged as such"); + } + else if (seq == m_highestTxSeq && m_dataCount == 0) + { + NS_TEST_ASSERT_MSG_EQ (isRetransmission, false, + "Incorrectly flagging seq as retransmission"); + m_dataCount++; + } + else if (seq == m_highestTxSeq && m_dataCount > 0) + { + NS_TEST_ASSERT_MSG_EQ (isRetransmission, true, + "A retransmission is not flagged as such"); + } +} + +void +TcpRttEstimationTest::RttTrace (Time oldTime, Time newTime) +{ + NS_LOG_DEBUG ("Rtt changed to " << newTime.GetSeconds ()); + m_rttChanged = true; +} + +void +TcpRttEstimationTest::FinalChecks () +{ + NS_TEST_ASSERT_MSG_EQ (m_rttChanged, true, "Rtt was not updated"); +} + + +/** + * \ingroup internet-test + * \ingroup tests + * + * \brief Check Rtt calculations with packet losses. + * + * \see TcpRttEstimationTest + */ +class TcpRttEstimationWithLossTest : public TcpRttEstimationTest +{ +public: + /** + * \brief Constructor. + * \param desc Test description. + * \param enableTs Enable TimeStamp option. + * \param pktCount Packet number. + * \param toDrop List of packet to drop. + */ + TcpRttEstimationWithLossTest (const std::string &desc, bool enableTs, + uint32_t pktCount, std::vector<uint32_t> toDrop); + +protected: + Ptr<ErrorModel> CreateReceiverErrorModel (); + +private: + std::vector<uint32_t> m_toDrop; //!< Packets to drop. +}; + +TcpRttEstimationWithLossTest::TcpRttEstimationWithLossTest (const std::string &desc, + bool enableTs, + uint32_t pktCount, + std::vector<uint32_t> toDrop) + : TcpRttEstimationTest (desc, enableTs, pktCount), + m_toDrop (toDrop) +{ + +} + +Ptr<ErrorModel> +TcpRttEstimationWithLossTest::CreateReceiverErrorModel () +{ + Ptr<TcpSeqErrorModel> errorModel = CreateObject<TcpSeqErrorModel> (); + + std::vector<uint32_t>::iterator it; + + for (it = m_toDrop.begin (); it != m_toDrop.end (); ++it) + { + errorModel->AddSeqToKill (SequenceNumber32 ((*it))); + } + + return errorModel; +} + + + +/** + * \ingroup internet-test + * \ingroup tests + * + * \brief TCP RTT estimation TestSuite + */ +class TcpRttEstimationTestSuite : public TestSuite +{ +public: + TcpRttEstimationTestSuite () : TestSuite ("tcp-rtt-estimation-test", UNIT) + { + AddTestCase (new TcpRttEstimationTest ("RTT estimation, ts, no data", true, 0), + TestCase::QUICK); + AddTestCase (new TcpRttEstimationTest ("RTT estimation, no ts, no data", false, 0), + TestCase::QUICK); + AddTestCase (new TcpRttEstimationTest ("RTT estimation, ts, some data", true, 10), + TestCase::QUICK); + AddTestCase (new TcpRttEstimationTest ("RTT estimation, no ts, some data", false, 10), + TestCase::QUICK); + + std::vector<uint32_t> toDrop; + toDrop.push_back (501); + + AddTestCase (new TcpRttEstimationWithLossTest ("RTT estimation, no ts," + " some data, with retr", + false, 10, toDrop), + TestCase::QUICK); + AddTestCase (new TcpRttEstimationWithLossTest ("RTT estimation, ts," + " some data, with retr", + true, 10, toDrop), + TestCase::QUICK); + + toDrop.push_back (501); + AddTestCase (new TcpRttEstimationWithLossTest ("RTT estimation, no ts," + " some data, with retr", + false, 10, toDrop), + TestCase::QUICK); + AddTestCase (new TcpRttEstimationWithLossTest ("RTT estimation, ts," + " some data, with retr", + true, 10, toDrop), + TestCase::QUICK); + + toDrop.push_back (54001); + toDrop.push_back (58001); + toDrop.push_back (58501); + toDrop.push_back (60001); + toDrop.push_back (68501); + AddTestCase (new TcpRttEstimationWithLossTest ("RTT estimation, no ts," + " a lot of data, with retr", + false, 1000, toDrop), + TestCase::QUICK); + AddTestCase (new TcpRttEstimationWithLossTest ("RTT estimation, ts," + " a lot of data, with retr", + true, 1000, toDrop), + TestCase::QUICK); + } + +}; + +static TcpRttEstimationTestSuite g_tcpRttEstimationTestSuite; //!< Static variable for test initialization + + diff --git a/pool/shard007/C++/0092751_LRUPolicy.cc b/pool/shard007/C++/0092751_LRUPolicy.cc new file mode 100644 index 0000000000000000000000000000000000000000..a1e3b277e1e5f7b4939caa7a08dac1e0af03ed83 --- /dev/null +++ b/pool/shard007/C++/0092751_LRUPolicy.cc @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2013 Advanced Micro Devices, Inc + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer; + * redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution; + * neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Author: Derek Hower + */ + +#include "mem/ruby/structures/LRUPolicy.hh" + + + +LRUPolicy::LRUPolicy(const Params * p) + : AbstractReplacementPolicy(p) +{ +} + + +LRUPolicy::~LRUPolicy() +{ +} + +LRUPolicy * +LRUReplacementPolicyParams::create() +{ + return new LRUPolicy(this); +} + + +void +LRUPolicy::touch(int64 set, int64 index, Tick time) +{ + assert(index >= 0 && index < m_assoc); + assert(set >= 0 && set < m_num_sets); + + m_last_ref_ptr[set][index] = time; +} + +int64 +LRUPolicy::getVictim(int64 set) const +{ + Tick time, smallest_time; + int64 smallest_index; + + smallest_index = 0; + smallest_time = m_last_ref_ptr[set][0]; + + for (unsigned i = 0; i < m_assoc; i++) { + time = m_last_ref_ptr[set][i]; + + if (time < smallest_time) { + smallest_index = i; + smallest_time = time; + } + } + + return smallest_index; +} diff --git a/pool/shard007/C++/0092754_kalman_filter3_d.cpp b/pool/shard007/C++/0092754_kalman_filter3_d.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d5ed44a87986db02958cf1b5b2fd0d5af0960129 --- /dev/null +++ b/pool/shard007/C++/0092754_kalman_filter3_d.cpp @@ -0,0 +1,139 @@ +#include <cmath> + +#include <rj_vision_filter/filter/kalman_filter3_d.hpp> +#include <rj_vision_filter/params.hpp> + +namespace vision_filter { + +DEFINE_NS_FLOAT64(kVisionFilterParamModule, robot, init_covariance, 100.0, + "Initial covariance of the filter. Controls how fast it gets " + "to the target.") +DEFINE_NS_FLOAT64(kVisionFilterParamModule, robot, process_noise, 0.5, + "Controls how quickly it reacts to changes in ball accelerations.") +DEFINE_NS_FLOAT64(kVisionFilterParamModule, robot, observation_noise, 2.0, + "Controls how much it trusts measurements from the camera.") +DEFINE_NS_FLOAT64(kVisionFilterParamModule, robot, orientation_scale, 1.0, + "Scales the covariance and noise to radians instead of " + "meters. Shouldn't matter too much, but it's here.") + +KalmanFilter3D::KalmanFilter3D() : KalmanFilter(1, 1) {} + +KalmanFilter3D::KalmanFilter3D(rj_geometry::Pose init_pose, rj_geometry::Twist init_twist) + : KalmanFilter(6, 3) { + // States are X pos, X vel, Y pos, Y vel, theta, omega + x_k1_k1_ << init_pose.position().x(), init_twist.linear().x(), init_pose.position().y(), + init_twist.linear().y(), init_pose.heading(), init_twist.angular(); + x_k_k1_ = x_k1_k1_; + x_k_k_ = x_k1_k1_; + + // Initial covariance is usually extremely high to converge to the true + // solution + double p = robot::PARAM_init_covariance; + double s = robot::PARAM_orientation_scale; + // clang-format off + P_k1_k1_ << p, 0, 0, 0, 0, 0, + 0, p, 0, 0, 0, 0, + 0, 0, p, 0, 0, 0, + 0, 0, 0, p, 0, 0, + 0, 0, 0, 0, s*p, 0, + 0, 0, 0, 0, 0, s*p; + // clang-format on + P_k_k1_ = P_k1_k1_; + P_k_k_ = P_k1_k1_; + + // State transition matrix (A) + // Pos, velocity, theta integrator. Assume constant velocity + double dt = PARAM_vision_loop_dt; + // clang-format off + F_k_ << 1, dt, 0, 0, 0, 0, + 0, 1, 0, 0, 0, 0, + 0, 0, 1, dt, 0, 0, + 0, 0, 0, 1, 0, 0, + 0, 0, 0, 0, 1, dt, + 0, 0, 0, 0, 0, 1; + // clang-format on + + // Control transition matrix (B) + // No inputs. Possible to update for our robots since we know our accel/vel + // command + // clang-format off + B_k_ << 0, + 0, + 0, + 0, + 0, + 0; + + // Observation Matrix (C) + // We can get positions + H_k_ << 1, 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, 0, + 0, 0, 0, 0, 1, 0; + // clang-format on + + // Covariance of process noise (how wrong A is) + // Based on a guassian white noise w_k in x_dot = A*x + B*u + G*w + // The noise can be propogated through the model resulting in a process + // noise of the form + // + // [1/3 T^3 1/2 T^2] * sigma^2 + // [1/2 T^2 T] + // Where sigma is the standard deviation of the process noise + // the change in velocity over one time step should be around sqrt(T * + // sigma^2) Note: T is the sample period Taken from Tiger's AutoRef. Most + // likely found through integration of error through the state matrices See + // https://en.wikipedia.org/wiki/Discretization#Discretization_of_process_noise + p = robot::PARAM_process_noise; + double sigma = sqrt(3.0 * p / dt) / dt; + double dt3 = 1.0 / 3.0 * dt * dt * dt * sigma * sigma; + double dt2 = 1.0 / 2.0 * dt * dt * sigma * sigma; + double dt1 = dt * sigma * sigma; + + // clang-format off + Q_k_ << dt3, dt2, 0, 0, 0, 0, + dt2, dt1, 0, 0, 0, 0, + 0, 0, dt3, dt2, 0, 0, + 0, 0, dt2, dt1, 0, 0, + 0, 0, 0, 0, s*dt3, s*dt2, + 0, 0, 0, 0, s*dt2, s*dt1; + // clang-format on + + // Covariance of observation noise (how wrong z_k is) + double o = robot::PARAM_observation_noise; + // clang-format off + R_k_ << o, 0, 0, + 0, o, 0, + 0, 0, s*o; + // clang-format on +} + +void KalmanFilter3D::predict_with_update(rj_geometry::Pose observation) { + z_k_ << observation.position().x(), observation.position().y(), observation.heading(); + + KalmanFilter::predict_with_update(); +} + +rj_geometry::Point KalmanFilter3D::get_pos() const { + return rj_geometry::Point(x_k_k_(0), x_k_k_(2)); +} + +double KalmanFilter3D::get_theta() const { return x_k_k_(4); } + +rj_geometry::Point KalmanFilter3D::get_vel() const { + return rj_geometry::Point(x_k_k_(1), x_k_k_(3)); +} + +double KalmanFilter3D::get_omega() const { return x_k_k_(5); } + +rj_geometry::Point KalmanFilter3D::get_pos_cov() const { + return rj_geometry::Point(P_k_k_(0, 0), P_k_k_(2, 2)); +} + +double KalmanFilter3D::get_theta_cov() const { return P_k_k_(4, 4); } + +rj_geometry::Point KalmanFilter3D::get_vel_cov() const { + return rj_geometry::Point(P_k_k_(1, 1), P_k_k_(3, 3)); +} + +double KalmanFilter3D::get_omega_cov() const { return P_k_k_(5, 5); } +} // namespace vision_filter \ No newline at end of file diff --git a/pool/shard007/C++/0092758_new_array_cookie_uaf_test.cpp b/pool/shard007/C++/0092758_new_array_cookie_uaf_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..335a56757d2961d4e337c8810dac436cf0510740 --- /dev/null +++ b/pool/shard007/C++/0092758_new_array_cookie_uaf_test.cpp @@ -0,0 +1,41 @@ +// REQUIRES: asan-64-bits +// RUN: %clangxx_asan -O3 %s -o %t +// RUN: %env_asan_opts=poison_array_cookie=1 not %run %t 2>&1 | FileCheck %s --check-prefix=COOKIE +// RUN: %env_asan_opts=poison_array_cookie=0 not %run %t 2>&1 | FileCheck %s --check-prefix=NO_COOKIE + +// UNSUPPORTED: ios + +#include <stdio.h> +#include <stdlib.h> +#include <assert.h> +int dtor_counter; +struct C { + int x; + ~C() { + dtor_counter++; + fprintf(stderr, "DTOR %d\n", dtor_counter); + } +}; + +__attribute__((noinline)) void Delete(C *c) { delete[] c; } +__attribute__((no_sanitize_address)) void Write42ToCookie(C *c) { + long *p = reinterpret_cast<long*>(c); + p[-1] = 42; +} + +int main(int argc, char **argv) { + C *buffer = new C[argc]; + delete [] buffer; + Write42ToCookie(buffer); + delete [] buffer; +// COOKIE: DTOR 1 +// COOKIE-NOT: DTOR 2 +// COOKIE: AddressSanitizer: loaded array cookie from free-d memory +// COOKIE: AddressSanitizer: attempting double-free +// NO_COOKIE: DTOR 1 +// NO_COOKIE: DTOR 43 +// NO_COOKIE-NOT: DTOR 44 +// NO_COOKIE-NOT: AddressSanitizer: loaded array cookie from free-d memory +// NO_COOKIE: AddressSanitizer: attempting double-free + +} diff --git a/pool/shard007/C++/0092762_8.2.cpp b/pool/shard007/C++/0092762_8.2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fdb1e58109da1432370db1f335d6aeb8ee0e36d2 --- /dev/null +++ b/pool/shard007/C++/0092762_8.2.cpp @@ -0,0 +1,33 @@ +#include <iostream> +#include <seqan/sequence.h> +#include <seqan/seq_io.h> +#include <seqan/stream.h> + +using namespace seqan; +using namespace std; + +int main(int argc, char const ** argv) { + + if (argc!=6){ + std::cerr << "USAGE: 8.2 FAIFILE FASTFILE ID START END\n"; + return 1; + } + + seqan::FaiIndex faiIndex; + if (read(faiIndex, argv[2],argv[1])!= 0){ + std::cerr << "ERROR: Could not read the index!\n"; + return 1; + } + + unsigned idx = 0; + if (!getIdByName(faiIndex, argv[3], idx)) + std::cerr << "ERROR: FAI index has no entry for "<<argv[3]<<".\n"; + + seqan::CharString seqChr1Infix; + if (readRegion(seqChr1Infix, faiIndex, idx, lexicalCast2(argv[4]), lexicalCast2(argv[5])) != 0) + std::cerr << "ERROR: Could not read region.\n"; + + cout << seqChr1Infix << endl; + + return 0; +} \ No newline at end of file diff --git a/pool/shard007/C++/0092779_QueryStringEncoderTest.cpp b/pool/shard007/C++/0092779_QueryStringEncoderTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e2b6d67ff58e33a92d84436e7ff7d811dff3bc6f --- /dev/null +++ b/pool/shard007/C++/0092779_QueryStringEncoderTest.cpp @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2010-2011 frankee zhou (frankee.zhou at gmail dot com) + * + * Distributed under 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 "gtest/gtest.h" +#include "cetty/handler/codec/http/QueryStringEncoder.h" + +using namespace cetty::handler::codec::http; + +TEST(QueryStringEncoderTest, testEncoder) { + static const char* EncoderStr = + "search?hl=zh-CN&newwindow=1&safe=strict&q=test+bss&aq=f&aqi=&aql=&oq="; + + QueryStringEncoder encoder("search"); + encoder.addParam("hl", "zh-CN"); + encoder.addParam("newwindow", "1"); + encoder.addParam("safe", "strict"); + encoder.addParam("q", "test+bss"); + encoder.addParam("aq", "f"); + encoder.addParam("aqi", ""); + encoder.addParam("aql", ""); + encoder.addParam("oq", ""); + + ASSERT_STREQ(EncoderStr, encoder.toString().c_str()); +} \ No newline at end of file diff --git a/pool/shard007/C++/0092785_blockwriter.cpp b/pool/shard007/C++/0092785_blockwriter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fef4c5d2c3e1771189afac99e7526f42a8debc67 --- /dev/null +++ b/pool/shard007/C++/0092785_blockwriter.cpp @@ -0,0 +1,30 @@ +#include "include/socket/blockwriter.h" + + +// Getter +QDataStream& BlockWriter::getStream(){ + return stream; +} + + +// Constructor +BlockWriter::BlockWriter(QIODevice* io){ + this->io = io; + + buffer.open(QIODevice::WriteOnly); + stream.setVersion(QDataStream::Qt_5_9); + stream.setDevice(&buffer); + stream << quint64(0); +} + + + +// Destructor +BlockWriter::~BlockWriter(){ + stream.device()->seek(0); + stream << static_cast<quint64>(buffer.size()); + io->write(buffer.buffer()); +} + + + diff --git a/pool/shard007/C++/0092786_PhysicsGhostObject.cpp b/pool/shard007/C++/0092786_PhysicsGhostObject.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2bb90ae4f344bb1b34010dfb0d2857703d34ddd2 --- /dev/null +++ b/pool/shard007/C++/0092786_PhysicsGhostObject.cpp @@ -0,0 +1,107 @@ +#include "Base.h" +#include "PhysicsGhostObject.h" +#include "Node.h" +#include "Game.h" + +namespace gameplay +{ + +PhysicsGhostObject::PhysicsGhostObject(Node* node, const PhysicsCollisionShape::Definition& shape, int group, int mask) + : PhysicsCollisionObject(node, group, mask), _ghostObject(NULL) +{ + Vector3 centerOfMassOffset; + PhysicsController* physicsController = Game::getInstance()->getPhysicsController(); + GP_ASSERT(physicsController); + + // Create and set the collision shape for the ghost object. + _collisionShape = physicsController->createShape(node, shape, ¢erOfMassOffset, false); + GP_ASSERT(_collisionShape); + + // Create the ghost object. + _ghostObject = bullet_new<btPairCachingGhostObject>(); + _ghostObject->setCollisionShape(_collisionShape->getShape()); + _ghostObject->setCollisionFlags(_ghostObject->getCollisionFlags() | btCollisionObject::CF_NO_CONTACT_RESPONSE); + + // Initialize a physics motion state object for syncing the transform. + _motionState = new PhysicsMotionState(_node, this, ¢erOfMassOffset); + _motionState->getWorldTransform(_ghostObject->getWorldTransform()); + + // Add the ghost object to the physics world. + physicsController->addCollisionObject(this); + + GP_ASSERT(_node); + _node->addListener(this); +} + +PhysicsGhostObject::~PhysicsGhostObject() +{ + GP_ASSERT(_node); + _node->removeListener(this); + + GP_ASSERT(Game::getInstance()->getPhysicsController()); + Game::getInstance()->getPhysicsController()->removeCollisionObject(this, true); + + SAFE_DELETE(_ghostObject); +} + +PhysicsGhostObject* PhysicsGhostObject::create(Node* node, Properties* properties) +{ + // Check if the properties is valid and has a valid namespace. + if (!properties || !(strcmp(properties->getNamespace(), "collisionObject") == 0)) + { + GP_ERROR("Failed to load ghost object from properties object: must be non-null object and have namespace equal to 'collisionObject'."); + return NULL; + } + + // Check that the type is specified and correct. + const char* type = properties->getString("type"); + if (!type) + { + GP_ERROR("Failed to load ghost object from properties object; required attribute 'type' is missing."); + return NULL; + } + if (strcmp(type, "GHOST_OBJECT") != 0) + { + GP_ERROR("Failed to load ghost object from properties object; attribute 'type' must be equal to 'GHOST_OBJECT'."); + return NULL; + } + + // Load the physics collision shape definition. + PhysicsCollisionShape::Definition shape = PhysicsCollisionShape::Definition::create(node, properties); + if (shape.isEmpty()) + { + GP_ERROR("Failed to create collision shape during ghost object creation."); + return NULL; + } + + // Create the ghost object. + PhysicsGhostObject* ghost = new PhysicsGhostObject(node, shape, + properties->exists("group") ? properties->getInt("group") : PHYSICS_COLLISION_GROUP_DEFAULT, + properties->exists("mask") ? properties->getInt("mask") : PHYSICS_COLLISION_MASK_DEFAULT); + + return ghost; +} + +PhysicsCollisionObject::Type PhysicsGhostObject::getType() const +{ + return GHOST_OBJECT; +} + +btCollisionObject* PhysicsGhostObject::getCollisionObject() const +{ + return _ghostObject; +} + +void PhysicsGhostObject::transformChanged(Transform* transform, long cookie) +{ + GP_ASSERT(_motionState); + GP_ASSERT(_ghostObject); + + // Update the motion state with the transform from the node. + _motionState->updateTransformFromNode(); + + // Update the transform on the ghost object. + _motionState->getWorldTransform(_ghostObject->getWorldTransform()); +} + +} diff --git a/pool/shard007/C++/0092787_InstallService.cpp b/pool/shard007/C++/0092787_InstallService.cpp new file mode 100644 index 0000000000000000000000000000000000000000..14509074c4edd6027035060ff8234ac60627d301 --- /dev/null +++ b/pool/shard007/C++/0092787_InstallService.cpp @@ -0,0 +1,115 @@ +#include <windows.h> +//#include <tchar.h> +//#include <strsafe.h> +#include <string.h> +#include <stdio.h> + +#define SVCNAME "OLXDedServer" +#define SVCDISPLAYNAME "OpenLieroX dedicated server" +#define SVCEXENAME "OLXDedServerService.exe" + +// +// Purpose: +// Installs a service in the SCM database +// +// Parameters: +// None +// +// Return value: +// None +// +VOID SvcInstall() +{ + SC_HANDLE schSCManager; + SC_HANDLE schService; + char szPath[MAX_PATH]; + char szCommand[MAX_PATH*2]; + + if( !GetModuleFileName( NULL, szPath, MAX_PATH ) ) + { + printf("Cannot install service (%d)\n", GetLastError()); + return; + } + char * sep = strrchr(szPath, '\\'); + if( sep ) + { + strcpy( sep+1, SVCEXENAME ); + } + + strcpy( szCommand, "\"" ); + strcat( szCommand, szPath ); + strcat( szCommand, "\"" ); + + // Get a handle to the SCM database. + + schSCManager = OpenSCManager( + NULL, // local computer + NULL, // ServicesActive database + SC_MANAGER_ALL_ACCESS); // full access rights + + if (NULL == schSCManager) + { + printf("OpenSCManager failed (%d)\n", GetLastError()); + return; + } + + // Create the service + + schService = CreateService( + schSCManager, // SCM database + SVCNAME, // name of service + SVCDISPLAYNAME, // service name to display + SERVICE_ALL_ACCESS, // desired access + SERVICE_WIN32_OWN_PROCESS, // service type + SERVICE_AUTO_START, // start type + SERVICE_ERROR_NORMAL, // error control type + szCommand, // path to service's binary + "extended base", // After net services + NULL, // no tag identifier + NULL, // no dependencies + NULL, // LocalSystem account + NULL); // no password + + if (schService == NULL) + { + char errorBuf[1024] = "Unknown error"; + FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, errorBuf, sizeof(errorBuf), NULL ); + printf("CreateService failed - %s - reboot and try again\n", errorBuf); + CloseServiceHandle(schSCManager); + return; + } + else printf("Service installed successfully, command = %s\n", szCommand); + + SERVICE_DESCRIPTION sd; + sd.lpDescription = "OpenLieroX dedicated server service. It will restart OLX process it it doesn't output anything to logs in 60 seconds - it checks both stdout.txt and dedicated_control.log files"; + + ChangeServiceConfig2( schService, SERVICE_CONFIG_DESCRIPTION, &sd); + + StartService( schService, 0, NULL); + + CloseServiceHandle(schService); + CloseServiceHandle(schSCManager); + + HKEY hKey; + DWORD dwDisp = 0; + const char * keyAddr = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\" SVCNAME; + + if(RegCreateKeyEx( HKEY_LOCAL_MACHINE, keyAddr, 0L, NULL, REG_OPTION_NON_VOLATILE, + KEY_ALL_ACCESS, NULL, &hKey, &dwDisp) != ERROR_SUCCESS) + { + printf("RegCreateKeyEx failed (%d)\n", GetLastError()); + return; + } + + DWORD MsgTypes = 0x00000007; // The magic value from MSDN + RegSetValueEx(hKey, "EventMessageFile", 0, REG_SZ, (const BYTE *)szPath, strlen(szPath) + 1); + RegSetValueEx(hKey, "TypesSupported", 0, REG_DWORD, (const BYTE *)&MsgTypes, sizeof(MsgTypes)); + + RegCloseKey(hKey); + +} + +void main(int argc, char *argv[]) +{ + SvcInstall(); +} diff --git a/pool/shard007/C++/0092788_gmm-make-regtree.cc b/pool/shard007/C++/0092788_gmm-make-regtree.cc new file mode 100644 index 0000000000000000000000000000000000000000..8c79d013e0d9a7f86cfd3877d9e4372d6717c9dd --- /dev/null +++ b/pool/shard007/C++/0092788_gmm-make-regtree.cc @@ -0,0 +1,107 @@ +// gmmbin/gmm-make-regtree.cc + +// Copyright 2009-2011 Saarland University; Microsoft Corporation + +// See ../../COPYING for clarification regarding multiple authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +// MERCHANTABLITY OR NON-INFRINGEMENT. +// See the Apache 2 License for the specific language governing permissions and +// limitations under the License. + +#include "base/kaldi-common.h" +#include "util/kaldi-io.h" +#include "util/text-utils.h" +#include "gmm/mle-am-diag-gmm.h" +#include "tree/context-dep.h" +#include "hmm/transition-model.h" +#include "transform/regression-tree.h" + + +int main(int argc, char *argv[]) { + try { + typedef kaldi::int32 int32; + typedef kaldi::BaseFloat BaseFloat; + + const char *usage = + "Build regression class tree.\n" + "Usage: gmm-make-regtree [options] <model-file> <regtree-out>\n" + "E.g.: gmm-make-regtree --silphones=1:2:3 --state-occs=1.occs 1.mdl 1.regtree\n" + " [Note: state-occs come from --write-occs option of gmm-est]\n"; + + std::string occs_in_filename; + std::string sil_phones_str; + bool binary_write = true; + int32 max_leaves = 1; + kaldi::ParseOptions po(usage); + po.Register("state-occs", &occs_in_filename, "File containing state occupancies (use --write-occs in gmm-est)"); + po.Register("sil-phones", &sil_phones_str, "Colon-separated list of integer ids of silence phones, e.g. 1:2:3; if used, create top-level speech/sil split (only one reg-class for silence)."); + po.Register("binary", &binary_write, "Write output in binary mode"); + po.Register("max-leaves", &max_leaves, "Maximum number of leaves in regression tree."); + po.Read(argc, argv); + + if (po.NumArgs() != 2) { + po.PrintUsage(); + exit(1); + } + + std::string model_in_filename = po.GetArg(1), + tree_out_filename = po.GetArg(2); + + kaldi::AmDiagGmm am_gmm; + kaldi::TransitionModel trans_model; + { + bool binary_read; + kaldi::Input ki(model_in_filename, &binary_read); + trans_model.Read(ki.Stream(), binary_read); + am_gmm.Read(ki.Stream(), binary_read); + } + + kaldi::Vector<BaseFloat> state_occs; + if (occs_in_filename != "") { + bool binary_read; + kaldi::Input ki(occs_in_filename, &binary_read); + state_occs.Read(ki.Stream(), binary_read); + } else { + KALDI_LOG << "--state-occs option not provided so using constant occupancies."; + state_occs.Resize(am_gmm.NumPdfs()); + state_occs.Set(1.0); + } + + std::vector<int32> sil_pdfs; + if (sil_phones_str != "") { + std::vector<int32> sil_phones; + if (!kaldi::SplitStringToIntegers(sil_phones_str, ":", false, &sil_phones)) + KALDI_ERR << "invalid sil-phones option " << sil_phones_str; + std::sort(sil_phones.begin(), sil_phones.end()); + bool ans = GetPdfsForPhones(trans_model, sil_phones, &sil_pdfs); + if (!ans) + KALDI_WARN << "Pdfs associated with silence phones are not only " + "associated with silence phones: your speech-silence split " + "may not be meaningful."; + } + + kaldi::RegressionTree regtree; + regtree.BuildTree(state_occs, sil_pdfs, am_gmm, max_leaves); + // Write out the regression tree + { + kaldi::Output ko(tree_out_filename, binary_write); + regtree.Write(ko.Stream(), binary_write); + } + + KALDI_LOG << "Written regression tree to " << tree_out_filename; + } catch(const std::exception &e) { + std::cerr << e.what() << '\n'; + return -1; + } +} + + diff --git a/pool/shard007/C++/0092795_stabs_types.cpp b/pool/shard007/C++/0092795_stabs_types.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8355934c34dc59b2afe0dfc574a48910adbde024 --- /dev/null +++ b/pool/shard007/C++/0092795_stabs_types.cpp @@ -0,0 +1,208 @@ +/* Copyright 2013 David Axmark + +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 <vector> + +//todo: cleanup +#define LOGGING_ENABLED +#define CONFIG_H + +#include "helpers/helpers.h" +#include "helpers/hash_set.h" + +#include "stabs_types.h" +#include "stabs_file.h" +#include "stabs.h" + +using namespace std; + +//struct type_name_less : public binary_function<Type, Type, bool> { +class type_name_hash { +private: + hash_compare<string> mHC; +public: + enum { //arbitrary + bucket_size = 4, + min_buckets = 20000, + }; + size_t operator()(const Type* key) const { + return mHC(key->name); + } + bool operator()(const Type* left, const Type* right) const { + return (left->name < right->name); + } +}; + +struct type_tuple_hash { +private: + hash_compare<int> mHC; +public: + enum { + bucket_size = 4, + min_buckets = 20000, + }; + size_t operator()(const Type* key) const { + return mHC(mHC(key->id.a) + key->id.b); + } + bool operator()(const Type* left, const Type* right) const { + if(left->id.a < right->id.a) + return true; + else if(left->id.a == right->id.a) + return left->id.b < right->id.b; + else + return false; + } +}; + +#ifdef HAVE_TR1 +struct type_name_equal { + bool operator()(const Type* left, const Type* right) const { + return left->name == right->name; + } +}; +struct type_tuple_equal { + bool operator()(const Type* left, const Type* right) const { + return left->id == right->id; + } +}; +#define TNE ,type_name_equal +#define TTE ,type_tuple_equal +#else +#define TNE +#define TTE +#endif + +// this doesn't work yet for some strange reason. +//typedef hash_set<Type*, type_name_hash TNE> TypeNameSet; +//typedef hash_set<Type*, type_tuple_hash TTE> TypeTupleSet; + +typedef set<Type*, type_name_hash> TypeNameSet; +typedef set<Type*, type_tuple_hash> TypeTupleSet; + +static vector<TypeTupleSet*> sTypeTupleSets; +static vector<TypeNameSet*> sTypeNameSets; +static vector<std::string> sTypeFiles; + +void addTypeFile(int file, const std::string& fileName) { + if(file >= (int)sTypeTupleSets.size()) { + sTypeTupleSets.resize(file + 1); + sTypeNameSets.resize(file + 1); + sTypeFiles.resize(file + 1); + + sTypeTupleSets[file] = new TypeTupleSet; + sTypeNameSets[file] = new TypeNameSet; + } + + sTypeFiles[file] = fileName; +} + +bool addType(const Type& cs) { + Type* s = new Type(cs); + //LOG("addType %i (%i,%i)\n", gCurrentFile, s->id.a, s->id.b); + + pair<TypeTupleSet::iterator, bool> res = sTypeTupleSets[gCurrentFile]->insert(s); + if(res.second) { + sTypeNameSets[gCurrentFile]->insert(s); + } else { //tuple already defined. it must be a delayed type. + //LOG("dupe\n"); + Type* t = *res.first; + //DEBUG_ASSERT(t->type->type() == TypeBase::eUnknown); + if(t->type->type() != TypeBase::eUnknown) { + LOG("weird dupe: (%i,%i) %s\n", t->id.a, t->id.b, t->name.c_str()); + delete s; + return false; + } + DEBUG_ASSERT(t->id == s->id); + t->name = s->name; + t->type = s->type; + TypeTupleSet::iterator temp = res.first; + temp++; + sTypeTupleSets[gCurrentFile]->erase(res.first); +#if defined(__GNUC__) && !defined(HAVE_TR1) + sTypeTupleSets[gCurrentFile]->insert(t); +#else + sTypeTupleSets[gCurrentFile]->insert(temp, t); +#endif + sTypeNameSets[gCurrentFile]->erase(s); + sTypeNameSets[gCurrentFile]->insert(t); + } + + return true; +} + +const Type* stabsFindTypeByName(const std::string& name, int scope) { + if((size_t)scope>=sTypeTupleSets.size() || scope<0) return NULL; +#if 0 + set<Type>::const_iterator itr = sTypeTupleSets[scope].begin(); + for(;itr!=sTypeTupleSets[scope].end(); itr++) { + if((*itr).name == name) return &(*itr); + } + return NULL; +#endif + if(!sTypeNameSets[scope]) + return NULL; + Type t; + t.name = name; + TypeNameSet::const_iterator itr = sTypeNameSets[scope]->find(&t); + if(itr == sTypeNameSets[scope]->end()) + return NULL; + else + return *itr; +} + +const TypeBase* findTypeByNameAndFileGlobal(const std::string& name, int scope) { + const Type* type = stabsFindTypeByName(name, scope); + if(type) return type->type; + + // okay we didn't find it in the local scope, let's + // search through all scopes. If we get multiple hits + // we have an error.. + for(size_t i = 0; i < sTypeTupleSets.size(); i++) { + //LOG("Searching through type set of %s for type definition of %s\n", sTypeFiles[i].c_str(), name.c_str()); + const Type* type2 = stabsFindTypeByName(name, i); + if(type2) { + //LOG("Found one!\n"); + if(type) { + LOG("Multiple instances of type %s found.\n", name.c_str()); + //let's return one of the instances, for now. + return type->type; + } + type = type2; + } + } + + if(!type) return NULL; + return type->type; +} + +const TypeBase* findTypeByNameAndTupleAndFileGlobal(const std::string& name, Tuple tuple, int scope) { + const TypeBase* t = findTypeByTupleAndFile(tuple, scope); + if(t) return t; + + return findTypeByNameAndFileGlobal(name, scope); +} + +const TypeBase* findTypeByTuple(Tuple t) { + return findTypeByTupleAndFile(t, gCurrentFile); +} + +const TypeBase* findTypeByTupleAndFile(Tuple t, int file) { + Type s; + s.id = t; + TypeTupleSet::const_iterator itr = sTypeTupleSets[file]->find(&s); + if(itr == sTypeTupleSets[file]->end()) + return NULL; + return (*itr)->type; +} diff --git a/pool/shard007/C++/0092801_Mesh.cpp b/pool/shard007/C++/0092801_Mesh.cpp new file mode 100644 index 0000000000000000000000000000000000000000..52cf809b9b8e3d0823e4b5b6f2e82255ba004a8f --- /dev/null +++ b/pool/shard007/C++/0092801_Mesh.cpp @@ -0,0 +1,93 @@ +#include "stdafx.h" +#include "Mesh.h" +#include "Shader.h" +#include "Device.h" + + +CMesh::CMesh() + : m_pShader(NULL), + m_pGrapicDevice(CDevice::GetInstance()) +{ +} + + +CMesh::~CMesh() +{ +} + +void CMesh::Render() +{ + CVIBuffer::Render(); +} + +void CMesh::MakeVertexNormal(BYTE * _pVertices, WORD * _pIndices) +{ + if (!_pIndices) + SetNormalVectorByBasic(_pVertices); + else + SetNormalVectorByAverage(_pVertices, _pIndices, (m_iIndex / 3), 3, false); +} + +void CMesh::SetNormalVectorByBasic(BYTE * _pVertices) +{ + D3DXVECTOR3 vNormal; + VTXTEX* pVertex = NULL; + + int nPrimitives = m_iVertices / 3; + for (int i = 0; i < nPrimitives; ++i) + { + vNormal = GetTriAngleNormal(_pVertices, (i * 3 + 0), (i * 3 + 1), (i * 3 + 2)); + + pVertex = (VTXTEX*)(_pVertices + ((i * 3 + 0) * m_iVertexStrides)); + pVertex->vNormal = -vNormal; + pVertex = (VTXTEX*)(_pVertices + ((i * 3 + 1) * m_iVertexStrides)); + pVertex->vNormal = -vNormal; + pVertex = (VTXTEX*)(_pVertices + ((i * 3 + 2) * m_iVertexStrides)); + pVertex->vNormal = -vNormal; + } +} + +void CMesh::SetNormalVectorByAverage(BYTE * _pVertices, WORD * _pIndices, int _iPrimitives, int _iOffset, bool _bStrip) +{ + D3DXVECTOR3 vNormal(0.f, 0.f, 0.f); + VTXTEX* pVertex = NULL; + USHORT nIndex_0, nIndex_1, nIndex_2; + + for (int i = 0; i < m_iVertices; ++i) + { + vNormal = D3DXVECTOR3(0.f, 0.f, 0.f); + + for (int j = 0; j < _iPrimitives; j++) + { + nIndex_0 = (_bStrip) ? (((j % 2) == 0) ? (j * _iOffset + 0) : (j * _iOffset + 1)) : (j * _iOffset + 0); + if (_pIndices) nIndex_0 = _pIndices[nIndex_0]; + + nIndex_1 = (_bStrip) ? (((j % 2) == 0) ? (j * _iOffset + 1) : (j * _iOffset + 0)) : (j * _iOffset + 1); + if (_pIndices) nIndex_1 = _pIndices[nIndex_1]; + + nIndex_2 = (_pIndices) ? _pIndices[j * _iOffset + 2] : (j * _iOffset + 2); + + if ((nIndex_0 == i) || (nIndex_1 == i) || (nIndex_2 == i)) + vNormal += GetTriAngleNormal(_pVertices, nIndex_0, nIndex_1, nIndex_2); + } + D3DXVec3Normalize(&vNormal, &vNormal); + pVertex = (VTXTEX *)(_pVertices + (i * m_iVertexStrides)); + pVertex->vNormal = vNormal; + } +} + +D3DXVECTOR3 CMesh::GetTriAngleNormal(BYTE * _pVertices, USHORT _nIndex_0, USHORT _nIndex_1, USHORT _nIndex_2) +{ + D3DXVECTOR3 vNormal(0.f, 0.f, 0.f); + D3DXVECTOR3 vP_0 = *((D3DXVECTOR3 *)(_pVertices + (m_iVertexStrides * _nIndex_0))); + D3DXVECTOR3 vP_1 = *((D3DXVECTOR3 *)(_pVertices + (m_iVertexStrides * _nIndex_1))); + D3DXVECTOR3 vP_2 = *((D3DXVECTOR3 *)(_pVertices + (m_iVertexStrides * _nIndex_2))); + + D3DXVECTOR3 vEdge_0 = vP_1 - vP_0; + D3DXVECTOR3 vEdge_1 = vP_2 - vP_0; + + D3DXVec3Cross(&vNormal, &vEdge_0, &vEdge_1); + D3DXVec3Normalize(&vNormal, &vNormal); + + return vNormal; +} diff --git a/pool/shard007/C++/0092802_dnssrv.cpp b/pool/shard007/C++/0092802_dnssrv.cpp new file mode 100644 index 0000000000000000000000000000000000000000..de3238505c197ace7eea0a09647905d0acfcdb74 --- /dev/null +++ b/pool/shard007/C++/0092802_dnssrv.cpp @@ -0,0 +1,121 @@ +#include "jni.h" +#include <sys/types.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <sys/time.h> +#include <unistd.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include "udns.h" + +int srv_cmp(const void* v1, const void* v2) { + struct dns_srv* srv1 = (struct dns_srv*)v1; + struct dns_srv* srv2 = (struct dns_srv*)v2; + if(srv1->priority == srv2->priority) + return srv2->weight - srv1->weight; + else + return srv1->priority - srv2->priority; +} + +extern "C" jobjectArray Java_org_sipdroid_net_DnsSrv_getHostSRV(JNIEnv* env, jclass clazz, + jstring nameStr, jstring srvStr, jstring protoStr, jstring dnsStr0, jstring dnsStr1) { + if (nameStr == NULL || srvStr == NULL || protoStr == NULL || (dnsStr0 == NULL && dnsStr1 == NULL)) { + return NULL; + } + + jobjectArray ret = NULL; + struct dns_ctx *nctx = NULL; + + if (dns_init(NULL, 0) < 0 || !(nctx = dns_new(NULL))) + return NULL; + + const char* name = env->GetStringUTFChars(nameStr, NULL); + const char* srv = env->GetStringUTFChars(srvStr, NULL); + const char* proto = env->GetStringUTFChars(protoStr, NULL); + + int r = 0; + unsigned short port = dns_set_opt(nctx, DNS_OPT_PORT, -1); + + dns_add_serv(nctx, NULL); + + if(dnsStr0 != NULL) { + const char* dns = env->GetStringUTFChars(dnsStr0, NULL); + union { + struct sockaddr_in addr; + struct sockaddr_in6 addr6; + } a; + memset(&a, 0, sizeof(struct sockaddr_in6)); + + int iptype = 0; + + if (dns_pton(AF_INET, dns, &a.addr.sin_addr) > 0) { + iptype = 1; + a.addr.sin_family = AF_INET; + a.addr.sin_port = htons(port); + } + #ifdef HAVE_IPv6 + else if (dns_pton(AF_INET6, dns, &a.addr6.sin6_addr) > 0) { + iptype = 1; + a.addr6.sin6_family = AF_INET6; + a.addr6.sin6_port = htons(port); + } + #endif + env->ReleaseStringUTFChars(dnsStr0, dns); + + if(iptype) + r = dns_add_serv_s(nctx, (struct sockaddr *)&a); + } + + if(dnsStr1 != NULL) { + const char* dns = env->GetStringUTFChars(dnsStr1, NULL); + union { + struct sockaddr_in addr; + struct sockaddr_in6 addr6; + } a; + int iptype = 0; + + if (dns_pton(AF_INET, dns, &a.addr.sin_addr) > 0) { + iptype = 1; + a.addr.sin_family = AF_INET; + a.addr.sin_port = htons(port); + } + #ifdef HAVE_IPv6 + else if (dns_pton(AF_INET6, dns, &a.addr6.sin6_addr) > 0) { + iptype = 1; + a.addr6.sin6_family = AF_INET6; + a.addr6.sin6_port = htons(port); + } + #endif + env->ReleaseStringUTFChars(dnsStr1, dns); + + if(iptype) + r = dns_add_serv_s(nctx, (struct sockaddr *)&a); + } + + if(r > 0) { + if (dns_open(nctx) < 0) + return NULL; + + struct dns_rr_srv *rrsrv = dns_resolve_srv(nctx, name, srv, proto, 0); + if(rrsrv) { + qsort(rrsrv->dnssrv_srv, rrsrv->dnssrv_nrr, sizeof(struct dns_srv), srv_cmp); + ret = (jobjectArray)env->NewObjectArray(rrsrv->dnssrv_nrr, env->FindClass("java/lang/String"), env->NewStringUTF("")); + char buf[DNS_MAXNAME*2]; + for (int i = 0; i < rrsrv->dnssrv_nrr; i++) { + struct dns_srv* s = &rrsrv->dnssrv_srv[i]; + sprintf(buf, "%s,%d,%d,%d", s->name, s->port, s->priority, s->weight); + env->SetObjectArrayElement(ret, i, env->NewStringUTF(buf)); + } + free(rrsrv); + } + } + + env->ReleaseStringUTFChars(nameStr, name); + env->ReleaseStringUTFChars(srvStr, srv); + env->ReleaseStringUTFChars(protoStr, proto); + + dns_free(nctx); + + return ret; +} diff --git a/pool/shard007/C++/0092819_Utils.cpp b/pool/shard007/C++/0092819_Utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b19b8a730af19b7d564f5ffae218da086c6b019a --- /dev/null +++ b/pool/shard007/C++/0092819_Utils.cpp @@ -0,0 +1,85 @@ +#include <algorithm> +#include <iterator> + +#include "Utils.h" + +namespace sfall +{ + +WORD ByteSwapW(WORD w) { + return ((w & 0xFF) << 8) | ((w & 0xFF00) >> 8); +} + +DWORD ByteSwapD(DWORD dw) { + return ((dw & 0xFF) << 24) | ((dw & 0xFF00) << 8) | ((dw & 0xFF0000) >> 8) | ((dw & 0xFF000000) >> 24); +} + +std::vector<std::string> split(const std::string &s, char delim) { + std::vector<std::string> elems; + split(s, delim, std::back_inserter(elems)); + return elems; +} + +std::string trim(const std::string& str) { + size_t first = str.find_first_not_of(' '); + if (std::string::npos == first) { + return str; + } + size_t last = str.find_last_not_of(' '); + return str.substr(first, (last - first + 1)); +} + +void trim(char* str) { + if (str[0] == 0) return; + int len = strlen(str) - 1; + + int i = len; + while (len >= 0 && isSpace(str[len])) len--; + if (i != len) str[len + 1] = '\0'; // delete all spaces on the right + + i = 0; + while (i < len && isSpace(str[i])) i++; + if (i > 0) { + int j = 0; + do { + str[j] = str[j + i]; // shift all chars (including null char) to the left + } while (++j <= len); + } +} + +void ToLowerCase(std::string& line) { + std::transform(line.begin(), line.end(), line.begin(), ::tolower); +} + +bool isSpace(char c) { + return (c == ' ' || c == '\t' /*|| c == '\n' || c == '\r'*/); +} + +// returns position, find word must be lowercase +const char* strfind(const char* source, const char* word) { + if (source == 0 || word == 0 || *word == 0) return 0; + const char *w_pos, *s_pos; + while(*source != 0) { + w_pos = word, s_pos = source++; + while (tolower(*s_pos) == *w_pos) { + s_pos++; + if (*++w_pos == 0) return s_pos - (w_pos - word); + } + } + return 0; +} + +// replace all '/' chars to '\' +void StrNormalizePath(char* path) { + if (*path == 0) return; + do { + if (*path == '/') *path = '\\'; + } while (*(++path) != 0); +} + +// max range 0-32767 +long GetRandom(long min, long max) { + return (min + (std::rand() % (max - (min - 1)))); +} + +} diff --git a/pool/shard007/C++/0092823_hxsymbiansockhlp.cpp b/pool/shard007/C++/0092823_hxsymbiansockhlp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fc5b54caed2cbe23ec37d06d5898ab01d9b3f5f4 --- /dev/null +++ b/pool/shard007/C++/0092823_hxsymbiansockhlp.cpp @@ -0,0 +1,143 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Source last modified: $Id: hxsymbiansockhlp.cpp,v 1.5 2006/12/06 10:15:07 gahluwalia Exp $ + * + * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved. + * + * The contents of this file, and the files included with this file, + * are subject to the current version of the RealNetworks Public + * Source License (the "RPSL") available at + * http://www.helixcommunity.org/content/rpsl unless you have licensed + * the file under the current version of the RealNetworks Community + * Source License (the "RCSL") available at + * http://www.helixcommunity.org/content/rcsl, in which case the RCSL + * will apply. You may also obtain the license terms directly from + * RealNetworks. You may not use this file except in compliance with + * the RPSL or, if you have a valid RCSL with RealNetworks applicable + * to this file, the RCSL. Please see the applicable RPSL or RCSL for + * the rights, obligations and limitations governing use of the + * contents of the file. + * + * Alternatively, the contents of this file may be used under the + * terms of the GNU General Public License Version 2 or later (the + * "GPL") in which case the provisions of the GPL are applicable + * instead of those above. If you wish to allow use of your version of + * this file only under the terms of the GPL, and not to allow others + * to use your version of this file under the terms of either the RPSL + * or RCSL, indicate your decision by deleting the provisions above + * and replace them with the notice and other provisions required by + * the GPL. If you do not delete the provisions above, a recipient may + * use your version of this file under the terms of any one of the + * RPSL, the RCSL or the GPL. + * + * This file is part of the Helix DNA Technology. RealNetworks is the + * developer of the Original Code and owns the copyrights in the + * portions it created. + * + * This file, and the files included with this file, is distributed + * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY + * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS + * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET + * ENJOYMENT OR NON-INFRINGEMENT. + * + * Technology Compatibility Kit Test Suite(s) Location: + * http://www.helixcommunity.org/content/tck + * + * Contributor(s): + * + * ***** END LICENSE BLOCK ***** */ + +#include "hxsymbiansockhlp.h" +#include "hlxclib/string.h" +#include "hxtbuf.h" + +HX_RESULT HXSymbianSocketHelper::ResizeOrCreate(IHXCommonClassFactory* pCCF, + UINT32 ulSize, + REF(IHXBuffer*) pBuffer) +{ + HX_RESULT res = HXR_FAILED; + + if (pBuffer) + { + // We have a buffer so just resize it + res = pBuffer->SetSize(ulSize); + } + else + { + // We don't have a buffer so create one + res = CreateBuffer(pCCF, ulSize, pBuffer); + } + + return res; +} + +HX_RESULT HXSymbianSocketHelper::CopyOrTransfer(IHXCommonClassFactory* pCCF, + UINT32 ulSize, + REF(IHXBuffer*) pSrcBuf, + REF(IHXBuffer*) pDestBuf) +{ + HX_RESULT res = HXR_FAILED; + if (HXR_OK == CreateBuffer(pCCF, ulSize, pDestBuf)) + { + // Copy the data into the new buffer + memcpy(pDestBuf->GetBuffer(), pSrcBuf->GetBuffer(), ulSize); + IHXTimeStampedBuffer* pTSBuffer = 0; + UINT32 timeStamp = 0; + if(HXR_OK == pSrcBuf->QueryInterface(IID_IHXTimeStampedBuffer, (void **)&pTSBuffer)) + { + timeStamp = pTSBuffer->GetTimeStamp(); + HX_RELEASE(pTSBuffer); + } + if(HXR_OK == pDestBuf->QueryInterface(IID_IHXTimeStampedBuffer, (void **)&pTSBuffer)) + { + pTSBuffer->SetTimeStamp(timeStamp); + HX_RELEASE(pTSBuffer); + } + res = HXR_OK; + } + else if (pSrcBuf) + { + // We couldn't create a new buffer. Use the buffer we have + + // Transfer ownership + pDestBuf = pSrcBuf; + pSrcBuf = NULL; + + if (pDestBuf) + { + // Set the size + pDestBuf->SetSize(ulSize); + } + + res = HXR_OK; + } + + return res; +} + +HX_RESULT HXSymbianSocketHelper::CreateBuffer(IHXCommonClassFactory* pCCF, + UINT32 ulSize, + REF(IHXBuffer*) pBuffer) +{ + HX_RESULT res = HXR_FAILED; + + if (pCCF) + { + IHXTimeStampedBuffer* pTSBuffer = NULL; + res = pCCF->CreateInstance(IID_IHXTimeStampedBuffer, (void**)&pTSBuffer); + + if (HXR_OK == res) + { + pTSBuffer->QueryInterface(IID_IHXBuffer, (void**)&pBuffer); + HX_RELEASE(pTSBuffer); + res = pBuffer->SetSize(ulSize); + + if (HXR_OK != res) + { + HX_RELEASE(pBuffer); + } + } + } + + return res; +} diff --git a/pool/shard007/C++/0092827_simple_url_loader_test_helper.cc b/pool/shard007/C++/0092827_simple_url_loader_test_helper.cc new file mode 100644 index 0000000000000000000000000000000000000000..66a73e5cbdb670e48808a87a5e859e80e81d3971 --- /dev/null +++ b/pool/shard007/C++/0092827_simple_url_loader_test_helper.cc @@ -0,0 +1,41 @@ +// Copyright 2017 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 "content/public/test/simple_url_loader_test_helper.h" + +#include "base/bind.h" +#include "base/callback.h" +#include "base/check.h" + +namespace content { + +SimpleURLLoaderTestHelper::SimpleURLLoaderTestHelper() {} + +SimpleURLLoaderTestHelper::~SimpleURLLoaderTestHelper() {} + +network::SimpleURLLoader::BodyAsStringCallback +SimpleURLLoaderTestHelper::GetCallback() { + DCHECK(!callback_created_); + callback_created_ = true; + + return base::BindOnce(&SimpleURLLoaderTestHelper::OnCompleteCallback, + weak_ptr_factory_.GetWeakPtr()); +} + +void SimpleURLLoaderTestHelper::WaitForCallback() { + DCHECK(!wait_started_); + wait_started_ = true; + run_loop_.Run(); +} + +void SimpleURLLoaderTestHelper::OnCompleteCallback( + std::unique_ptr<std::string> response_body) { + DCHECK(!response_body_); + + response_body_ = std::move(response_body); + + run_loop_.Quit(); +} + +} // namespace content diff --git a/pool/shard007/C++/0092835_Queue.cpp b/pool/shard007/C++/0092835_Queue.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3a0cb109fb26407574b49c96f84782b7704041f4 --- /dev/null +++ b/pool/shard007/C++/0092835_Queue.cpp @@ -0,0 +1,184 @@ +// +// Queue.cpp +// laba2_OOP +// +// Created by Дима Басан on 04.12.15. +// Copyright © 2015 Дима Басан. All rights reserved. +// + +#include "Queue.hpp" +#include <fstream> +Element elementtwo; +Queue::Queue() +{ + first = EMPTY; +}; + +Queue::Queue(Queue& queue) +{ + for(int i=0;i<queue.GetCount();i++) + { + q[i].data=queue.q[i].data; + q[i].priority=queue.q[i].priority; + first=queue.first; + } +} + +Queue::Queue(int dataforconstr,short prioritetforconstr) +{ + Element elementforconstr; + elementforconstr.data=dataforconstr; + elementforconstr.priority=prioritetforconstr; + Add(elementforconstr); +} + +void Queue::Add(const Element elem) +{ + int i; + + // поиск позиции + for(i = first; i >= 0; i--) + if(q[i].priority > elem.priority) + break; + // Если очередь заполнена, удалить элемент с меньшим приоритетом + if(IsFull()) + { + if(i != -1) + { + for(int j = 0; j < i; j++) + q[j] = q[j + 1]; + + q[i] = elem; + } + } + else + { + for(int j = first; j > i; j--) + q[j + 1] = q[j]; + + q[i + 1] = elem; + first++; + } + +} + +int Queue::GetCount() +{ + return first + 1; +} + +Element Queue::Remove() +{ + if(IsEmpty()) + return Element(); + int temp1=9999; + int temp2=0; + for (int i=0; i<GetCount(); i++) { + if(q[i].priority<temp1) + { + temp1=q[i].priority; + temp2=i; + } + } + for(int i=temp2;i<GetCount()-1;i++) + { + q[i]=q[i+1]; + } + + return q[first--]; +} + + + +void Queue::Clear() +{ + first = EMPTY; +} + +void Queue::AddFromFile() +{ + ifstream fin; + fin.open("/Users/admin/Desktop/C++/laba2_OOP/laba2_OOP/1.txt"); + while (!fin.eof()) + { + fin>>elementtwo.data; + fin>>elementtwo.priority; + Add(elementtwo); + } + fin.close(); +} + +void Queue::SaveToFile(int count,int nameforfile) +{ + ofstream fout; + + char namefileforsave[51]="/Users/admin/Desktop/C++/laba2_OOP/laba2_OOP/"; + char str[2]; + str[0] =nameforfile+'0'; + str[1]=0; + char a[5]=".txt"; + fout.open(strcat(namefileforsave, strcat(str, a))); + + for(int i=0;i<count;i++) + { + + fout<<q[i].data; + fout<<" "; + fout<<q[i].priority; + fout<<endl; + } + fout.close(); +} + +Queue& Queue::operator->() +{ + return *this; +} + +Queue::Queue(Queue&qq,Queue&p,int countforcopy) +{ + for(int i=0; i<countforcopy;i++) + { + p.q[i].data=qq.q[i].data; + p.q[i].priority=qq.q[i].priority; + } +}; + +ostream& operator << (std::ostream& os, Queue& queue) { + return os << queue; +} + +istream& operator >>(istream& is, Queue& queue) { + Element elementforoperator; + is>>elementforoperator.data; + is>>elementforoperator.priority; + queue.Add(elementforoperator); + return is; +} + +int& Queue::operator[](int index) +{ + return ((int*)this)[index]; +} + +Queue & Queue::operator=(Queue queueforcopy1) +{ + + int k1=(*this).GetCount(); + int k2=queueforcopy1.GetCount(); + if (k2<k1) { + k1=k2; + } + + for(int i=0;i<k1;i++) + { + q[i].data=queueforcopy1.q[i].data; + q[i].priority=queueforcopy1.q[i].priority; + } + return (*this); + +} + + + + diff --git a/pool/shard007/C++/0092837_WKTStreamReader.cpp b/pool/shard007/C++/0092837_WKTStreamReader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4649d44523312d92f742ee3e665010dafc31f3b4 --- /dev/null +++ b/pool/shard007/C++/0092837_WKTStreamReader.cpp @@ -0,0 +1,64 @@ +/********************************************************************** + * + * GEOS - Geometry Engine Open Source + * http://geos.osgeo.org + * + * Copyright (C) 2020 Martin Davis + * + * This is free software; you can redistribute and/or modify it under + * the terms of the GNU Lesser General Public Licence as published + * by the Free Software Foundation. + * See the COPYING file for more information. + * + **********************************************************************/ + +#include <geos/io/WKTReader.h> + +#include <fstream> +#include <iostream> +#include <sstream> +#include <memory> // for unique_ptr +#include <algorithm> + +#include "WKTStreamReader.h" + +using namespace geos::geom; + +WKTStreamReader::WKTStreamReader(std::istream& p_instr) + : instr(p_instr) +{ +} + +WKTStreamReader::~WKTStreamReader() { + +} + +/*public*/ + + +/* +Return: nullptr if at EOF +*/ +Geometry* +WKTStreamReader::next() +{ + std::string wkt = ""; + + std::string::difference_type lParen = 0; + std::string::difference_type rParen = 0; + do { + std::string line; + std::getline(instr, line); + if (! instr) { + return nullptr; + } + + lParen += std::count(line.begin(), line.end(), '('); + rParen += std::count(line.begin(), line.end(), ')'); + + wkt += line; + } while (lParen == 0 || lParen != rParen); + + auto g = rdr.read( wkt.c_str() ); + return g.release(); +} diff --git a/pool/shard007/C++/0092838_gettransitgatewayregistrationsresponse.cpp b/pool/shard007/C++/0092838_gettransitgatewayregistrationsresponse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0100f6369ca9d8b0f52232225a55f13c894128bf --- /dev/null +++ b/pool/shard007/C++/0092838_gettransitgatewayregistrationsresponse.cpp @@ -0,0 +1,107 @@ +/* + Copyright 2013-2021 Paul Colby + + This file is part of QtAws. + + QtAws is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + QtAws is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with the QtAws. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "gettransitgatewayregistrationsresponse.h" +#include "gettransitgatewayregistrationsresponse_p.h" + +#include <QDebug> +#include <QNetworkReply> +#include <QXmlStreamReader> + +namespace QtAws { +namespace NetworkManager { + +/*! + * \class QtAws::NetworkManager::GetTransitGatewayRegistrationsResponse + * \brief The GetTransitGatewayRegistrationsResponse class provides an interace for NetworkManager GetTransitGatewayRegistrations responses. + * + * \inmodule QtAwsNetworkManager + * + * Transit Gateway Network Manager (Network Manager) enables you to create a global network, in which you can monitor your + * AWS and on-premises networks that are built around transit + * + * gateways> + * + * The Network Manager APIs are supported in the US West (Oregon) Region only. You must specify the <code>us-west-2</code> + * Region in all requests made to Network + * + * \sa NetworkManagerClient::getTransitGatewayRegistrations + */ + +/*! + * Constructs a GetTransitGatewayRegistrationsResponse object for \a reply to \a request, with parent \a parent. + */ +GetTransitGatewayRegistrationsResponse::GetTransitGatewayRegistrationsResponse( + const GetTransitGatewayRegistrationsRequest &request, + QNetworkReply * const reply, + QObject * const parent) + : NetworkManagerResponse(new GetTransitGatewayRegistrationsResponsePrivate(this), parent) +{ + setRequest(new GetTransitGatewayRegistrationsRequest(request)); + setReply(reply); +} + +/*! + * \reimp + */ +const GetTransitGatewayRegistrationsRequest * GetTransitGatewayRegistrationsResponse::request() const +{ + Q_D(const GetTransitGatewayRegistrationsResponse); + return static_cast<const GetTransitGatewayRegistrationsRequest *>(d->request); +} + +/*! + * \reimp + * Parses a successful NetworkManager GetTransitGatewayRegistrations \a response. + */ +void GetTransitGatewayRegistrationsResponse::parseSuccess(QIODevice &response) +{ + //Q_D(GetTransitGatewayRegistrationsResponse); + QXmlStreamReader xml(&response); + /// @todo +} + +/*! + * \class QtAws::NetworkManager::GetTransitGatewayRegistrationsResponsePrivate + * \brief The GetTransitGatewayRegistrationsResponsePrivate class provides private implementation for GetTransitGatewayRegistrationsResponse. + * \internal + * + * \inmodule QtAwsNetworkManager + */ + +/*! + * Constructs a GetTransitGatewayRegistrationsResponsePrivate object with public implementation \a q. + */ +GetTransitGatewayRegistrationsResponsePrivate::GetTransitGatewayRegistrationsResponsePrivate( + GetTransitGatewayRegistrationsResponse * const q) : NetworkManagerResponsePrivate(q) +{ + +} + +/*! + * Parses a NetworkManager GetTransitGatewayRegistrations response element from \a xml. + */ +void GetTransitGatewayRegistrationsResponsePrivate::parseGetTransitGatewayRegistrationsResponse(QXmlStreamReader &xml) +{ + Q_ASSERT(xml.name() == QLatin1String("GetTransitGatewayRegistrationsResponse")); + Q_UNUSED(xml) ///< @todo +} + +} // namespace NetworkManager +} // namespace QtAws diff --git a/pool/shard007/C++/0092839_channel_layer.cpp b/pool/shard007/C++/0092839_channel_layer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..03b1729d60f5ce72a1b1db38576af358c6146e7e --- /dev/null +++ b/pool/shard007/C++/0092839_channel_layer.cpp @@ -0,0 +1,155 @@ +/* +// Copyright (c) 2018 Intel Corporation +// +// 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 "channel_layer.hpp" + +#include "channel_mgmt.hpp" +#include "cipher_mgmt.hpp" + +#include <phosphor-logging/log.hpp> + +namespace ipmi +{ + +bool doesDeviceExist(const uint8_t chNum) +{ + // TODO: This is not the reliable way to find the device + // associated with ethernet interface as the channel number to + // eth association is not done. Need to revisit later + struct stat fileStat = {0}; + std::string devName("/sys/class/net/" + getChannelName(chNum)); + + if (stat(devName.data(), &fileStat) != 0) + { + phosphor::logging::log<phosphor::logging::level::DEBUG>( + "Ethernet device not found"); + return false; + } + + return true; +} + +bool isValidPrivLimit(const uint8_t privLimit) +{ + // Callback privilege is deprecated in OpenBMC + // At present, "OEM Privilege" is not used in OpenBMC + return ((privLimit > PRIVILEGE_CALLBACK) && (privLimit < PRIVILEGE_OEM)); +} + +bool isValidAccessMode(const uint8_t accessMode) +{ + return ( + (accessMode >= static_cast<uint8_t>(EChannelAccessMode::disabled)) && + (accessMode <= static_cast<uint8_t>(EChannelAccessMode::shared))); +} + +bool isValidChannel(const uint8_t chNum) +{ + return getChannelConfigObject().isValidChannel(chNum); +} + +bool isValidAuthType(const uint8_t chNum, const EAuthType& authType) +{ + return getChannelConfigObject().isValidAuthType(chNum, authType); +} + +EChannelSessSupported getChannelSessionSupport(const uint8_t chNum) +{ + return getChannelConfigObject().getChannelSessionSupport(chNum); +} + +int getChannelActiveSessions(const uint8_t chNum) +{ + return getChannelConfigObject().getChannelActiveSessions(chNum); +} + +size_t getChannelMaxTransferSize(uint8_t chNum) +{ + return getChannelConfigObject().getChannelMaxTransferSize(chNum); +} + +Cc ipmiChannelInit() +{ + getChannelConfigObject(); + getCipherConfigObject(csPrivFileName, csPrivDefaultFileName); + return ccSuccess; +} + +Cc getChannelInfo(const uint8_t chNum, ChannelInfo& chInfo) +{ + return getChannelConfigObject().getChannelInfo(chNum, chInfo); +} + +Cc getChannelAccessData(const uint8_t chNum, ChannelAccess& chAccessData) +{ + return getChannelConfigObject().getChannelAccessData(chNum, chAccessData); +} + +Cc setChannelAccessData(const uint8_t chNum, const ChannelAccess& chAccessData, + const uint8_t setFlag) +{ + return getChannelConfigObject().setChannelAccessData(chNum, chAccessData, + setFlag); +} + +Cc getChannelAccessPersistData(const uint8_t chNum, ChannelAccess& chAccessData) +{ + return getChannelConfigObject().getChannelAccessPersistData(chNum, + chAccessData); +} + +Cc setChannelAccessPersistData(const uint8_t chNum, + const ChannelAccess& chAccessData, + const uint8_t setFlag) +{ + return getChannelConfigObject().setChannelAccessPersistData( + chNum, chAccessData, setFlag); +} + +Cc getChannelAuthTypeSupported(const uint8_t chNum, uint8_t& authTypeSupported) +{ + return getChannelConfigObject().getChannelAuthTypeSupported( + chNum, authTypeSupported); +} + +Cc getChannelEnabledAuthType(const uint8_t chNum, const uint8_t priv, + EAuthType& authType) +{ + return getChannelConfigObject().getChannelEnabledAuthType(chNum, priv, + authType); +} + +std::string getChannelName(const uint8_t chNum) +{ + return getChannelConfigObject().getChannelName(chNum); +} + +uint8_t getChannelByName(const std::string& chName) +{ + return getChannelConfigObject().getChannelByName(chName); +} + +bool isValidPayloadType(const PayloadType payloadType) +{ + return ( + payloadType == PayloadType::IPMI || payloadType == PayloadType::SOL || + payloadType == PayloadType::OPEN_SESSION_REQUEST || + payloadType == PayloadType::OPEN_SESSION_RESPONSE || + payloadType == PayloadType::RAKP1 || + payloadType == PayloadType::RAKP2 || + payloadType == PayloadType::RAKP3 || payloadType == PayloadType::RAKP4); +} +} // namespace ipmi diff --git a/pool/shard007/C++/0092840_automation.cpp b/pool/shard007/C++/0092840_automation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ddcffbfec2286d4dc0d03d6d086f7702426d7daf --- /dev/null +++ b/pool/shard007/C++/0092840_automation.cpp @@ -0,0 +1,141 @@ +#include "crosstable.h" +#include "automation.h" + +#include <QTime> +#include <QString> +#include <QDebug> +#include <QFileInfo> + +#define FIRST_DIAG_VAR 5000 + + +#include "hmi_plc.h" +extern HmiPlcBlock plcBlock; + +u_int32_t variablesBuffer[FIRST_DIAG_VAR - 1]; // The raw type of CrossTable Vars is u_int32_t + // The buffer size is big enough to store all Users Cross Table Variables + + +/* put here the initalization */ +void setup(void) +{ + while (PLC_EngineStatus < 2) { + fprintf(stderr, "*"); + sleep(1); + } + QString fileDump = QString("/local/root/dumpVars.bin"); + if (QFile::exists(fileDump)) { + if (restoreVariables(ID_HMI_1_Start_H_1, 40, fileDump)) { + qDebug("Vars Restored from: [%s]", fileDump.toLatin1().data()); + } + else { + qCritical("Error Restoring Vars from: [%s]", fileDump.toLatin1().data()); + } + } + else { + qDebug("Dump File [%s] NOT found", fileDump.toLatin1().data()); + } +} + +/* put here the operation made every 100ms */ +void loop(void) +{ + +} + +bool dumpVariables(int nStart, int nVariables, QString &szFile2Dump) +// nStart: Starting Cross Table Index of Variable to be dumped +// nVariables: Number of Items to be dumped +// szFile2Dump: File to be dumped +{ + bool fRes = false; + QTime dumpTime; + + dumpTime.restart(); + if (nStart < 1 || nStart > FIRST_DIAG_VAR -1 || FIRST_DIAG_VAR < (nStart + nVariables)) { + qCritical("Variables Indexes out of Range: nStart [%d] must be from [1] to [%d] and nStart + nVariables [%d] should be less than [%d]", + nStart, FIRST_DIAG_VAR -1, nVariables, FIRST_DIAG_VAR); + } + else { + // Clear Buffer + memset (&variablesBuffer[0], 0x00, sizeof(variablesBuffer)); + + pthread_mutex_lock(&datasync_recv_mutex); + { + // Protected copy from Cross Table storage area + memcpy(&variablesBuffer[0], &(plcBlock.values[nStart]), nVariables * sizeof(u_int32_t)); + } + pthread_mutex_unlock(&datasync_recv_mutex); + + // Write to Binary file + FILE *out; + out = fopen(szFile2Dump.toLatin1().data(), "wb"); + if (out != NULL) + { + fwrite(&variablesBuffer[0], sizeof(u_int32_t), nVariables, out); + fclose(out); + fRes = true; + } + } + // Log Dump result + if (fRes) { + qDebug("Dumped [%d] Variables from: [%d] Elapsed: [%d]ms to File: [%s]", nVariables, nStart, dumpTime.elapsed(), szFile2Dump.toLatin1().data()); + } + else { + qCritical("Error Dumping Variables to File: [%s]", szFile2Dump.toLatin1().data()); + } + return fRes; +} + +bool restoreVariables(int nStart, int nVariables, QString &szFile2Restore) +// nStart: Starting Cross Table Index of Variable to be restored +// nVariables: Number of Items to be restored +// szFile2Restore: File to be restored +{ + bool fRes = false; + QTime restoreTime; + + restoreTime.restart(); + if (nStart < 1 || nStart > FIRST_DIAG_VAR -1 || FIRST_DIAG_VAR < (nStart + nVariables)) { + qCritical("Variables Indexes out of Range: nStart [%d] must be from [1] to [%d] and nStart + nVariables [%d] should be less than [%d]", + nStart, FIRST_DIAG_VAR -1, nVariables, FIRST_DIAG_VAR); + } + else { + // Check for existence and minimum size of binary File + QFileInfo fileInfo(szFile2Restore); + if (fileInfo.exists() && fileInfo.size() >= nVariables * sizeof(u_int32_t)) { + FILE *out; + out = fopen(szFile2Restore.toLatin1().data(), "rb"); + if (out != NULL) + { + // Clear Buffer + memset (&variablesBuffer[0], 0x00, sizeof(variablesBuffer)); + // Read requested elements + int nItems = fread(&variablesBuffer[0], sizeof(u_int32_t), nVariables, out); + fclose(out); + if (nItems == nVariables) { + // Write Buffer Items to Cross Table Variables + beginWrite(); + for (int nItem = 0; nItem < nItems; nItem++) { + addWrite(nStart + nItem, &variablesBuffer[nItem]); + } + endWrite(); + fRes = true; + } + } + } + else { + qCritical("Variables File: [%s] NOT Found", szFile2Restore.toLatin1().data()); + } + } + // Log Dump result + if (fRes) { + qDebug("Restored [%d] Variables starting from: [%d]. Elapsed: [%d]ms from File: [%s]", nVariables, nStart, restoreTime.elapsed(), szFile2Restore.toLatin1().data()); + } + else { + qCritical("Error Restoring Variables from File: [%s]", szFile2Restore.toLatin1().data()); + } + return fRes; + +} + diff --git a/pool/shard007/C++/0092846_tf_jitrt_fuse_fill_into_tiled_reduction.cc b/pool/shard007/C++/0092846_tf_jitrt_fuse_fill_into_tiled_reduction.cc new file mode 100644 index 0000000000000000000000000000000000000000..fc6bbf01fc3563a19f3b4c20644a81a8642b5480 --- /dev/null +++ b/pool/shard007/C++/0092846_tf_jitrt_fuse_fill_into_tiled_reduction.cc @@ -0,0 +1,338 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include <memory> +#include <utility> + +#include "mlir-hlo/Dialect/gml_st/transforms/transforms.h" +#include "mlir/Dialect/Linalg/IR/Linalg.h" +#include "mlir/Dialect/Linalg/Passes.h" +#include "mlir/Dialect/Tensor/IR/Tensor.h" +#include "mlir/IR/BlockAndValueMapping.h" +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" +#include "tensorflow/compiler/mlir/tensorflow/ir/tf_dialect.h" +#include "tensorflow/compiler/mlir/tfrt/jit/transforms/tf_jitrt_passes.h" + +namespace tensorflow { +namespace { + +#define GEN_PASS_CLASSES +#include "tensorflow/compiler/mlir/tfrt/jit/transforms/tf_jitrt_passes.h.inc" + +using llvm::makeArrayRef; +using mlir::BlockAndValueMapping; +using mlir::BlockArgument; +using mlir::dyn_cast; +using mlir::failure; +using mlir::Location; +using mlir::LogicalResult; +using mlir::MLIRContext; +using mlir::OpBuilder; +using mlir::Operation; +using mlir::OpFoldResult; +using mlir::OpRewritePattern; +using mlir::PatternRewriter; +using mlir::SmallVector; +using mlir::success; +using mlir::Value; +using mlir::ValueRange; +using mlir::gml_st::LoopOp; +using mlir::linalg::FillOp; +using mlir::linalg::GenericOp; +using mlir::linalg::InitTensorOp; +using mlir::linalg::LinalgOp; +using mlir::linalg::YieldOp; +using mlir::tensor::ExtractSliceOp; +using mlir::tensor::InsertSliceOp; + +SmallVector<OpFoldResult> GetParallelDimStep(LoopOp tiled_loop) { + assert(tiled_loop.getNumLoops() == 2 && "Expected a 2D loop"); + Value step = tiled_loop.isParallelDimension(0) ? tiled_loop.step().front() + : tiled_loop.step().back(); + if (auto constant = step.getDefiningOp<mlir::arith::ConstantOp>()) { + return {constant.getValue()}; + } + return {step}; +} + +// Fuses `linalg.fill` into a loop with a tiled reduction. +// Currently, only 2D case is supported. Fusion into a tiled 1D reduction is +// also possible. +struct FuseFillIntoTiledReductionPattern : public OpRewritePattern<GenericOp> { + explicit FuseFillIntoTiledReductionPattern(MLIRContext *context, + mlir::PatternBenefit benefit = 1) + : OpRewritePattern<GenericOp>(context, benefit) {} + + LogicalResult matchAndRewrite(GenericOp linalg_op, + PatternRewriter &rewriter) const override { + if (linalg_op.getNumOutputs() != 1) return failure(); + if (linalg_op.getNumLoops() != 2) return failure(); + + // Get immediate parent. + auto tiled_loop_op = + dyn_cast<LoopOp>(linalg_op->getParentRegion()->getParentOp()); + if (!tiled_loop_op) return failure(); + if (tiled_loop_op.getNumLoops() != 2) return failure(); + + return RewriteTiledReduction(rewriter, tiled_loop_op, linalg_op); + } + + private: + // Add a new output argument to the `tiled_loop`. It will be produced by + // `init_tensor` op with the same shape of the tiled output argument. + // + // Rewrite + // + // %init = linalg.init_tensor + // %fill = linalg.fill(%cst, %init) + // linalg.tiled_loop outs(%fill) + // + // into + // + // %init = linalg.init_tensor + //** %init_tile = linalg.init_tensor [%stride] + // %fill = linalg.fill(%cst, %init) + //** linalg.tiled_loop outs(%fill, %init_tile) + BlockArgument CloneAndAppendInitTensorToTiledLoop(PatternRewriter &rewriter, + FillOp fill, + LoopOp tiled_loop) const { + OpBuilder::InsertionGuard guard(rewriter); + rewriter.setInsertionPoint(fill); + + auto init = fill.output().getDefiningOp<InitTensorOp>(); + + Value init_clone = rewriter.create<InitTensorOp>( + init.getLoc(), GetParallelDimStep(tiled_loop), + init.getType().cast<mlir::RankedTensorType>().getElementType()); + mlir::OpOperand *init_clone_output_operand; + rewriter.updateRootInPlace(tiled_loop, [&]() { + init_clone_output_operand = + &tiled_loop.appendOutputOperand(rewriter, init_clone); + }); + return tiled_loop.getTiedBlockArgument(*init_clone_output_operand); + } + + // Fuse `fill` operation into the `tiled_loop`, rewire the `linalg.generic` to + // use it as the output for the reduced tile. Also create an additional + // `insert_slice` that updates the new output. + // + // Rewrite + // + // %init = linalg.init_tensor + // %init_tile = linalg.init_tensor [%stride] + // %fill = linalg.fill(%cst, %init) + // linalg.tiled_loop outs(%fill, %init_tile) { + // %extract_output_slice = tensor.extract_slice %fill + // %reduce = linalg.generic outs (%extract_output_slice) + // %insert_output_slice = tensor.insert_slice %reduce into %fill + // linalg.yield %insert_output_slice + // } + // + // into + // + // %init = linalg.init_tensor + // %init_tile = linalg.init_tensor + // %fill = linalg.fill(%cst, %init) + // linalg.tiled_loop outs(%fill, %init_tile) { + // %extract_output_slice = tensor.extract_slice %fill + // + //** %slice_of_output_tile = tensor.extract_slice %init + //** %fill_of_output_tile = linalg.fill(%cst, %slice_of_output_tile) + //** %reduce = linalg.generic outs (%fill_of_output_tile) + //** %update_output_tile = tensor.insert_slice %reduce into %init_tile + // + // %insert_output_slice = tensor.insert_slice %reduce into %fill + // linalg.yield %insert_output_slice, %update_output_tile + // } + void FuseFill(PatternRewriter &rewriter, LinalgOp tiled_op, FillOp fill, + BlockArgument loop_output_bb_arg, + BlockArgument output_tile_bb_arg, + ExtractSliceOp extract_output_slice, + InsertSliceOp insert_output_slice) const { + Location loc = tiled_op.getLoc(); + + OpBuilder::InsertionGuard g(rewriter); + rewriter.setInsertionPoint(tiled_op); + + SmallVector<OpFoldResult> offset{rewriter.getIndexAttr(0)}; + Value slice_of_output_tile = rewriter.create<ExtractSliceOp>( + loc, output_tile_bb_arg, offset, extract_output_slice.getMixedSizes(), + extract_output_slice.getMixedStrides()); + + auto fused_fill = + rewriter.create<FillOp>(loc, fill.value(), slice_of_output_tile); + rewriter.updateRootInPlace(tiled_op, [&]() { + tiled_op.getOutputOperand(0)->set(fused_fill.result()); + }); + + rewriter.setInsertionPointAfter(tiled_op); + Value cloned_insert = rewriter.create<mlir::tensor::InsertSliceOp>( + loc, fused_fill.getResult(0), output_tile_bb_arg, offset, + extract_output_slice.getMixedSizes(), + extract_output_slice.getMixedStrides()); + + auto yield = tiled_op.getOperation()->getBlock()->getTerminator(); + rewriter.updateRootInPlace( + yield, [&]() { yield->insertOperands(1, cloned_insert); }); + } + + // Add an operation that combines the partial result with the output. + // + // Rewrite + // + // %init = linalg.init_tensor + // %init_tile = linalg.init_tensor + // %fill = linalg.fill(%cst, %init) + // linalg.tiled_loop outs(%fill, %init_tile) { + // %extract_output_slice = tensor.extract_slice %fill + // + // %slice_of_output_tile = tensor.extract_slice %init + // %fill_of_output_tile = linalg.fill(%cst, %slice_of_output_tile) + // %reduce = linalg.generic outs (%fill_of_output_tile) + // %update_output_tile = tensor.insert_slice %reduce into %init_tile + // + // %insert_output_slice = tensor.insert_slice %reduce into %fill + // linalg.yield %insert_output_slice, %update_output_tile + // } + // + // into + // + // %init = linalg.init_tensor + // %init_tile = linalg.init_tensor + // %fill = linalg.fill(%cst, %init) + // linalg.tiled_loop outs(%fill, %init_tile) { + // %extract_output_slice = tensor.extract_slice %fill + // + // %slice_of_output_tile = tensor.extract_slice %init + // %fill_of_output_tile = linalg.fill(%cst, %slice_of_output_tile) + // %reduce = linalg.generic outs (%fill_of_output_tile) + // %update_output_tile = tensor.insert_slice %reduce into %init_tile + // + //** %combine = linalg.generic ins (%reduce) outs (%extract_output_slice) + //** %insert_output_slice = tensor.insert_slice %combine into %fill + // + // linalg.yield %insert_output_slice, %update_output_tile + // } + LogicalResult CombineReducedTileWithOutput( + PatternRewriter &rewriter, LinalgOp tiled_op, Value partial_result, + ExtractSliceOp extract_output_slice, + InsertSliceOp insert_output_slice) const { + rewriter.setInsertionPointAfter(tiled_op); + auto num_parallel_loops = tiled_op.getNumParallelLoops(); + SmallVector<mlir::StringRef, 3> parallel_iter_types( + num_parallel_loops, mlir::getParallelIteratorTypeName()); + auto id_map = rewriter.getMultiDimIdentityMap(num_parallel_loops); + + auto combiner_or = DetectCombiner(tiled_op); + if (failed(combiner_or)) return failure(); + Operation *combiner = combiner_or.getValue(); + + auto accumulator = rewriter.create<GenericOp>( + tiled_op.getLoc(), partial_result.getType(), + makeArrayRef(partial_result), + makeArrayRef(extract_output_slice.result()), + makeArrayRef({id_map, id_map}), parallel_iter_types, + [&](OpBuilder &b, Location nested_loc, ValueRange args) { + BlockAndValueMapping bvm; + bvm.map(combiner->getOperands(), args); + Value result_val = b.clone(*combiner, bvm)->getResult(0); + b.create<YieldOp>(nested_loc, result_val); + }); + + rewriter.updateRootInPlace(insert_output_slice, [&]() { + insert_output_slice.sourceMutable().assign(accumulator.getResult(0)); + }); + return success(); + } + + // Unfortunaly, there is no way to modify the results of the loop inplace. So + // we have to replace it with a clone. + LoopOp CreateLoopWithUpdatedResults(PatternRewriter &rewriter, + LoopOp tiled_loop) const { + auto loc = tiled_loop.getLoc(); + rewriter.setInsertionPoint(tiled_loop); + auto new_loop = rewriter.create<LoopOp>( + loc, mlir::TypeRange(tiled_loop.outputs()), tiled_loop.getOperands(), + tiled_loop->getAttrs()); + rewriter.inlineRegionBefore(tiled_loop.region(), new_loop.region(), + new_loop.region().begin()); + + rewriter.replaceOp(tiled_loop, new_loop.getResult(0)); + return new_loop; + } + + // Fuses FillOp producer of the output argument of the LoopOp and inserts + // an operation that accumulates the partial result, i.e. reduced tile, and + // the current value of the output tile. + LogicalResult RewriteTiledReduction(PatternRewriter &rewriter, + LoopOp tiled_loop, + LinalgOp tiled_op) const { + OpBuilder::InsertionGuard guard(rewriter); + rewriter.setInsertionPointAfter(tiled_op); + + // Find tiled loop output operand and the corresponding block argument. + mlir::OpOperand *loop_output_operand = + tiled_loop.findOutputOperand(tiled_loop.outputs().front()); + BlockArgument loop_output_bb_arg = + tiled_loop.getTiedBlockArgument(*loop_output_operand); + + // Find `linalg.fill` producer of the output. + auto fill = loop_output_operand->get().getDefiningOp<FillOp>(); + if (!fill) return failure(); + + // Find extract_slice/insert_slice pair used to RMW output. + auto extract_output_slice = + tiled_op.getOutputOperand(0)->get().getDefiningOp<ExtractSliceOp>(); + if (!extract_output_slice) return failure(); + + Value tiled_op_result = tiled_op->getResult(0); + auto insert_output_slice = + dyn_cast<InsertSliceOp>(*tiled_op_result.getUsers().begin()); + if (!insert_output_slice) return failure(); + + // Fuse the output. + BlockArgument output_tile_bb_arg = + CloneAndAppendInitTensorToTiledLoop(rewriter, fill, tiled_loop); + FuseFill(rewriter, tiled_op, fill, loop_output_bb_arg, output_tile_bb_arg, + extract_output_slice, insert_output_slice); + // We have already modified the loop above, so we need to update the + // results. + CreateLoopWithUpdatedResults(rewriter, tiled_loop); + return CombineReducedTileWithOutput(rewriter, tiled_op, tiled_op_result, + extract_output_slice, + insert_output_slice); + } +}; + +struct FuseFillIntoTiledReductionPass + : public FuseFillIntoTiledReductionBase<FuseFillIntoTiledReductionPass> { + void runOnOperation() override { + auto func = getOperation(); + auto context = func.getContext(); + + mlir::RewritePatternSet patterns(context); + patterns.add<FuseFillIntoTiledReductionPattern>(context); + (void)mlir::applyPatternsAndFoldGreedily(func, std::move(patterns)); + } +}; + +} // namespace + +std::unique_ptr<mlir::OperationPass<mlir::FuncOp>> +CreateFuseFillIntoTiledReductionPass() { + return std::make_unique<FuseFillIntoTiledReductionPass>(); +} + +} // namespace tensorflow diff --git a/pool/shard007/C++/0092857_class_object.cc b/pool/shard007/C++/0092857_class_object.cc new file mode 100644 index 0000000000000000000000000000000000000000..eb38ef539838bb8bde96f776db645cf14850b4b8 --- /dev/null +++ b/pool/shard007/C++/0092857_class_object.cc @@ -0,0 +1,66 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +#include <algorithm> +#include "core/data_render/class.h" +#include "core/data_render/class_object.h" +#include "core/data_render/exec_state.h" +#include "core/data_render/common_error.h" +#include "core/data_render/table.h" +#include "core/data_render/class_array.h" +#include "base/LogDefines.h" + +namespace weex { +namespace core { +namespace data_render { + +static Value keys(ExecState *exec_state); + +ClassDescriptor *NewClassOject() { + ClassDescriptor *object_desc = new ClassDescriptor(nullptr); + AddClassStaticCFunc(object_desc, "keys", keys); + return object_desc; +} + +static Value keys(ExecState *exec_state) { + Value ret = exec_state->class_factory()->CreateArray(); + do { + size_t length = exec_state->GetArgumentCount(); + if (length < 1) { + break; + } + Value *value = exec_state->GetArgument(0); + if (!IsArray(value) && !IsTable(value)) { + throw VMExecError("Object.keys caller isn't a Array or Table"); + } + if (IsTable(value)) { + std::vector<std::string> keys = GetTableKeys(ValueTo<Table>(value)); + Array *array = ValueTo<Array>(&ret); + for (int i = 0; i < keys.size(); i++) { + SetArray(array, i, exec_state->string_table()->StringFromUTF8(keys[i])); + } + } + + } while (0); + + return ret; +} + +} // namespace data_render +} // namespace core +} // namespace weex diff --git a/pool/shard007/C++/0092860_EmailConfigurationType.cpp b/pool/shard007/C++/0092860_EmailConfigurationType.cpp new file mode 100644 index 0000000000000000000000000000000000000000..38137b1e0e82fda1f73d6d8ce80768e288d2403d --- /dev/null +++ b/pool/shard007/C++/0092860_EmailConfigurationType.cpp @@ -0,0 +1,120 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include <aws/cognito-idp/model/EmailConfigurationType.h> +#include <aws/core/utils/json/JsonSerializer.h> + +#include <utility> + +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +namespace Aws +{ +namespace CognitoIdentityProvider +{ +namespace Model +{ + +EmailConfigurationType::EmailConfigurationType() : + m_sourceArnHasBeenSet(false), + m_replyToEmailAddressHasBeenSet(false), + m_emailSendingAccount(EmailSendingAccountType::NOT_SET), + m_emailSendingAccountHasBeenSet(false), + m_fromHasBeenSet(false), + m_configurationSetHasBeenSet(false) +{ +} + +EmailConfigurationType::EmailConfigurationType(JsonView jsonValue) : + m_sourceArnHasBeenSet(false), + m_replyToEmailAddressHasBeenSet(false), + m_emailSendingAccount(EmailSendingAccountType::NOT_SET), + m_emailSendingAccountHasBeenSet(false), + m_fromHasBeenSet(false), + m_configurationSetHasBeenSet(false) +{ + *this = jsonValue; +} + +EmailConfigurationType& EmailConfigurationType::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("SourceArn")) + { + m_sourceArn = jsonValue.GetString("SourceArn"); + + m_sourceArnHasBeenSet = true; + } + + if(jsonValue.ValueExists("ReplyToEmailAddress")) + { + m_replyToEmailAddress = jsonValue.GetString("ReplyToEmailAddress"); + + m_replyToEmailAddressHasBeenSet = true; + } + + if(jsonValue.ValueExists("EmailSendingAccount")) + { + m_emailSendingAccount = EmailSendingAccountTypeMapper::GetEmailSendingAccountTypeForName(jsonValue.GetString("EmailSendingAccount")); + + m_emailSendingAccountHasBeenSet = true; + } + + if(jsonValue.ValueExists("From")) + { + m_from = jsonValue.GetString("From"); + + m_fromHasBeenSet = true; + } + + if(jsonValue.ValueExists("ConfigurationSet")) + { + m_configurationSet = jsonValue.GetString("ConfigurationSet"); + + m_configurationSetHasBeenSet = true; + } + + return *this; +} + +JsonValue EmailConfigurationType::Jsonize() const +{ + JsonValue payload; + + if(m_sourceArnHasBeenSet) + { + payload.WithString("SourceArn", m_sourceArn); + + } + + if(m_replyToEmailAddressHasBeenSet) + { + payload.WithString("ReplyToEmailAddress", m_replyToEmailAddress); + + } + + if(m_emailSendingAccountHasBeenSet) + { + payload.WithString("EmailSendingAccount", EmailSendingAccountTypeMapper::GetNameForEmailSendingAccountType(m_emailSendingAccount)); + } + + if(m_fromHasBeenSet) + { + payload.WithString("From", m_from); + + } + + if(m_configurationSetHasBeenSet) + { + payload.WithString("ConfigurationSet", m_configurationSet); + + } + + return payload; +} + +} // namespace Model +} // namespace CognitoIdentityProvider +} // namespace Aws diff --git a/pool/shard007/C++/0092865_InsetMathSubstack.cpp b/pool/shard007/C++/0092865_InsetMathSubstack.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56d253e3b27e2b13e6c6ad25b8368babed0a2b4e --- /dev/null +++ b/pool/shard007/C++/0092865_InsetMathSubstack.cpp @@ -0,0 +1,170 @@ +/** + * \file InsetMathSubstack.cpp + * This file is part of LyX, the document processor. + * Licence details can be found in the file COPYING. + * + * \author André Pönitz + * + * Full author contact details are available in file CREDITS. + */ + +#include <config.h> + +#include "InsetMathSubstack.h" + +#include "LaTeXFeatures.h" +#include "MathData.h" +#include "MathStream.h" + +#include "FuncRequest.h" +#include "FuncStatus.h" +#include "support/gettext.h" + +#include "support/lstrings.h" + +#include <ostream> + +using namespace std; + +namespace lyx { + +using support::bformat; + + +InsetMathSubstack::InsetMathSubstack(Buffer * buf) + : InsetMathGrid(buf, 1, 1) +{} + + +Inset * InsetMathSubstack::clone() const +{ + return new InsetMathSubstack(*this); +} + + +void InsetMathSubstack::metrics(MetricsInfo & mi, Dimension & dim) const +{ + if (mi.base.style == LM_ST_DISPLAY) { + StyleChanger dummy(mi.base, LM_ST_TEXT); + InsetMathGrid::metrics(mi, dim); + } else { + InsetMathGrid::metrics(mi, dim); + } +} + + +void InsetMathSubstack::draw(PainterInfo & pi, int x, int y) const +{ + InsetMathGrid::draw(pi, x + 1, y); +} + + +bool InsetMathSubstack::getStatus(Cursor & cur, FuncRequest const & cmd, + FuncStatus & flag) const +{ + switch (cmd.action()) { + case LFUN_INSET_MODIFY: { + istringstream is(to_utf8(cmd.argument())); + string s; + is >> s; + if (s != "tabular") + break; + is >> s; + string const name = "substack"; + if (s == "add-vline-left" || s == "add-vline-right") { + flag.message(bformat( + from_utf8(N_("Can't add vertical grid lines in '%1$s'")), + from_utf8(name))); + flag.setEnabled(false); + return true; + } + // in contrary to \subaray, the columns in \substack + // are always centered and this cannot be changed + if (s == "align-left" || s == "align-right") { + flag.message(bformat( + from_utf8(N_("Can't change horizontal alignment in '%1$s'")), + from_utf8(name))); + flag.setEnabled(false); + return true; + } + break; + } + + default: + break; + } + return InsetMathGrid::getStatus(cur, cmd, flag); +} + + +void InsetMathSubstack::infoize(odocstream & os) const +{ + os << "Substack "; +} + + +void InsetMathSubstack::write(WriteStream & os) const +{ + MathEnsurer ensurer(os); + os << "\\substack{"; + InsetMathGrid::write(os); + os << "}\n"; +} + + +void InsetMathSubstack::normalize(NormalStream & os) const +{ + os << "[substack "; + InsetMathGrid::normalize(os); + os << ']'; +} + + +void InsetMathSubstack::maple(MapleStream & os) const +{ + os << "substack("; + InsetMathGrid::maple(os); + os << ')'; +} + + +void InsetMathSubstack::mathmlize(MathStream & os) const +{ + int movers = 0; + row_type const numrows = nrows(); + for (row_type row = 0; row < nrows(); ++row) { + if (row < numrows - 1) { + movers ++; + os << MTag("munder"); + } + os << MTag("mrow") << cell(index(row, 0)) << ETag("mrow"); + } + for (int i = 1; i <= movers; ++i) + os << ETag("munder"); +} + + +void InsetMathSubstack::htmlize(HtmlStream & os) const +{ + os << MTag("span", "class='substack'"); + for (row_type row = 0; row < nrows(); ++row) + os << MTag("span") << cell(index(row, 0)) << ETag("span"); + os << ETag("span"); +} + + +void InsetMathSubstack::validate(LaTeXFeatures & features) const +{ + if (features.runparams().isLaTeX()) + features.require("amsmath"); + else if (features.runparams().math_flavor == OutputParams::MathAsHTML) + features.addPreambleSnippet("<style type=\"text/css\">\n" + "span.substack{display: inline-block; vertical-align: middle; text-align:center; font-size: 75%;}\n" + "span.substack span{display: block;}\n" + "</style>"); + + InsetMathGrid::validate(features); +} + + +} // namespace lyx diff --git a/pool/shard007/C++/0092869_lua_packetmodifications.cpp b/pool/shard007/C++/0092869_lua_packetmodifications.cpp new file mode 100644 index 0000000000000000000000000000000000000000..65c97189b6e314036b0f84aa31d9ad4484762cd3 --- /dev/null +++ b/pool/shard007/C++/0092869_lua_packetmodifications.cpp @@ -0,0 +1,108 @@ +/** + * Tracebox -- A middlebox detection tool + * + * Copyright 2013-2015 by its authors. + * Some rights reserved. See LICENSE, AUTHORS. + */ + +#include "lua_packetmodifications.h" +#include "lua_packet.hpp" +#include "lua_crafter.hpp" + +using namespace Crafter; + +/*** + * A set of modifications between packets + * @classmod PacketModifications + */ +/*** + * Build a new PacketModifications + * @function new + * @tparam Packet original the reference packet to compare to + * @tparam Packet receivd the new packet that has been modified + * @treturn PacketModifications mod the set of modifications + */ +int l_packetmodifications_ref::l_PacketModifications(lua_State *l) +{ + Packet *original = l_packet_ref::get(l, 1); + Packet *received = new Packet(*l_packet_ref::get(l, 2)); + PacketModifications *mod = PacketModifications::ComputeModifications( + original, &received); + new l_packetmodifications_ref(mod, l); + return 1; +} + +int l_packetmodifications_ref::l_PacketModifications_print(lua_State *l) +{ + std::ostringstream stream; + PacketModifications *o = l_packetmodifications_ref::get(l, 1); + o->Print(stream); + l_data_type<std::string>(stream.str()).push(l); + return 1; +} + +int l_packetmodifications_ref::l_get_original(lua_State *l) +{ + l_ref<PacketModifications> *r = l_packetmodifications_ref::get_instance(l, 1); + new l_packet_ref(r, r->val->orig, l); + return 1; +} + +int l_packetmodifications_ref::l_get_received(lua_State *l) +{ + l_ref<PacketModifications> *r = l_packetmodifications_ref::get_instance(l, 1); + new l_packet_ref(r, r->val->modif, l); + return 1; +} + +static int l_partial(lua_State *l) +{ + PacketModifications *p = l_packetmodifications_ref::get(l, 1); + l_data_type<int>(p->partial).push(l); + return 1; +} + +void l_packetmodifications_ref::register_members(lua_State *l) +{ + l_ref<PacketModifications>::register_members(l); + meta_bind_func(l, "new", l_PacketModifications); + /*** + * Return the textual representation of the object. + * @function print + * @see tostring + * @treturn string + */ + meta_bind_func(l, "__tostring", l_PacketModifications_print); + /*** + * Same than @{print} + * @function __tostring + * @see print + */ + meta_bind_func(l, "print", l_PacketModifications_print); + /*** + * Get the original packet as reference when computing these modifications + * @function original + * @treturn Packet original + */ + meta_bind_func(l, "original", l_get_original); + /*** + * Get the reveived packet differing from the original packet + * @function received + * @treturn Packet received + */ + meta_bind_func(l, "received", l_get_received); + /*** + * Check if the modifications have been computed based on a partial + * header or not + * @function partial + * @treturn num partial 0 if not from a partial header + */ + meta_bind_func(l, "partial", l_partial); +} + +void l_packetmodifications_ref::debug(std::ostream& out) +{ + l_ref<PacketModifications>::debug(out); + out << (void*) this << " "; + this->val->Print(out, true); +} diff --git a/pool/shard007/C++/0092871_iterators.pass.cpp b/pool/shard007/C++/0092871_iterators.pass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4ac126a596d8a168c4ad7b581810446415b9a91a --- /dev/null +++ b/pool/shard007/C++/0092871_iterators.pass.cpp @@ -0,0 +1,125 @@ +//===----------------------------------------------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is dual licensed under the MIT and the University of Illinois Open +// Source Licenses. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +// <unordered_map> + +// template <class Key, class T, class Hash = hash<Key>, class Pred = equal_to<Key>, +// class Alloc = allocator<pair<const Key, T>>> +// class unordered_map + +// iterator begin() {return __table_.begin();} +// iterator end() {return __table_.end();} +// const_iterator begin() const {return __table_.begin();} +// const_iterator end() const {return __table_.end();} +// const_iterator cbegin() const {return __table_.begin();} +// const_iterator cend() const {return __table_.end();} + +#include <unordered_map> +#include <string> +#include <cassert> + +#include "min_allocator.h" + +int main() +{ + { + typedef std::unordered_map<int, std::string> C; + typedef std::pair<int, std::string> P; + P a[] = + { + P(1, "one"), + P(2, "two"), + P(3, "three"), + P(4, "four"), + P(1, "four"), + P(2, "four"), + }; + C c(a, a + sizeof(a)/sizeof(a[0])); + assert(c.bucket_count() >= 5); + assert(c.size() == 4); + assert(std::distance(c.begin(), c.end()) == c.size()); + assert(std::distance(c.cbegin(), c.cend()) == c.size()); + C::iterator i; + } + { + typedef std::unordered_map<int, std::string> C; + typedef std::pair<int, std::string> P; + P a[] = + { + P(1, "one"), + P(2, "two"), + P(3, "three"), + P(4, "four"), + P(1, "four"), + P(2, "four"), + }; + const C c(a, a + sizeof(a)/sizeof(a[0])); + assert(c.bucket_count() >= 5); + assert(c.size() == 4); + assert(std::distance(c.begin(), c.end()) == c.size()); + assert(std::distance(c.cbegin(), c.cend()) == c.size()); + C::const_iterator i; + } +#if __cplusplus >= 201103L + { + typedef std::unordered_map<int, std::string, std::hash<int>, std::equal_to<int>, + min_allocator<std::pair<const int, std::string>>> C; + typedef std::pair<int, std::string> P; + P a[] = + { + P(1, "one"), + P(2, "two"), + P(3, "three"), + P(4, "four"), + P(1, "four"), + P(2, "four"), + }; + C c(a, a + sizeof(a)/sizeof(a[0])); + assert(c.bucket_count() >= 5); + assert(c.size() == 4); + assert(std::distance(c.begin(), c.end()) == c.size()); + assert(std::distance(c.cbegin(), c.cend()) == c.size()); + C::iterator i; + } + { + typedef std::unordered_map<int, std::string, std::hash<int>, std::equal_to<int>, + min_allocator<std::pair<const int, std::string>>> C; + typedef std::pair<int, std::string> P; + P a[] = + { + P(1, "one"), + P(2, "two"), + P(3, "three"), + P(4, "four"), + P(1, "four"), + P(2, "four"), + }; + const C c(a, a + sizeof(a)/sizeof(a[0])); + assert(c.bucket_count() >= 5); + assert(c.size() == 4); + assert(std::distance(c.begin(), c.end()) == c.size()); + assert(std::distance(c.cbegin(), c.cend()) == c.size()); + C::const_iterator i; + } +#endif +#if _LIBCPP_STD_VER > 11 + { // N3644 testing + typedef std::unordered_map<int,double> C; + C::iterator ii1{}, ii2{}; + C::iterator ii4 = ii1; + C::const_iterator cii{}; + assert ( ii1 == ii2 ); + assert ( ii1 == ii4 ); + assert ( ii1 == cii ); + + assert ( !(ii1 != ii2 )); + assert ( !(ii1 != cii )); + } +#endif +} diff --git a/pool/shard007/C++/0092873_mw_main.cpp b/pool/shard007/C++/0092873_mw_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a24ad3b7d96d30d2fe6689e4a553970df53979a --- /dev/null +++ b/pool/shard007/C++/0092873_mw_main.cpp @@ -0,0 +1,200 @@ +#include <vector> + +#include <ESP8266WiFi.h> +#include <ESP8266WebServer.h> +#include <DNSServer.h> +#include <EEPROM.h> + +// Install PubSubClient with: +// pio lib search PubSubClient # -> library ID +// pio lib install <ID> +#include <PubSubClient.h> + +#include "../lib/mw-queue.h" +#include "../lib/mw-entity.h" +#include "../lib/mw-scheduler.h" + +#include "../lib/mw-basicnet.h" +#include "../lib/mw-mqtt.h" + +#include "../lib/entities/mw-ent-led.h" + +// Application name, used for default hostnames and AP-names +String application = "MeisterWerk"; + +// Task Scheduler object +MW_Scheduler mwScheduler; + +// Basic networking and web config +MW_BasicNet mwBN(application, 20, true); // application-name, timeout-for-connecting-to-AP, serial-debug-active + +// MQTT client +MW_MQTT mwMQ; + +// EEPROM user configuration content +T_EEPROM tep; + +// New led +MW_Led onboardLed("OnboardLed", BUILTIN_LED, false); // true: publish all led changes... + +// START SCHROTTHAUFEN -> Entity-Object-Model needed. +//--- Button task -------------------------------------------------------------- +int resetButtonDurationPressedMs = 0; +int resetButtonState = MW_STATE_UNDEFINED; +int lastButtonState = MW_STATE_UNDEFINED; +int lastButtonTicker = 0; +int buttonMode=0; +unsigned int buttonPort; +unsigned int resetButtonGetState() +{ + int state = digitalRead(buttonPort); + if (state == 0) + resetButtonState = MW_STATE_ON; + else + resetButtonState = MW_STATE_OFF; + return resetButtonState; +} +void resetButtonInit(unsigned int port) +{ + buttonPort = port; + pinMode(buttonPort, INPUT); + lastButtonState = resetButtonGetState(); +} +void resetButtonLoop(unsigned long ticker) +{ + if (lastButtonTicker == 0) + lastButtonTicker = ticker; + unsigned long deltaMs = (ticker - lastButtonTicker) / 1000L; + lastButtonTicker=ticker; + if (resetButtonGetState() == MW_STATE_OFF) + { + buttonMode=0; + if (resetButtonDurationPressedMs>0) + { + Serial.println("ResetDurationMs: "+String(resetButtonDurationPressedMs)); + if (resetButtonDurationPressedMs >= 30000) + { + // >=30 sec Long press: kill config eeprom + resetButtonDurationPressedMs = 0; + Serial.println("WARNING: HARD FACTORY RESET INITIATED!"); + Serial.println("EEPROM will be erased. The UUID of this device will be regenerated."); + mwBN.clearEEPROM(); + Serial.println("EEPROM erased, restarting..."); + ESP.restart(); + } + else + { + if (resetButtonDurationPressedMs >= 10000) + { + // >= 10 < 30 sec: go into access point mode: (XXX: hacky) + resetButtonDurationPressedMs = 0; + Serial.println("Entering accesspoint mode... (no restart)"); + mwBN.enterAccessPointMode(); + onboardLed.setBlinkIntervallMs(500); // XXX: should be set by entering access point mode + } + else + { + // <10 sec short press, restart esp() + resetButtonDurationPressedMs = 0; + Serial.println("Soft restart..."); + ESP.restart(); + } + } + } + } + else + { // Button is pressed. + resetButtonDurationPressedMs += deltaMs; + if (resetButtonDurationPressedMs >= 30000) + { // XXX: set only once + if (buttonMode<2) { + Serial.println("EEPROM erasure mode entered."); + onboardLed.setBlinkIntervallMs(100); // Furious blinking + buttonMode=2; + } + } + else + { + if (resetButtonDurationPressedMs >= 10000) + { + if (buttonMode<1) { + Serial.println("Enter AP mode (no erase config)"); + onboardLed.setBlinkIntervallMs(300); // Fast blinking + buttonMode=1; + } + } + } + } +} +//--- Heap watchdog task ------------------------------------------------------ +extern "C" { +#include "user_interface.h" +} +unsigned long getFreeHeap() +{ + uint32_t free = system_get_free_heap_size(); + return (unsigned long)free; +} +void watchdogLoop(unsigned long ticker) +{ + unsigned long freeHeap = getFreeHeap(); + if (freeHeap < 10000L) + { + // Alarm! + Serial.println("Watchdog: heap is low: " + String(freeHeap)); + } +} +//--- Basic Networking & Web config ------------------------------------------- +bool isWifiConnected = false; +void basicNetworkingWebConfigLoop(unsigned long ticker) { + // Handle AP connection/creation and Web config interface. + isWifiConnected = mwBN.handleCom(); +} +//--- MQTT client ------------------------------------------------------------- +void mqttClientLoop(unsigned long ticker) { + if (isWifiConnected) + { + // connected to local network + onboardLed.setBlinkIntervallMs(2000); + mwMQ.handleMQTT(); + } +} +//----------------------------------------------------------------------------- +// END SCHROTTHAUFEN ---------------------------------------------------------- + +void setup() +{ + // Debug console + Serial.begin(115200); + + // Internal LED + onboardLed.setState(MW_STATE_ON); + onboardLed.setMode(LED_MODE_BLINK); + onboardLed.setBlinkIntervallMs(500); // XXX: should be set by entering access point mode + + // Reset button + resetButtonInit(GPIO_ID_PIN0); // ID_PIN0 == D3 is the Flash button and will be observed for soft/hard reset. + // short press (<10sec): software-reboot, + // long press (10-30sec): enter access point mode, keep config (fast blinking) + // very long press (>=30 sec): erase eeprom, factory reset. (furious blinking) + mwScheduler.addTask("ResetButton", resetButtonLoop, 50000L, MW_PRIORITY_SYSTEMCRITICAL); + + // Heap watchdog + mwScheduler.addTask("Watchdog", watchdogLoop, 2000000L, MW_PRIORITY_LOW); + + // Basic networking & web configuration for accesspoint & WiFi-client mode + mwBN.begin(); // Start MW Basic Networking: try to connect to AP, or on failure: create config AP (http://10.1.1.1) + mwScheduler.addTask("BasicNetworking", basicNetworkingWebConfigLoop, 10000L, MW_PRIORITY_HIGH); + + // EEPROM configuration + tep = mwBN.getEEPROM(); + + // MQTT client + mwMQ.begin(tep.mqttserver); + mwScheduler.addTask("MqttClient", mqttClientLoop, 20000L, MW_PRIORITY_HIGH); +} + +void loop() +{ // non-blocking event loop + mwScheduler.loop(); +} diff --git a/pool/shard007/C++/0092879_tab_model_unittest.cc b/pool/shard007/C++/0092879_tab_model_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..96d208640f12c9d8f003dcd6be011cba818f8869 --- /dev/null +++ b/pool/shard007/C++/0092879_tab_model_unittest.cc @@ -0,0 +1,84 @@ +// Copyright (c) 2012 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 "chrome/browser/chrome_notification_types.h" +#include "chrome/browser/ui/android/tab_model/tab_model.h" +#include "chrome/test/base/testing_profile.h" +#include "content/public/browser/notification_service.h" +#include "content/public/browser/notification_source.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +typedef testing::Test TabModelTest; + +namespace { +class TabModelAndroidProfileMock : public TestingProfile { + public: + TabModelAndroidProfileMock() {} + virtual ~TabModelAndroidProfileMock() {} + + MOCK_METHOD0(GetOffTheRecordProfile, Profile*()); + MOCK_METHOD0(HasOffTheRecordProfile, bool()); +}; +} // namespace + +class TestTabModel : public TabModel { + public: + explicit TestTabModel(Profile* profile) + : TabModel(profile) {} + + virtual int GetTabCount() const OVERRIDE { return 0; } + virtual int GetActiveIndex() const OVERRIDE { return 0; } + virtual content::WebContents* GetWebContentsAt(int index) const OVERRIDE { + return NULL; + } + virtual void CreateTab(content::WebContents* web_contents) OVERRIDE {} + virtual content::WebContents* CreateTabForTesting(const GURL& url) OVERRIDE { + return NULL; + } + virtual bool IsSessionRestoreInProgress() const OVERRIDE { return false; } + virtual void OpenClearBrowsingData() const OVERRIDE {} + virtual browser_sync::SyncedTabDelegate* GetTabAt(int index) const OVERRIDE { + return NULL; + } + +}; + +TEST_F(TabModelTest, TestProfileHandling) { + // Construct TabModel with standard Profile. + TestingProfile testing_profile; + TestTabModel tab_model(&testing_profile); + + // Verify TabModel has the correct profile and profile type. + EXPECT_EQ(&testing_profile, tab_model.GetProfile()); + EXPECT_FALSE(tab_model.IsOffTheRecord()); + + // Notify profile is being destroyed and verify pointer is cleared. + content::NotificationService::current()->Notify( + chrome::NOTIFICATION_PROFILE_DESTROYED, + content::Source<Profile>(&testing_profile), + content::NotificationService::NoDetails()); + EXPECT_EQ(NULL, tab_model.GetProfile()); +} + +TEST_F(TabModelTest, TestProfileHandlingOffTheRecord) { + // Construct TabModel with off-the-record Profile. + TabModelAndroidProfileMock testing_profile; + EXPECT_CALL(testing_profile, HasOffTheRecordProfile()) + .WillOnce(testing::Return(true)); + EXPECT_CALL(testing_profile, GetOffTheRecordProfile()) + .WillOnce(testing::Return(&testing_profile)); + TestTabModel tab_model(&testing_profile); + + // Verify TabModel has the correct profile and profile type. + EXPECT_EQ(&testing_profile, tab_model.GetProfile()); + EXPECT_TRUE(tab_model.IsOffTheRecord()); + + // Notify profile is being destroyed and verify pointer is cleared. + content::NotificationService::current()->Notify( + chrome::NOTIFICATION_PROFILE_DESTROYED, + content::Source<Profile>(&testing_profile), + content::NotificationService::NoDetails()); + EXPECT_EQ(NULL, tab_model.GetProfile()); +} diff --git a/pool/shard007/C++/0092896_FilterByGoodTimeIntervalsForHXI.cc b/pool/shard007/C++/0092896_FilterByGoodTimeIntervalsForHXI.cc new file mode 100644 index 0000000000000000000000000000000000000000..01a8dfc897087b9d99516efa0152fde0fed4925a --- /dev/null +++ b/pool/shard007/C++/0092896_FilterByGoodTimeIntervalsForHXI.cc @@ -0,0 +1,66 @@ +/************************************************************************* + * * + * Copyright (c) 2011 Hirokazu Odaka * + * * + * This program is free software: you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation, either version 3 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program. If not, see <http://www.gnu.org/licenses/>. * + * * + *************************************************************************/ + +#include "FilterByGoodTimeIntervalsForHXI.hh" +#include "AstroUnits.hh" +#include "ReadHXIEventFITS.hh" + + +using namespace anlnext; + +namespace comptonsoft +{ + +FilterByGoodTimeIntervalsForHXI::FilterByGoodTimeIntervalsForHXI() = default; + +FilterByGoodTimeIntervalsForHXI::~FilterByGoodTimeIntervalsForHXI() = default; + +ANLStatus FilterByGoodTimeIntervalsForHXI::mod_initialize() +{ + get_module("ReadHXIEventFITS", &m_EventReader); + define_evs("FilterByGoodTimeIntervals:OK"); + + return AS_OK; +} + +ANLStatus FilterByGoodTimeIntervalsForHXI::mod_analyze() +{ + bool passed = false; + + const double t = m_EventReader->EventTime(); + for (const std::tuple<double, double>& interval: m_GTIs) { + const double time0 = std::get<0>(interval); + const double time1 = std::get<1>(interval); + if (time0<=t && t<time1) { + passed = true; + break; + } + } + + if (passed) { + set_evs("FilterByGoodTimeIntervals:OK"); + } + else { + return AS_SKIP; + } + + return AS_OK; +} + +} /* namespace comptonsoft */ diff --git a/pool/shard007/C++/0092899_app_restore_service_factory.cc b/pool/shard007/C++/0092899_app_restore_service_factory.cc new file mode 100644 index 0000000000000000000000000000000000000000..9a527aa43cfadf66e46b54906cacf9ab08d98e29 --- /dev/null +++ b/pool/shard007/C++/0092899_app_restore_service_factory.cc @@ -0,0 +1,46 @@ +// Copyright (c) 2012 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 "chrome/browser/extensions/app_restore_service_factory.h" + +#include "chrome/browser/extensions/app_restore_service.h" +#include "chrome/browser/profiles/profile_dependency_manager.h" + +namespace extensions { + +// static +AppRestoreService* AppRestoreServiceFactory::GetForProfile(Profile* profile) { + return static_cast<AppRestoreService*>( + GetInstance()->GetServiceForProfile(profile, true)); +} + +// static +void AppRestoreServiceFactory::ResetForProfile(Profile* profile) { + AppRestoreServiceFactory* factory = GetInstance(); + factory->ProfileShutdown(profile); + factory->ProfileDestroyed(profile); +} + +AppRestoreServiceFactory* AppRestoreServiceFactory::GetInstance() { + return Singleton<AppRestoreServiceFactory>::get(); +} + +AppRestoreServiceFactory::AppRestoreServiceFactory() + : ProfileKeyedServiceFactory("AppRestoreService", + ProfileDependencyManager::GetInstance()) { +} + +AppRestoreServiceFactory::~AppRestoreServiceFactory() { +} + +ProfileKeyedService* AppRestoreServiceFactory::BuildServiceInstanceFor( + Profile* profile) const { + return new AppRestoreService(profile); +} + +bool AppRestoreServiceFactory::ServiceIsCreatedWithProfile() const { + return true; +} + +} // namespace extensions diff --git a/pool/shard007/C++/0092902_extension_override_apitest.cc b/pool/shard007/C++/0092902_extension_override_apitest.cc new file mode 100644 index 0000000000000000000000000000000000000000..69c65e60ce583c990711f77133fd5b89e12b8da2 --- /dev/null +++ b/pool/shard007/C++/0092902_extension_override_apitest.cc @@ -0,0 +1,141 @@ +// Copyright (c) 2012 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 "chrome/browser/extensions/extension_apitest.h" +#include "chrome/browser/extensions/extension_service.h" +#include "chrome/browser/extensions/extension_web_ui.h" +#include "chrome/browser/prefs/pref_service.h" +#include "chrome/browser/prefs/scoped_user_pref_update.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_tabstrip.h" +#include "chrome/common/url_constants.h" +#include "chrome/test/base/ui_test_utils.h" +#include "content/public/browser/navigation_entry.h" +#include "content/public/browser/web_contents.h" + +using content::WebContents; + +class ExtensionOverrideTest : public ExtensionApiTest { + protected: + bool CheckHistoryOverridesContainsNoDupes() { + // There should be no duplicate entries in the preferences. + const DictionaryValue* overrides = + browser()->profile()->GetPrefs()->GetDictionary( + ExtensionWebUI::kExtensionURLOverrides); + + ListValue* values = NULL; + if (!overrides->GetList("history", &values)) + return false; + + std::set<std::string> seen_overrides; + for (size_t i = 0; i < values->GetSize(); ++i) { + std::string value; + if (!values->GetString(i, &value)) + return false; + + if (seen_overrides.find(value) != seen_overrides.end()) + return false; + + seen_overrides.insert(value); + } + + return true; + } +}; + +IN_PROC_BROWSER_TEST_F(ExtensionOverrideTest, OverrideNewtab) { + ASSERT_TRUE(RunExtensionTest("override/newtab")) << message_; + { + ResultCatcher catcher; + // Navigate to the new tab page. The overridden new tab page + // will call chrome.test.notifyPass() . + ui_test_utils::NavigateToURL(browser(), GURL("chrome://newtab/")); + WebContents* tab = chrome::GetActiveWebContents(browser()); + ASSERT_TRUE(tab->GetController().GetActiveEntry()); + EXPECT_TRUE(tab->GetController().GetActiveEntry()->GetURL(). + SchemeIs(chrome::kExtensionScheme)); + + ASSERT_TRUE(catcher.GetNextResult()); + } + + // TODO(erikkay) Load a second extension with the same override. + // Verify behavior, then unload the first and verify behavior, etc. +} + +#if defined(OS_MACOSX) +// Hangy: http://crbug.com/70511 +#define MAYBE_OverrideNewtabIncognito DISABLED_OverrideNewtabIncognito +#else +#define MAYBE_OverrideNewtabIncognito OverrideNewtabIncognito +#endif +IN_PROC_BROWSER_TEST_F(ExtensionOverrideTest, MAYBE_OverrideNewtabIncognito) { + ASSERT_TRUE(RunExtensionTest("override/newtab")) << message_; + + // Navigate an incognito tab to the new tab page. We should get the actual + // new tab page because we can't load chrome-extension URLs in incognito. + Browser* otr_browser = ui_test_utils::OpenURLOffTheRecord( + browser()->profile(), GURL("chrome://newtab/")); + WebContents* tab = chrome::GetActiveWebContents(otr_browser); + ASSERT_TRUE(tab->GetController().GetActiveEntry()); + EXPECT_FALSE(tab->GetController().GetActiveEntry()->GetURL(). + SchemeIs(chrome::kExtensionScheme)); +} + +// Times out consistently on Win, http://crbug.com/45173. +#if defined(OS_WIN) +#define MAYBE_OverrideHistory DISABLED_OverrideHistory +#else +#define MAYBE_OverrideHistory OverrideHistory +#endif // defined(OS_WIN) + +IN_PROC_BROWSER_TEST_F(ExtensionOverrideTest, MAYBE_OverrideHistory) { + ASSERT_TRUE(RunExtensionTest("override/history")) << message_; + { + ResultCatcher catcher; + // Navigate to the history page. The overridden history page + // will call chrome.test.notifyPass() . + ui_test_utils::NavigateToURL(browser(), GURL("chrome://history/")); + ASSERT_TRUE(catcher.GetNextResult()); + } +} + +// Regression test for http://crbug.com/41442. +IN_PROC_BROWSER_TEST_F(ExtensionOverrideTest, ShouldNotCreateDuplicateEntries) { + const extensions::Extension* extension = + LoadExtension(test_data_dir_.AppendASCII("override/history")); + ASSERT_TRUE(extension); + + // Simulate several LoadExtension() calls happening over the lifetime of + // a preferences file without corresponding UnloadExtension() calls. + for (size_t i = 0; i < 3; ++i) { + ExtensionWebUI::RegisterChromeURLOverrides( + browser()->profile(), + extension->GetChromeURLOverrides()); + } + + ASSERT_TRUE(CheckHistoryOverridesContainsNoDupes()); +} + +IN_PROC_BROWSER_TEST_F(ExtensionOverrideTest, ShouldCleanUpDuplicateEntries) { + // Simulate several LoadExtension() calls happening over the lifetime of + // a preferences file without corresponding UnloadExtension() calls. This is + // the same as the above test, except for that it is testing the case where + // the file already contains dupes when an extension is loaded. + ListValue* list = new ListValue(); + for (size_t i = 0; i < 3; ++i) + list->Append(Value::CreateStringValue("http://www.google.com/")); + + { + DictionaryPrefUpdate update(browser()->profile()->GetPrefs(), + ExtensionWebUI::kExtensionURLOverrides); + update.Get()->Set("history", list); + } + + ASSERT_FALSE(CheckHistoryOverridesContainsNoDupes()); + + ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("override/history"))); + + ASSERT_TRUE(CheckHistoryOverridesContainsNoDupes()); +} diff --git a/pool/shard007/C++/0092905_proxy_protocol_fuzz_test.cc b/pool/shard007/C++/0092905_proxy_protocol_fuzz_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..8129d8fb8721e85fcd4126ba612863a627996b0d --- /dev/null +++ b/pool/shard007/C++/0092905_proxy_protocol_fuzz_test.cc @@ -0,0 +1,32 @@ +#include "extensions/filters/listener/proxy_protocol/proxy_protocol.h" + +#include "test/extensions/filters/listener/common/fuzz/listener_filter_fuzzer.h" +#include "test/extensions/filters/listener/proxy_protocol/proxy_protocol_fuzz_test.pb.validate.h" +#include "test/fuzz/fuzz_runner.h" + +namespace Envoy { +namespace Extensions { +namespace ListenerFilters { +namespace ProxyProtocol { + +DEFINE_PROTO_FUZZER( + const test::extensions::filters::listener::proxy_protocol::ProxyProtocolTestCase& input) { + try { + TestUtility::validate(input); + } catch (const ProtoValidationException& e) { + ENVOY_LOG_MISC(debug, "ProtoValidationException: {}", e.what()); + return; + } + + Stats::IsolatedStoreImpl store; + ConfigSharedPtr cfg = std::make_shared<Config>(store, input.config()); + auto filter = std::make_unique<Filter>(std::move(cfg)); + + ListenerFilterFuzzer fuzzer; + fuzzer.fuzz(*filter, input.fuzzed()); +} + +} // namespace ProxyProtocol +} // namespace ListenerFilters +} // namespace Extensions +} // namespace Envoy diff --git a/pool/shard007/C++/0092906_mmap_file_tests.cc b/pool/shard007/C++/0092906_mmap_file_tests.cc new file mode 100644 index 0000000000000000000000000000000000000000..5859c97c616305f7f151d1f7c648fe926842ed0d --- /dev/null +++ b/pool/shard007/C++/0092906_mmap_file_tests.cc @@ -0,0 +1,114 @@ +// Copyright 2020 Google LLC +// +// 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 <fstream> + +#include "gtest/gtest.h" +#include "mmap_file.h" +#include "segy_file.h" +#include "test/test_base.h" + +namespace segystack { +namespace test { + +class MmapFileTest : public ::testing::Test { + void SetUp() override { + tmp_file_ = "/tmp/segystack_mmap_file_test.bin"; + std::ofstream ofs(tmp_file_.c_str(), + std::ofstream::trunc | std::ofstream::binary); + test_header_ = "Test data"; + ofs.write(test_header_.c_str(), test_header_.size()); + ofs.close(); + } + + void TearDown() override { ::unlink(tmp_file_.c_str()); } + + protected: + std::string tmp_file_; + std::string test_header_; +}; + +TEST_F(MmapFileTest, NonExistent) { + std::string nonexistent_file("/tmp/non_existent_file.bin"); + MmapFile fp(nonexistent_file); + ASSERT_FALSE(fp.exists()); + ASSERT_THROW(fp.open(), std::runtime_error); + ASSERT_THROW(fp.fd(), std::runtime_error); + + std::ofstream ofp(nonexistent_file.c_str()); + ofp << "data"; + ofp.close(); + + ASSERT_NO_THROW(fp.open(std::ios_base::in)); + ASSERT_NO_THROW(fp.close()); + ASSERT_NO_THROW(fp.remove()); + ASSERT_FALSE(fp.exists()); +} + +TEST_F(MmapFileTest, BasicOperations) { + MmapFile fp(tmp_file_); + ASSERT_EQ(fp.name(), tmp_file_); + ASSERT_TRUE(fp.exists()); + ASSERT_FALSE(fp.is_open()); + ASSERT_FALSE(fp.is_mapped()); + ASSERT_THROW(fp.fd(), std::runtime_error); + ASSERT_NO_THROW(fp.open(std::ios_base::in)); + ASSERT_TRUE(fp.is_open()); + ASSERT_EQ(fp.size(), test_header_.size()); + + struct stat statbuf; + ASSERT_EQ(::fstat(fp.fd(), &statbuf), 0); + + ASSERT_FALSE(fp.is_mapped()); + ASSERT_NO_THROW(fp.map()); + ASSERT_TRUE(fp.is_mapped()); + + ASSERT_NE(fp.addr(), nullptr); + ASSERT_NE(fp.char_addr(), nullptr); + + std::vector<char> buffer(fp.size()); + ::memcpy(buffer.data(), fp.addr(), fp.size()); + std::string buffer_str(buffer.data(), buffer.size()); + ASSERT_EQ(buffer_str, test_header_); + + ASSERT_NO_THROW(fp.unmap()); + ASSERT_FALSE(fp.is_mapped()); + ASSERT_TRUE(fp.is_open()); + ASSERT_NO_THROW(fp.close()); + ASSERT_FALSE(fp.is_open()); + ASSERT_FALSE(fp.is_mapped()); +} + +TEST_F(MmapFileTest, CheckTestSegy) { + int num_samples = 7; + int num_il = 3, num_xl = 4; + create_test_segy(tmp_file_, num_samples, 4, num_il, 1, num_xl, 1, 0.0f, 0.0f, + 1.0f, 1.0f); + + MmapFile fp(tmp_file_); + ASSERT_NO_THROW(fp.open(std::ios_base::in)); + ASSERT_EQ( + fp.size(), + SegyFile::TEXT_HEADER_SIZE + SegyFile::BINARY_HEADER_SIZE + + num_il * num_xl * + (SegyFile::TRACE_HEADER_SIZE + sizeof(float) * num_samples)); + ASSERT_NO_THROW(fp.map()); + ASSERT_EQ(fp.end() - fp.begin(), fp.size()); + ASSERT_NO_THROW(fp.close()); + ASSERT_NO_THROW(fp.remove()); + ASSERT_FALSE(fp.exists()); +} + +} // namespace test +} // namespace segystack diff --git a/pool/shard007/C++/0092912_photonestimationtask.cpp b/pool/shard007/C++/0092912_photonestimationtask.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3a21510f1f38121ffb49f8a12f5f7a185ec2c251 --- /dev/null +++ b/pool/shard007/C++/0092912_photonestimationtask.cpp @@ -0,0 +1,228 @@ +//****************************************************************************** +/// +/// @file backend/lighting/photonestimationtask.cpp +/// +/// This module implements Photon Mapping. +/// +/// Author: Nathan Kopp +/// +/// @copyright +/// @parblock +/// +/// Persistence of Vision Ray Tracer ('POV-Ray') version 3.8. +/// Copyright 1991-2019 Persistence of Vision Raytracer Pty. Ltd. +/// +/// POV-Ray is free software: you can redistribute it and/or modify +/// it under the terms of the GNU Affero General Public License as +/// published by the Free Software Foundation, either version 3 of the +/// License, or (at your option) any later version. +/// +/// POV-Ray is distributed in the hope that it will be useful, +/// but WITHOUT ANY WARRANTY; without even the implied warranty of +/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +/// GNU Affero General Public License for more details. +/// +/// You should have received a copy of the GNU Affero General Public License +/// along with this program. If not, see <http://www.gnu.org/licenses/>. +/// +/// ---------------------------------------------------------------------------- +/// +/// POV-Ray is based on the popular DKB raytracer version 2.12. +/// DKBTrace was originally written by David K. Buck. +/// DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins. +/// +/// @endparblock +/// +//****************************************************************************** + +// Unit header file must be the first file included within POV-Ray *.cpp files (pulls in config) +#include "backend/lighting/photonestimationtask.h" + +// C++ variants of C standard header files +// (none at the moment) + +// C++ standard header files +#include <memory> + +// POV-Ray header files (base module) +// (none at the moment) + +// POV-Ray header files (core module) +#include "core/bounding/boundingbox.h" +#include "core/lighting/lightgroup.h" +#include "core/lighting/lightsource.h" +#include "core/math/matrix.h" +#include "core/scene/object.h" +#include "core/shape/csg.h" +#include "core/support/octree.h" + +// POV-Ray header files (POVMS module) +#include "povms/povmscpp.h" +#include "povms/povmsid.h" +#include "povms/povmsutil.h" + +// POV-Ray header files (backend module) +#include "backend/scene/backendscenedata.h" +#include "backend/scene/view.h" +#include "backend/scene/viewthreaddata.h" + +// this must be the last file included +#include "base/povdebug.h" + +namespace pov +{ + +using std::vector; + +PhotonEstimationTask::PhotonEstimationTask(ViewData *vd, size_t seed) : + RenderTask(vd, seed, "Photon"), + cooperate(*this) +{ + photonCountEstimate = 0; +} + +PhotonEstimationTask::~PhotonEstimationTask() +{ +} + + +void PhotonEstimationTask::Run() +{ + // quit right away if photons not enabled + if (!GetSceneData()->photonSettings.photonsEnabled) return; + + if (GetSceneData()->photonSettings.surfaceCount==0) return; + + Cooperate(); + + // COUNT THE PHOTONS + DBL factor; + photonCountEstimate = 0.0; + + // global lights + GetViewDataPtr()->Light_Is_Global = true; + for(vector<LightSource *>::iterator Light = GetSceneData()->lightSources.begin(); Light != GetSceneData()->lightSources.end(); Light++) + { + if((*Light)->Light_Type != FILL_LIGHT_SOURCE) + SearchThroughObjectsEstimatePhotons(GetSceneData()->objects, *Light); + } + + // light_group lights + /* + TODO + renderer->sceneData->photonSettings.Light_Is_Global = false; + for(vector<LightSource *>::iterator Light_Group_Light = renderer->sceneData->lightGroupLights.begin(); Light_Group_Light != renderer->sceneData->lightGroupLights.end(); Light_Group_Light++) + { + Light = Light_Group_Light->Light; + if (Light->Light_Type != FILL_LightSource) + { + SearchThroughObjectsEstimatePhotons(GetSceneData()->objects, *Light); + } + } + */ + + factor = (DBL)photonCountEstimate/GetSceneData()->photonSettings.surfaceCount; + factor = sqrt(factor); + GetSceneData()->photonSettings.surfaceSeparation *= factor; + + + // good idea to make sure all warnings and errors arrive frontend now [trf] + Cooperate(); +} + +void PhotonEstimationTask::Stopped() +{ + // nothing to do for now [trf] +} + +void PhotonEstimationTask::Finish() +{ + GetViewDataPtr()->timeType = TraceThreadData::kPhotonTime; + GetViewDataPtr()->realTime = ConsumedRealTime(); + GetViewDataPtr()->cpuTime = ConsumedCPUTime(); +} + + +void PhotonEstimationTask::SearchThroughObjectsEstimatePhotons(vector<ObjectPtr>& Objects, LightSource *Light) +{ + ViewThreadData *renderDataPtr = GetViewDataPtr(); + std::shared_ptr<SceneData> sceneData = GetSceneData(); + + /* check this object and all siblings */ + for(vector<ObjectPtr>::iterator Sib = Objects.begin(); Sib != Objects.end(); Sib++) + { + if(Test_Flag((*Sib), PH_TARGET_FLAG) && + !((*Sib)->Type & LIGHT_SOURCE_OBJECT)) + { + /* do not shoot photons if global lights are turned off for ObjectPtr */ + if(!Test_Flag((*Sib), NO_GLOBAL_LIGHTS_FLAG)) + { + EstimatePhotonsForObjectAndLight((*Sib), Light); + } + + Cooperate(); + } + /* if it has children, check them too */ + else if(((*Sib)->Type & IS_COMPOUND_OBJECT)) + { + SearchThroughObjectsEstimatePhotons((reinterpret_cast<CSG *>(*Sib))->children, Light); + } + } +} + +void PhotonEstimationTask::EstimatePhotonsForObjectAndLight(ObjectPtr Object, LightSource *Light) +{ + int mergedFlags=0; /* merged flags to see if we should shoot photons */ + ViewThreadData *renderDataPtr = GetViewDataPtr(); + + /* first, check on various flags... make sure all is a go for this ObjectPtr */ + LightTargetCombo combo(Light,Object); + mergedFlags = combo.computeMergedFlags(); + + if (!( ((mergedFlags & PH_RFR_ON_FLAG) && !(mergedFlags & PH_RFR_OFF_FLAG)) || + ((mergedFlags & PH_RFL_ON_FLAG) && !(mergedFlags & PH_RFL_OFF_FLAG)) )) + /* it is a no-go for this object... bail out now */ + return; + + if(!Object) return; + + ShootingDirection shootingDirection(Light,Object); + shootingDirection.compute(); + + /* calculate the spacial separation (spread) */ + renderDataPtr->photonSpread = combo.target->Ph_Density*GetSceneData()->photonSettings.surfaceSeparation; + + /* if rays aren't parallel, divide by dist so we get separation at a distance of 1 unit */ + if (!combo.light->Parallel) + { + renderDataPtr->photonSpread /= shootingDirection.dist; + } + + /* try to guess the number of photons */ + DBL x=shootingDirection.rad / (combo.target->Ph_Density*GetSceneData()->photonSettings.surfaceSeparation); + x=x*x*M_PI; + + if ( ((mergedFlags & PH_RFR_ON_FLAG) && !(mergedFlags & PH_RFR_OFF_FLAG)) && + ((mergedFlags & PH_RFL_ON_FLAG) && !(mergedFlags & PH_RFL_OFF_FLAG)) ) + { + x *= 1.5; /* assume 2 times as many photons with both reflection & refraction */ + } + + if ( !Test_Flag(combo.target, PH_IGNORE_PHOTONS_FLAG) ) + { + if ( ((mergedFlags & PH_RFR_ON_FLAG) && !(mergedFlags & PH_RFR_OFF_FLAG)) ) + { + if ( ((mergedFlags & PH_RFL_ON_FLAG) && !(mergedFlags & PH_RFL_OFF_FLAG)) ) + x *= 3; /* assume 3 times as many photons if ignore_photons not used */ + else + x *= 2; /* assume less for only refraction */ + } + } + + x *= 0.5; /* assume 1/2 of photons hit target ObjectPtr */ + + photonCountEstimate += x; +} + +} +// end of namespace pov diff --git a/pool/shard007/C++/0092919_CWE191_Integer_Underflow__unsigned_int_min_sub_72a.cpp b/pool/shard007/C++/0092919_CWE191_Integer_Underflow__unsigned_int_min_sub_72a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..109e84354b653b286b344e2687aabc6468f097eb --- /dev/null +++ b/pool/shard007/C++/0092919_CWE191_Integer_Underflow__unsigned_int_min_sub_72a.cpp @@ -0,0 +1,118 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE191_Integer_Underflow__unsigned_int_min_sub_72a.cpp +Label Definition File: CWE191_Integer_Underflow.label.xml +Template File: sources-sinks-72a.tmpl.cpp +*/ +/* + * @description + * CWE: 191 Integer Underflow + * BadSource: min Set data to the min value for unsigned int + * GoodSource: Set data to a small, non-zero number (negative two) + * Sinks: sub + * GoodSink: Ensure there will not be an underflow before subtracting 1 from data + * BadSink : Subtract 1 from data, which can cause an Underflow + * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files + * + * */ + +#include "std_testcase.h" +#include <vector> + +using namespace std; + +namespace CWE191_Integer_Underflow__unsigned_int_min_sub_72 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink(vector<unsigned int> dataVector); + +void bad() +{ + unsigned int data; + vector<unsigned int> dataVector; + data = 0; + /* POTENTIAL FLAW: Use the minimum size of the data type */ + data = 0; + /* Put data in a vector */ + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + badSink(dataVector); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(vector<unsigned int> dataVector); + +static void goodG2B() +{ + unsigned int data; + vector<unsigned int> dataVector; + data = 0; + /* FIX: Use a small, non-zero value that will not cause an underflow in the sinks */ + data = -2; + /* Put data in a vector */ + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + goodG2BSink(dataVector); +} + +/* goodB2G uses the BadSource with the GoodSink */ +void goodB2GSink(vector<unsigned int> dataVector); + +static void goodB2G() +{ + unsigned int data; + vector<unsigned int> dataVector; + data = 0; + /* POTENTIAL FLAW: Use the minimum size of the data type */ + data = 0; + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + goodB2GSink(dataVector); +} + +void good() +{ + goodG2B(); + goodB2G(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +using namespace CWE191_Integer_Underflow__unsigned_int_min_sub_72; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard007/C++/0092926_TriangleMesh.cpp b/pool/shard007/C++/0092926_TriangleMesh.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0d97ed0c653ae8b2a037c803b157eaaf8c7ee5d3 --- /dev/null +++ b/pool/shard007/C++/0092926_TriangleMesh.cpp @@ -0,0 +1,46 @@ +#include "TriangleMesh.hpp" +#include <Core/Geometry/RayCast.hpp> +#include <Core/Geometry/TriangleOperation.hpp> // triangleArea +#include <Core/Types.hpp> + +#include <array> +#include <vector> + +namespace Ra { +namespace Core { +namespace Geometry { + +/****/ + +bool AttribArrayGeometry::append( const AttribArrayGeometry& other ) { + // check same attributes through names + if ( !m_vertexAttribs.hasSameAttribs( other.m_vertexAttribs ) ) return false; + // Deal with all attributes the same way (vertices and normals too) + other.m_vertexAttribs.for_each_attrib( [this]( const auto& attr ) { + if ( attr->isFloat() ) this->append_attrib<float>( attr ); + if ( attr->isVec2() ) this->append_attrib<Vector2>( attr ); + if ( attr->isVec3() ) this->append_attrib<Vector3>( attr ); + if ( attr->isVec4() ) this->append_attrib<Vector4>( attr ); + } ); + + return true; +} + +void AttribArrayGeometry::clearAttributes() { + PointAttribHandle::Container v = vertices(); + NormalAttribHandle::Container n = normals(); + m_vertexAttribs.clear(); + initDefaultAttribs(); + setVertices( v ); + setNormals( n ); +} + +void AttribArrayGeometry::colorize( const Utils::Color& color ) { + static const std::string colorAttribName( "in_color" ); + auto colorAttribHandle = addAttrib<Core::Vector4>( colorAttribName ); + getAttrib( colorAttribHandle ).setData( Vector4Array( vertices().size(), color ) ); +} + +} // namespace Geometry +} // namespace Core +} // namespace Ra diff --git a/pool/shard007/C++/0092927_t_dpi_var.cpp b/pool/shard007/C++/0092927_t_dpi_var.cpp new file mode 100644 index 0000000000000000000000000000000000000000..af86f950f1f1f7711f90891aebfc965692e738fd --- /dev/null +++ b/pool/shard007/C++/0092927_t_dpi_var.cpp @@ -0,0 +1,147 @@ +// -*- mode: C++; c-file-style: "cc-mode" -*- +//************************************************************************* +// +// Copyright 2010-2011 by Wilson Snyder. This program is free software; you can +// redistribute it and/or modify it under the terms of either the GNU +// Lesser General Public License Version 3 or the Perl Artistic License. +// Version 2.0. +// +// Verilator is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +//************************************************************************* + +#include "Vt_dpi_var.h" +#include "verilated.h" +#include "svdpi.h" + +#include "verilated_syms.h" + +//====================================================================== + +struct MyMon { + vluint32_t* sigsp[2]; + MyMon() { sigsp[0]=NULL; sigsp[1]=NULL; } +}; +MyMon mons[2]; + +void mon_register_a(const char* namep, void* sigp, bool isOut) { + // Callback from initial block in monitor +#ifdef TEST_VERBOSE + VL_PRINTF("- mon_register_a(\"%s\", %p, %d);\n", namep, sigp, isOut); +#endif + mons[0].sigsp[isOut] = (vluint32_t*)sigp; +} + +void mon_do(MyMon* monp) { + if (!monp->sigsp[0]) vl_fatal(__FILE__,__LINE__,"","never registered"); + if (!monp->sigsp[1]) vl_fatal(__FILE__,__LINE__,"","never registered"); + *monp->sigsp[1] = (*(monp->sigsp[0]))+1; + +#ifdef TEST_VERBOSE + VL_PRINTF("- mon_do(%08x(&%p) -> %08x(&%p));\n", + *(monp->sigsp[0]), monp->sigsp[0], *(monp->sigsp[1]), monp->sigsp[1]); +#endif +} + +void mon_class_name(const char* namep) { +#ifdef TEST_VERBOSE + VL_PRINTF("- mon_class_name(\"%s\");\n", namep); +#endif + // Check the C's calling name of "" doesn't lead to extra dots in the name() + if (namep && namep[0]=='.') vl_fatal(__FILE__,__LINE__,"", (string("Unexp class name ")+namep).c_str()); +} + +extern "C" void mon_scope_name(const char* namep); +void mon_scope_name(const char* namep) { + const char* modp = svGetNameFromScope(svGetScope()); +#ifdef TEST_VERBOSE + VL_PRINTF("- mon_scope_name('%s', \"%s\");\n", modp, namep); +#endif + if (strcmp(namep,"t.sub")) vl_fatal(__FILE__,__LINE__,"", (string("Unexp scope name ")+namep).c_str()); + if (strcmp(modp,"t.sub")) vl_fatal(__FILE__,__LINE__,"", (string("Unexp dpiscope name ")+modp).c_str()); +} + +extern "C" void mon_register_b(const char* namep, int isOut); +void mon_register_b(const char* namep, int isOut) { + const char* modp = svGetNameFromScope(svGetScope()); +#ifdef TEST_VERBOSE + VL_PRINTF("- mon_register_b('%s', \"%s\", %d);\n", modp, namep, isOut); +#endif + // Use scope to get pointer and size of signal + const VerilatedScope* scopep = Verilated::dpiScope(); + const VerilatedVar* varp = scopep->varFind(namep); + if (!varp) { + VL_PRINTF("%%Warning: mon_register_b signal not found: \"%s\"\n", namep); + } else if (varp->vltype() != VLVT_UINT32) { + VL_PRINTF("%%Warning: wrong type for signal: \"%s\"\n", namep); + } else { + vluint32_t* datap = (vluint32_t*)(varp->datap()); + VL_PRINTF("- mon_register_b('%s', \"%s\", %p, %d);\n", modp, namep, datap, isOut); + mons[1].sigsp[isOut] = (vluint32_t*)(varp->datap()); + } +} + +extern "C" void mon_register_done(); +void mon_register_done() { + const char* modp = svGetNameFromScope(svGetScope()); +#ifdef TEST_VERBOSE + VL_PRINTF("- mon_register_done('%s');\n", modp); +#endif + // Print list of all signals - if we didn't register2 anything we'd pick them off here + const VerilatedScope* scopep = Verilated::dpiScope(); + if (VerilatedVarNameMap* varsp = scopep->varsp()) { + for (VerilatedVarNameMap::const_iterator it = varsp->begin(); + it != varsp->end(); ++it) { + VL_PRINTF("- mon2: %s\n", it->first); + } + } +} + +extern "C" void mon_eval(); +void mon_eval() { + // Callback from always@ negedge + mon_do(&mons[0]); + mon_do(&mons[1]); +} + +//====================================================================== + +unsigned int main_time = false; + +double sc_time_stamp () { + return main_time; +} +int main(int argc, char **argv, char **env) { + double sim_time = 1100; + Verilated::commandArgs(argc, argv); + Verilated::debug(0); + + VM_PREFIX* topp = new VM_PREFIX (""); // Note null name - we're flattening it out + +#ifdef VERILATOR +# ifdef TEST_VERBOSE + Verilated::scopesDump(); +# endif +#endif + + topp->eval(); + topp->clk = 0; + main_time += 10; + + while (sc_time_stamp() < sim_time && !Verilated::gotFinish()) { + main_time += 1; + topp->eval(); + topp->clk = !topp->clk; + //mon_do(); + } + if (!Verilated::gotFinish()) { + vl_fatal(__FILE__,__LINE__,"main", "%Error: Timeout; never got a $finish"); + } + topp->final(); + + delete topp; topp=NULL; + exit(0L); +} diff --git a/pool/shard007/C++/0092930_a_node.cpp b/pool/shard007/C++/0092930_a_node.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ac5970c962bc0a321e9e1e3a11ebf442b3c9094f --- /dev/null +++ b/pool/shard007/C++/0092930_a_node.cpp @@ -0,0 +1,26 @@ +#include <iostream> +#include "headers/a_node.h" +#include <vector> +#include <algorithm> + +a_node::a_node() { + this->ativo = true; +} + +bool compare_node::operator()(a_node *&a1, a_node *&a2) { + return ( a1->f > a2->f ); +} + +void a_vector::push_node(a_node *n) { + this->push_back(n); + std::push_heap(this->begin(), this->end(), compare_node()); +} + +void a_vector::pop_node() { + std::pop_heap(this->begin(), this->end(), compare_node()); + this->pop_back(); +} + +void a_vector::initialize_vec() { + std::make_heap(this->begin(), this->end(), compare_node()); +} diff --git a/pool/shard007/C++/0092932_flutter_font_selector.cc b/pool/shard007/C++/0092932_flutter_font_selector.cc new file mode 100644 index 0000000000000000000000000000000000000000..c3efbcacb4a9d330daa344cd9601aaeb4c9a7116 --- /dev/null +++ b/pool/shard007/C++/0092932_flutter_font_selector.cc @@ -0,0 +1,189 @@ +// Copyright 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 "base/logging.h" +#include "base/values.h" +#include "base/json/json_reader.h" +#include "services/asset_bundle/zip_asset_bundle.h" +#include "sky/engine/core/script/ui_dart_state.h" +#include "sky/engine/platform/fonts/FontData.h" +#include "sky/engine/platform/fonts/FontFaceCreationParams.h" +#include "sky/engine/platform/fonts/SimpleFontData.h" +#include "sky/shell/ui/flutter_font_selector.h" +#include "third_party/skia/include/core/SkStream.h" +#include "third_party/skia/include/core/SkTypeface.h" +#include "third_party/skia/include/ports/SkFontMgr.h" + +namespace sky { +namespace shell { + +namespace { +const char kFontManifestAssetPath[] = "FontManifest.json"; +} + +using base::DictionaryValue; +using base::JSONReader; +using base::ListValue; +using base::StringValue; +using base::Value; +using blink::FontCacheKey; +using blink::FontData; +using blink::FontDescription; +using blink::FontFaceCreationParams; +using blink::FontPlatformData; +using blink::SimpleFontData; +using mojo::asset_bundle::ZipAssetBundle; + +void FlutterFontSelector::install( + const scoped_refptr<ZipAssetBundle>& zip_asset_bundle) { + RefPtr<FlutterFontSelector> font_selector = adoptRef( + new FlutterFontSelector(zip_asset_bundle)); + font_selector->parseFontManifest(); + blink::UIDartState::Current()->set_font_selector(font_selector); +} + +FlutterFontSelector::FlutterFontSelector( + const scoped_refptr<ZipAssetBundle>& zip_asset_bundle) + : zip_asset_bundle_(zip_asset_bundle) { +} + +FlutterFontSelector::~FlutterFontSelector() { +} + +FlutterFontSelector::TypefaceAsset::TypefaceAsset() { +} + +FlutterFontSelector::TypefaceAsset::~TypefaceAsset() { +} + +void FlutterFontSelector::parseFontManifest() { + std::vector<uint8_t> font_manifest_data; + if (!zip_asset_bundle_->GetAsBuffer(kFontManifestAssetPath, + &font_manifest_data)) + return; + + base::StringPiece font_manifest_str( + reinterpret_cast<const char*>(font_manifest_data.data()), + font_manifest_data.size()); + scoped_ptr<Value> font_manifest_json = JSONReader::Read(font_manifest_str); + if (font_manifest_json == nullptr) + return; + + ListValue* family_list; + if (!font_manifest_json->GetAsList(&family_list)) + return; + + for (auto family : *family_list) { + DictionaryValue* family_dict; + if (!family->GetAsDictionary(&family_dict)) + continue; + std::string family_name; + if (!family_dict->GetString("family", &family_name)) + continue; + + ListValue* font_list; + if (!family_dict->GetList("fonts", &font_list)) + continue; + + if (font_list->GetSize() != 1) { + LOG(WARNING) << "Font family " << family_name + << " must have exactly one font"; + continue; + } + DictionaryValue* font_dict; + if (!font_list->GetDictionary(0, &font_dict)) + continue; + + std::string asset_path; + if (!font_dict->GetString("asset", &asset_path)) + continue; + + font_asset_path_map_.set(AtomicString::fromUTF8(family_name.c_str()), + AtomicString::fromUTF8(asset_path.c_str())); + } +} + +PassRefPtr<FontData> FlutterFontSelector::getFontData( + const FontDescription& font_description, + const AtomicString& family_name) { + FontFaceCreationParams creationParams(family_name); + FontCacheKey key = font_description.cacheKey(creationParams); + RefPtr<SimpleFontData> font_data = font_platform_data_cache_.get(key); + + if (font_data == nullptr) { + SkTypeface* typeface = getTypefaceAsset(family_name); + if (typeface == nullptr) + return nullptr; + + bool synthetic_bold = + (font_description.weight() >= blink::FontWeight600 && !typeface->isBold()) || + font_description.isSyntheticBold(); + bool synthetic_italic = + (font_description.style() && !typeface->isItalic()) || + font_description.isSyntheticItalic(); + FontPlatformData platform_data( + typeface, + family_name.utf8().data(), + font_description.effectiveFontSize(), + synthetic_bold, + synthetic_italic, + font_description.orientation(), + font_description.useSubpixelPositioning()); + + font_data = SimpleFontData::create(platform_data); + font_platform_data_cache_.set(key, font_data); + } + + return font_data; +} + +SkTypeface* FlutterFontSelector::getTypefaceAsset( + const AtomicString& family_name) { + auto it = typeface_cache_.find(family_name); + if (it != typeface_cache_.end()) { + const TypefaceAsset* cache_asset = it->value.get(); + return cache_asset ? cache_asset->typeface.get() : nullptr; + } + + String font_asset_path = font_asset_path_map_.get(family_name); + if (font_asset_path.isEmpty()) + return nullptr; + + std::unique_ptr<TypefaceAsset> typeface_asset(new TypefaceAsset); + if (!zip_asset_bundle_->GetAsBuffer(font_asset_path.toUTF8(), + &typeface_asset->data)) { + typeface_cache_.set(family_name, nullptr); + return nullptr; + } + + SkAutoTUnref<SkFontMgr> font_mgr(SkFontMgr::RefDefault()); + SkMemoryStream* typeface_stream = new SkMemoryStream( + typeface_asset->data.data(), typeface_asset->data.size()); + typeface_asset->typeface = adoptRef( + font_mgr->createFromStream(typeface_stream)); + if (typeface_asset->typeface == nullptr) { + typeface_cache_.set(family_name, nullptr); + return nullptr; + } + + SkTypeface* result = typeface_asset->typeface.get(); + typeface_cache_.set(family_name, adoptPtr(typeface_asset.release())); + return result; +} + +void FlutterFontSelector::willUseFontData( + const FontDescription& font_description, + const AtomicString& family, + UChar32 character) { +} + +unsigned FlutterFontSelector::version() const { + return 0; +} + +void FlutterFontSelector::fontCacheInvalidated() { +} + +} // namespace shell +} // namespace sky diff --git a/pool/shard007/C++/0092940_gesture_event_details.cc b/pool/shard007/C++/0092940_gesture_event_details.cc new file mode 100644 index 0000000000000000000000000000000000000000..3f478e5aaabce15848e5b1fe6f733e689ad9e994 --- /dev/null +++ b/pool/shard007/C++/0092940_gesture_event_details.cc @@ -0,0 +1,72 @@ +// 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 "ui/events/gesture_event_details.h" + +namespace ui { + +GestureEventDetails::GestureEventDetails() + : type_(ET_UNKNOWN), touch_points_(0), oldest_touch_id_(-1) { +} + +GestureEventDetails::GestureEventDetails(ui::EventType type, + float delta_x, + float delta_y) + : type_(type), touch_points_(1), oldest_touch_id_(0) { + DCHECK_GE(type, ET_GESTURE_TYPE_START); + DCHECK_LE(type, ET_GESTURE_TYPE_END); + switch (type_) { + case ui::ET_GESTURE_SCROLL_BEGIN: + data.scroll_begin.x_hint = delta_x; + data.scroll_begin.y_hint = delta_y; + break; + + case ui::ET_GESTURE_SCROLL_UPDATE: + data.scroll_update.x = delta_x; + data.scroll_update.y = delta_y; + break; + + case ui::ET_SCROLL_FLING_START: + data.fling_velocity.x = delta_x; + data.fling_velocity.y = delta_y; + break; + + case ui::ET_GESTURE_TWO_FINGER_TAP: + data.first_finger_enclosing_rectangle.width = delta_x; + data.first_finger_enclosing_rectangle.height = delta_y; + break; + + case ui::ET_GESTURE_PINCH_UPDATE: + data.scale = delta_x; + CHECK_EQ(0.f, delta_y) << "Unknown data in delta_y for pinch"; + break; + + case ui::ET_GESTURE_SWIPE: + data.swipe.left = delta_x < 0; + data.swipe.right = delta_x > 0; + data.swipe.up = delta_y < 0; + data.swipe.down = delta_y > 0; + break; + + case ui::ET_GESTURE_TAP: + case ui::ET_GESTURE_DOUBLE_TAP: + case ui::ET_GESTURE_TAP_UNCONFIRMED: + data.tap_count = static_cast<int>(delta_x); + CHECK_EQ(0.f, delta_y) << "Unknown data in delta_y for tap."; + break; + + default: + if (delta_x != 0.f || delta_y != 0.f) { + DLOG(WARNING) << "A gesture event (" << type << ") had unknown data: (" + << delta_x << "," << delta_y; + } + break; + } +} + +GestureEventDetails::Details::Details() { + memset(this, 0, sizeof(Details)); +} + +} // namespace ui diff --git a/pool/shard007/C++/0092945_script.cc b/pool/shard007/C++/0092945_script.cc new file mode 100644 index 0000000000000000000000000000000000000000..5f66554b6b53d16250afbab1e40f95ed00440780 --- /dev/null +++ b/pool/shard007/C++/0092945_script.cc @@ -0,0 +1,112 @@ +#include "stdafx.h" + + extern "C"{ + int luaopen_gamesrv (lua_State* tolua_S); +} + +namespace Script +{ + lua_State* L; + int init() + { + L = lua_open(); + luaL_openlibs(L); + luaopen_gamesrv(L); + luaopen_pblua(L); + luaopen_json(L); + + if(dofile("main.lua")) + { + return 1; + } + + return 0; + } + + int dofile(const char* filepath) + { + if(luaL_dofile(L, filepath)) + { + if (lua_isstring(L, -1)) + { + LOG_LOG("dofile error %s\n", lua_tostring(L, -1)); + return 1; + } + } + return 0; + } + + int pushluafunction(const char *func) + { + char *start = (char *)func; + char *class_name = start; + char *pfunc = start; + while(*pfunc != 0) + { + if(*pfunc == '.' && class_name == start) + { + *pfunc = 0; + lua_getglobal(L, class_name); + *pfunc = '.'; + if(lua_isnil(L, -1)){ + return 1; + } + class_name = pfunc + 1; + }else if(*pfunc == '.') + { + *pfunc = 0; + lua_pushstring(L, class_name); + lua_gettable(L, -2); + *pfunc = '.'; + if(lua_isnil(L, -1)) + { + return 2; + } + lua_remove(L, -2);//弹出table + class_name = pfunc + 1; + } + pfunc++; + } + if(class_name == start) + { + lua_getglobal(L, class_name); + if(lua_isnil(L, -1)) + { + return 3; + } + }else + { + lua_pushstring(L, class_name); + lua_gettable(L, -2); + if(lua_isnil(L, -1)) + { + return 4; + } + lua_remove(L, -2);//弹出table + } + return 0; + } + + int printluastack() + { + lua_getglobal(L, "debug"); + lua_getfield(L, -1, "traceback"); + lua_pcall(L, 0, 1, 0); + const char* sz = lua_tostring(L, -1); + printf("%s\n", sz); + return 0; + } + + void update() + { + static char douniu_update[32] = "Douniu.update"; + pushluafunction(douniu_update); + if (lua_pcall(Script::L, 0, 0, 0) != 0) + { + if (lua_isstring(Script::L, -1)) + { + LOG_ERROR("Douniu.update error %s\n", lua_tostring(Script::L, -1)); + } + } + } +}; diff --git a/pool/shard007/C++/0092946_snake.cc b/pool/shard007/C++/0092946_snake.cc new file mode 100644 index 0000000000000000000000000000000000000000..8ede9473c5f95b0a3085390a92cfff0bbe087d02 --- /dev/null +++ b/pool/shard007/C++/0092946_snake.cc @@ -0,0 +1,76 @@ +#include <memory> +#include <stdexcept> +#include "snake.hh" +#include "cell.hh" + +namespace { + const Direction UP = Direction::UP; + const Direction DOWN = Direction::DOWN; + const Direction LEFT = Direction::LEFT; + const Direction RIGHT = Direction::RIGHT; +} + +Snake::Snake(SDL_Surface *surface, unsigned x, unsigned y, Direction direction): + direction(direction), needsToGrow(false), surface(surface) +{ + auto color = getColor(); + body.push_back(std::unique_ptr<Cell>{new Cell(surface, x, y, color)}); +} + +Snake::Snake(SDL_Surface *surface, unsigned x, unsigned y, Direction direction, + unsigned screenWidth, unsigned screenHeight, + decltype(body.size()) initialLength): + direction(direction), needsToGrow(false), surface(surface) +{ + auto color = getColor(); + if (initialLength == 0) { + throw std::invalid_argument("Initial snake length cannot be zero"); + } else if (x * Cell::width() > screenWidth || + y * Cell::height() > screenHeight) { + throw std::invalid_argument("Initial snake coordinates not on screen"); + } else { + body.push_back(std::unique_ptr<Cell>{new Cell(surface, x, y, color)}); + growToInitialLength(initialLength, screenWidth, screenHeight); + } +} + +void Snake::growToInitialLength(decltype(body.size()) initialLength, + unsigned screenWidth, unsigned screenHeight) +{ + unsigned x = head().xPosition() * Cell::width(); + unsigned y = head().yPosition() * Cell::height() + Cell::getYOffset(); + Direction primaryDirection = direction; + Direction secondaryDirection; + switch (direction) { + case UP: case DOWN: + secondaryDirection = (screenWidth - x) > x ? RIGHT : LEFT; + break; + case LEFT: case RIGHT: + secondaryDirection = (screenHeight - y) > y ? DOWN : UP; + break; + } + + while (--initialLength) { + auto next = nextPosition(); + unsigned x = next.first * Cell::width(); + unsigned y = next.second * Cell::height() + Cell::getYOffset(); + // Give a two cell border to prevent immediate deaths + if (x < Cell::width() * 2 || + y < Cell::height() * 2 + Cell::getYOffset() || + x >= screenWidth - Cell::width() * 2 || + y >= screenHeight - Cell::height() * 2) { + if (direction == secondaryDirection) { + throw std::runtime_error("Initial snake length too large"); + } else { + direction = secondaryDirection; + } + } else { + grow(); + move(); + if (direction == secondaryDirection) { + primaryDirection = invert(primaryDirection); + direction = primaryDirection; + } + } + } +} diff --git a/pool/shard007/C++/0092947_proxy_lock.cc b/pool/shard007/C++/0092947_proxy_lock.cc new file mode 100644 index 0000000000000000000000000000000000000000..e1c06521840a3b46837a247fdf6db23f16c66c11 --- /dev/null +++ b/pool/shard007/C++/0092947_proxy_lock.cc @@ -0,0 +1,99 @@ +// Copyright (c) 2012 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 "ppapi/shared_impl/proxy_lock.h" + +#include "base/lazy_instance.h" +#include "base/synchronization/lock.h" +#include "base/threading/thread_local.h" +#include "ppapi/shared_impl/ppapi_globals.h" + +namespace ppapi { + +base::LazyInstance<base::Lock>::Leaky g_proxy_lock = LAZY_INSTANCE_INITIALIZER; + +bool g_disable_locking = false; +base::LazyInstance<base::ThreadLocalBoolean>::Leaky + g_disable_locking_for_thread = LAZY_INSTANCE_INITIALIZER; + +// Simple single-thread deadlock detector for the proxy lock. +// |true| when the current thread has the lock. +base::LazyInstance<base::ThreadLocalBoolean>::Leaky g_proxy_locked_on_thread = + LAZY_INSTANCE_INITIALIZER; + +// static +base::Lock* ProxyLock::Get() { + if (g_disable_locking || g_disable_locking_for_thread.Get().Get()) + return NULL; + return &g_proxy_lock.Get(); +} + +// Functions below should only access the lock via Get to ensure that they don't +// try to use the lock on the host side of the proxy, where locking is +// unnecessary and wrong (because we haven't coded the host side to account for +// locking). + +// static +void ProxyLock::Acquire() NO_THREAD_SAFETY_ANALYSIS { + // NO_THREAD_SAFETY_ANALYSIS: Runtime dependent locking. + base::Lock* lock = Get(); + if (lock) { + // This thread does not already hold the lock. + const bool deadlock = g_proxy_locked_on_thread.Get().Get(); + CHECK(!deadlock); + + lock->Acquire(); + g_proxy_locked_on_thread.Get().Set(true); + } +} + +// static +void ProxyLock::Release() NO_THREAD_SAFETY_ANALYSIS { + // NO_THREAD_SAFETY_ANALYSIS: Runtime dependent locking. + base::Lock* lock = Get(); + if (lock) { + // This thread currently holds the lock. + const bool locked = g_proxy_locked_on_thread.Get().Get(); + CHECK(locked); + + g_proxy_locked_on_thread.Get().Set(false); + lock->Release(); + } +} + +// static +void ProxyLock::AssertAcquired() { + base::Lock* lock = Get(); + if (lock) { + // This thread currently holds the lock. + const bool locked = g_proxy_locked_on_thread.Get().Get(); + CHECK(locked); + + lock->AssertAcquired(); + } +} + +// static +void ProxyLock::DisableLocking() { + // Note, we don't DCHECK that this flag isn't already set, because multiple + // unit tests may run in succession and all set it. + g_disable_locking = true; +} + +ProxyLock::LockingDisablerForTest::LockingDisablerForTest() { + // Note, we don't DCHECK that this flag isn't already set, because multiple + // unit tests may run in succession and all set it. + g_disable_locking_for_thread.Get().Set(true); +} + +ProxyLock::LockingDisablerForTest::~LockingDisablerForTest() { + g_disable_locking_for_thread.Get().Set(false); +} + +void CallWhileUnlocked(base::OnceClosure closure) { + ProxyAutoUnlock lock; + std::move(closure).Run(); +} + +} // namespace ppapi diff --git a/pool/shard007/C++/0092951_cache_fetcher.cpp b/pool/shard007/C++/0092951_cache_fetcher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f60ecd19a445a1426fd198c85de987919e28ff65 --- /dev/null +++ b/pool/shard007/C++/0092951_cache_fetcher.cpp @@ -0,0 +1,58 @@ +#include "cache_fetcher.hpp" + +namespace TrRouting +{ + + template<class T> + void CacheFetcher::saveToCapnpCacheFile(T& data, std::string cacheFilePath) { + std::ofstream oCacheFile; + oCacheFile.open(cacheFilePath, std::ios::out | std::ios::trunc | std::ios::binary); + oCacheFile.close(); + int fd = open(cacheFilePath.c_str(), O_WRONLY); + ::capnp::writePackedMessageToFd(fd, data); + close(fd); + } + + bool CacheFetcher::capnpCacheFileExists(std::string cacheFilePath) { + std::ifstream iCacheFile; + bool notEmpty = false; + iCacheFile.open(cacheFilePath); + notEmpty = iCacheFile.is_open(); + //std::cout << "capnpCacheFileExists: " << CacheFetcher::getFilePath(cacheFilePath, params, customPath) << " : " << (notEmpty ? "TRUE" : "FALSE") << std::endl; + iCacheFile.close(); + return notEmpty; + } + + int CacheFetcher::getCacheFilesCount(std::string cacheFilePath) { + std::ifstream iCacheFile; + iCacheFile.open(cacheFilePath); + std::string strCount; + int count {1}; + if (iCacheFile.is_open()) + { + iCacheFile >> count; + std::cout << cacheFilePath << " has " << count << " cache files" << std::endl; + } + iCacheFile.close(); + return count; + } + + std::string CacheFetcher::getFilePath(std::string cacheFilePath, Parameters& params, std::string customPath) { + std::string filePath = ""; + if (!params.cacheDirectoryPath.empty()) { + filePath += params.cacheDirectoryPath + "/"; + } + if (!params.projectShortname.empty()) { + filePath += params.projectShortname + "/"; + } + if (customPath.empty()) + { + return filePath + cacheFilePath; + } + else + { + return filePath + customPath + "/" + cacheFilePath; + } + } + +} diff --git a/pool/shard007/C++/0092954_texture_uploader_unittest.cc b/pool/shard007/C++/0092954_texture_uploader_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..07b1d999617437be4d6f1ea3bb5415215491b892 --- /dev/null +++ b/pool/shard007/C++/0092954_texture_uploader_unittest.cc @@ -0,0 +1,60 @@ +// 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. + +#include "mojo/gpu/texture_uploader.h" + +#include "base/bind.h" +#include "base/message_loop/message_loop.h" +#include "mojo/gpu/texture_cache.h" +#include "mojo/public/cpp/application/application_impl.h" +#include "mojo/public/cpp/application/application_test_base.h" +#include "mojo/public/cpp/application/connect.h" +#include "mojo/services/surfaces/public/interfaces/surface_id.mojom.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +class TextureUploaderTest : public mojo::test::ApplicationTestBase { + public: + TextureUploaderTest() : surface_id_(1u), weak_factory_(this) {} + ~TextureUploaderTest() override {} + + void SetUp() override { + mojo::test::ApplicationTestBase::SetUp(); + + mojo::ServiceProviderPtr surfaces_service_provider; + application_impl()->shell()->ConnectToApplication( + "mojo:surfaces_service", mojo::GetProxy(&surfaces_service_provider), + nullptr); + mojo::ConnectToService(surfaces_service_provider.get(), &surface_); + gl_context_ = mojo::GLContext::Create(application_impl()->shell()); + surface_->CreateSurface(surface_id_); + texture_cache_.reset(new mojo::TextureCache(gl_context_, nullptr)); + } + + void OnFrameCompleteExit() { base::MessageLoop::current()->Quit(); } + + protected: + uint32_t surface_id_; + base::WeakPtr<mojo::GLContext> gl_context_; + scoped_ptr<mojo::TextureCache> texture_cache_; + mojo::SurfacePtr surface_; + base::WeakPtrFactory<TextureUploaderTest> weak_factory_; + + private: + DISALLOW_COPY_AND_ASSIGN(TextureUploaderTest); +}; + +TEST_F(TextureUploaderTest, Base) { + mojo::Size size; + size.width = 100; + size.height = 100; + scoped_ptr<mojo::TextureCache::TextureInfo> texture_info( + texture_cache_->GetTexture(size).Pass()); + mojo::FramePtr frame = mojo::TextureUploader::GetUploadFrame( + gl_context_, texture_info->ResourceId(), texture_info->Texture()); + EXPECT_FALSE(frame.is_null()); +} + +} // namespace diff --git a/pool/shard007/C++/0092965_debugwidget.cpp b/pool/shard007/C++/0092965_debugwidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3875cc5738aaef491029a55c8d5d0030200518fc --- /dev/null +++ b/pool/shard007/C++/0092965_debugwidget.cpp @@ -0,0 +1,213 @@ +/* + This file is part of Akonadi. + + Copyright (c) 2006 Tobias Koenig <tokoe@kde.org> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + USA. +*/ + +#include "debugwidget.h" + +#include "tracernotificationinterface.h" +#include "connectionpage.h" + +#include <akonadi/control.h> + +#include <KFileDialog> +#include <KLocale> +#include <KTabWidget> +#include <KTextEdit> +#include <Akonadi/ServerManager> + +#include <QPushButton> +#include <QSplitter> +#include <QVBoxLayout> +#include <QCheckBox> + +using org::freedesktop::Akonadi::DebugInterface; + +DebugWidget::DebugWidget( QWidget *parent ) + : QWidget( parent ) +{ + QVBoxLayout *layout = new QVBoxLayout( this ); + + QString service = "org.freedesktop.Akonadi"; + if ( Akonadi::ServerManager::hasInstanceIdentifier() ) { + service += "." + Akonadi::ServerManager::instanceIdentifier(); + } + mDebugInterface = new DebugInterface( service, "/debug", QDBusConnection::sessionBus(), this ); + QCheckBox *cb = new QCheckBox( i18n("Enable debugger"), this ); + cb->setChecked( mDebugInterface->isValid() && mDebugInterface->tracer().value() == QLatin1String( "dbus" ) ); + connect( cb, SIGNAL(toggled(bool)), SLOT(enableDebugger(bool)) ); + layout->addWidget( cb ); + + QSplitter *splitter = new QSplitter( Qt::Vertical, this ); + splitter->setObjectName( "debugSplitter" ); + layout->addWidget( splitter ); + + mConnectionPages = new KTabWidget( splitter ); + mConnectionPages->setTabsClosable( true ); + + mGeneralView = new KTextEdit( splitter ); + mGeneralView->setReadOnly( true ); + + ConnectionPage *page = new ConnectionPage( "All" ); + page->showAllConnections( true ); + mConnectionPages->addTab( page, "All" ); + + connect( mConnectionPages, SIGNAL(tabCloseRequested(int)), SLOT(tabCloseRequested(int)) ); + + org::freedesktop::Akonadi::TracerNotification *iface = new org::freedesktop::Akonadi::TracerNotification( QString(), "/tracing/notifications", QDBusConnection::sessionBus(), this ); + + connect( iface, SIGNAL(connectionStarted(QString,QString)), + this, SLOT(connectionStarted(QString,QString)) ); + connect( iface, SIGNAL(connectionEnded(QString,QString)), + this, SLOT(connectionEnded(QString,QString)) ); + connect( iface, SIGNAL(signalEmitted(QString,QString)), + this, SLOT(signalEmitted(QString,QString)) ); + connect( iface, SIGNAL(warningEmitted(QString,QString)), + this, SLOT(warningEmitted(QString,QString)) ); + connect( iface, SIGNAL(errorEmitted(QString,QString)), + this, SLOT(errorEmitted(QString,QString)) ); + + // in case we started listening when the connection is already ongoing + connect( iface, SIGNAL(connectionDataInput(QString,QString)), + this, SLOT(connectionStarted(QString,QString)) ); + connect( iface, SIGNAL(connectionDataOutput(QString,QString)), + this, SLOT(connectionStarted(QString,QString)) ); + + QHBoxLayout *buttonLayout = new QHBoxLayout; + layout->addLayout( buttonLayout ); + + QPushButton *clearAllButton = new QPushButton( "Clear All Tabs", this ); + QPushButton *clearCurrentButton = new QPushButton( "Clear Current Tab", this ); + QPushButton *clearGeneralButton = new QPushButton( "Clear Information View", this ); + QPushButton *saveRichtextButton = new QPushButton( "Save as RichText...", this ); + + buttonLayout->addWidget( clearAllButton ); + buttonLayout->addWidget( clearCurrentButton ); + buttonLayout->addWidget( clearGeneralButton ); + buttonLayout->addWidget( saveRichtextButton ); + + connect( clearAllButton, SIGNAL(clicked()), this, SLOT(clearAllTabs()) ); + connect( clearCurrentButton, SIGNAL(clicked()), this, SLOT(clearCurrentTab()) ); + connect( clearGeneralButton, SIGNAL(clicked()), mGeneralView, SLOT(clear()) ); + connect( saveRichtextButton, SIGNAL(clicked()), this, SLOT(saveRichText()) ); + + Akonadi::Control::widgetNeedsAkonadi( this ); +} + +void DebugWidget::connectionStarted( const QString &identifier, const QString &msg ) +{ + Q_UNUSED( msg ); + if ( mPageHash.contains( identifier ) ) + return; + + ConnectionPage *page = new ConnectionPage( identifier ); + mConnectionPages->addTab( page, identifier ); + + mPageHash.insert( identifier, page ); +} + +void DebugWidget::connectionEnded( const QString &identifier, const QString& ) +{ + if ( !mPageHash.contains( identifier ) ) + return; + + QWidget *widget = mPageHash[ identifier ]; + + mConnectionPages->removeTab( mConnectionPages->indexOf( widget ) ); + + mPageHash.remove( identifier ); + delete widget; +} + +void DebugWidget::tabCloseRequested( int index ) +{ + if ( index != 0 ) { + QWidget *page = mConnectionPages->widget( index ); + QMutableHashIterator<QString, ConnectionPage*> it( mPageHash ); + while ( it.hasNext() ) { + it.next(); + if ( it.value() == page ) { + it.remove(); + break; + } + } + + mConnectionPages->removeTab( index ); + } +} + +void DebugWidget::clearAllTabs() +{ + ConnectionPage *page = qobject_cast<ConnectionPage*>( mConnectionPages->widget( 0 ) ); + if ( page ) + page->clear(); + + QMutableHashIterator<QString, ConnectionPage*> it( mPageHash ); + while ( it.hasNext() ) + it.next().value()->clear(); +} + +void DebugWidget::clearCurrentTab() +{ + ConnectionPage *page = qobject_cast<ConnectionPage*>( mConnectionPages->currentWidget() ); + if ( !page ) + return; + + page->clear(); +} + +void DebugWidget::signalEmitted( const QString &signalName, const QString &msg ) +{ + mGeneralView->append( QString( "<font color=\"green\">%1 ( %2 )</font>" ).arg( signalName, msg ) ); +} + +void DebugWidget::warningEmitted( const QString &componentName, const QString &msg ) +{ + mGeneralView->append( QString( "<font color=\"blue\">%1: %2</font>" ).arg( componentName, msg ) ); +} + +void DebugWidget::errorEmitted( const QString &componentName, const QString &msg ) +{ + mGeneralView->append( QString( "<font color=\"red\">%1: %2</font>" ).arg( componentName, msg ) ); +} + +void DebugWidget::enableDebugger(bool enable) +{ + mDebugInterface->setTracer( enable ? QLatin1String( "dbus" ) : QLatin1String( "null" ) ); +} + +void DebugWidget::saveRichText() +{ + ConnectionPage *page = qobject_cast<ConnectionPage*>( mConnectionPages->currentWidget() ); + if ( !page ) + return; + + const QString fileName = KFileDialog::getSaveFileName(); + if ( fileName.isEmpty() ) + return; + + QFile file( fileName ); + if ( !file.open( QIODevice::WriteOnly ) ) + return; + + file.write( page->toHtml().toUtf8() ); + file.close(); +} + +#include "debugwidget.moc" diff --git a/pool/shard007/C++/0092966_checkBST.cpp b/pool/shard007/C++/0092966_checkBST.cpp new file mode 100644 index 0000000000000000000000000000000000000000..db491ea12507be667f26acca533a5b2fa42167cf --- /dev/null +++ b/pool/shard007/C++/0092966_checkBST.cpp @@ -0,0 +1,85 @@ +#include <iostream> + +using namespace std; + +#define null 0 + +class node +{ + public: + int data; + node *left; + node *right; + node() + { + left=null; + right=null; + } +}; + +node *create_node(int data) +{ + node *temp=new node; + temp->data=data; + return temp; +} + +node *minimum(node *n) +{ + if(!(n->left)) + return n; + return minimum(n->left); +} + +node *maximum(node *n) +{ + if(!(n->right)) + return n; + return maximum(n->right); +} + +bool checkBST(node* root) +{ + //cout<<root->data<<" "; + if(!root->left && !root->right) //no children case + return true; + if(!root->right) //no right child + { + if(maximum(root->left)->data < root->data) + return checkBST(root->left); + return false; + } + if(!root->left) //no left child + { + if(minimum(root->right)->data > root->data) + return checkBST(root->right); + return false; + } + if(maximum(root->left)->data < root->data && minimum(root->right)->data > root->data) //two children case + return (checkBST(root->left) && checkBST(root->right)); + return false; +} + +int main() +{ + node *root=create_node(20); + root->left=create_node(15); + root->right=create_node(25); + root->left->left=create_node(10); + root->left->right=create_node(17); + root->right->right=create_node(40); + root->left->left->left=create_node(2); + root->left->left->right=create_node(12); + root->left->right->left=create_node(16); + root->left->right->right=create_node(18); + root->right->right->right=create_node(60); + root->right->right->right->left=create_node(55); + root->right->right->right->left->left=create_node(50); + if(checkBST(root)) + { + cout<<"YES"; + return 0; + } + cout<<"No"; + return 0; +} diff --git a/pool/shard007/C++/0092972_IPCV_BWSkel.cpp b/pool/shard007/C++/0092972_IPCV_BWSkel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..260d0fe6e5e5cf1b07e193db807048f5b661fd86 --- /dev/null +++ b/pool/shard007/C++/0092972_IPCV_BWSkel.cpp @@ -0,0 +1,229 @@ +///////////////////////////////////////////////////////////////////// +// // +// This function will use hit-or-miss morphology to // +// thin a given binary image. Function will continue // +// until there is no change in input and output images // +// // +// // +// File Name: calculateGVF.cpp // +// File Type: C++ source // +// Auther: Asanka Wickramasinghe // +// Project: Image Processing CV // +// Module: Image Processing Library (ImageProcCV) // +// Date Created: 2012 - Mar // +// // +///////////////////////////////////////////////////////////////////// +#include "ImageProcCV.h" + +void ImageProcCV::bwSkel(const cv::Mat _input, cv::Mat& _output) +{ + //Process input arrays into matrices with required parameters + //src and dst had to have same dimensions an same datatypes. + cv::Mat src = _input; + cv::Mat& dst = _output; + + dst = src.clone(); + cv::Mat intermediate = src.clone(); + + bool changesMade = true; + + while(changesMade) + { + changesMade = false; + for(int i= 0; i< intermediate.rows;i++) + { + uchar north,south,east,west,northeast,southeast,southwest,northwest; + //get the address of raq i + uchar *drow = intermediate.ptr<uchar>(i); + uchar *output = dst.ptr<uchar>(i); + //if (i != 0) + uchar *drow_above = intermediate.ptr<uchar>(i-1); + // if(i != (input.rows -1) ) + uchar *drow_below = intermediate.ptr<uchar>(i+1); + for(int j = 0; j< dst.cols; j++) + { + if (drow[j] != 0x00) + { + east = (j == (dst.cols - 1))? 0 : drow[j+1]; + north = (i == 0)? 0 : drow_above[j]; + west = (j == 0)? 0 : drow[j-1]; + south = (i == (dst.rows - 1))? 0 : drow_below[j]; + northeast = ((i == 0) || (j == (dst.cols - 1)))? 0 : drow_above[j+1]; + northwest = ((i == 0) || (j == 0))? 0 :drow_above[j-1]; + southwest = ((i == (dst.rows - 1)) || (j == 0))? 0 : drow_below[j-1]; + southeast = ((i == (dst.rows - 1)) || (j == (dst.cols - 1)))? 0 : drow_below[j+1]; + + /* check for kernel + + 0 0 0 + _ 1 _ + 1 1 1 + + */ + if(((north | northeast | northwest) == 0x00)&&((south & southeast & southwest) == 0xff ) ) + { + output[j]=0x00; + changesMade = true; + continue; + } + + /* check for kernel + + 1 _ 0 + 1 1 0 + 1 _ 0 + */ + else if(((west & southwest & northwest) == 0xff)&&((east | southeast | northeast) == 0x00 ) ) + { + output[j]=0x00; + changesMade = true; + continue; + } + + /* check for kernel + + 1 1 1 + _ 1 _ + 0 0 0 + */ + else if(((north & northeast & northwest) == 0xff)&&((south | southeast | southwest) == 0x00 ) ) + { + output[j]=0x00; + changesMade = true; + continue; + } + + /* check for kernel + + 0 _ 1 + 0 1 1 + 0 _ 1 + */ + else if(((west | southwest | northwest) == 0x00)&&((east & southeast & northeast) == 0xff ) ) + { + output[j]=0x00; + changesMade = true; + continue; + } + + /* check for kernel + + _ 0 0 + 1 1 0 + _ 1 _ + */ + //else if(((west & south & southwest) == 0xff)&&((east | north | northeast ) == 0x00 ) ) + else if(((west & south) == 0xff)&&((east | north | northeast ) == 0x00 ) ) + { + output[j]=0x00; + changesMade = true; + continue; + } + + /* check for kernel + + _ 1 _ + 1 1 0 + _ 0 0 + */ + //else if(((west & north & northwest) == 0xff)&&((east | south | southeast) == 0x00 ) ) + else if(((west & north) == 0xff)&&((east | south | southeast) == 0x00 ) ) + { + output[j]=0x00; + changesMade = true; + continue; + } + + /* check for kernel + + _ 1 _ + 0 1 1 + 0 0 _ + */ + //else if(((west | south | southwest) == 0x00 )&&((east & north & northeast) == 0xff ) ) + else if(((west | south | southwest) == 0x00 )&&((east & north) == 0xff ) ) + { + output[j]=0x00; + changesMade = true; + continue; + } + + /* check for kernel + + 0 0 _ + 0 1 1 + _ 1 _ + */ + //else if(((west | north | northwest ) == 0x00 )&&((east & south & southeast) == 0xff ) ) + else if(((west | north | northwest ) == 0x00 )&&((east & south) == 0xff ) ) + { + output[j]=0x00; + changesMade = true; + continue; + } + } + } + } + intermediate = dst; + + } + + //removing spurs + /* before_count = (int)valuesVector.size(); + after_count = 0 ; + + for(int i= 0; i<(int)valuesVector.size();i++) + { + uchar north,south,east,west,northeast,southeast,southwest,northwest; + int x,y; + x = valuesVector[i].x; + y = valuesVector[i].y; + + if(x==0 && y!=0)//boundry condition + { + north = dst.at<uchar>(y-1,x); + east = dst.at<uchar>(y,x+1); + west = 0xff; + south = dst.at<uchar>(y+1,x); + northeast = dst.at<uchar>(y-1,x+1); + southeast = dst.at<uchar>(y+1,x+1); + southwest = 0xff; + northwest = 0xff; + + } + if(x==0 && y!=0)//boundry condition + { + north = 0xff; + east = dst.at<uchar>(y,x+1); + west = dst.at<uchar>(y,x-1); + south = dst.at<uchar>(y+1,x); + northeast = 0xff; + southeast = dst.at<uchar>(y+1,x+1); + southwest = dst.at<uchar>(y+1,x-1); + northwest = 0xff; + + } + if(x!=0 && y!=0) + { + north = dst.at<uchar>(y-1,x); + east = dst.at<uchar>(y,x+1); + west = dst.at<uchar>(y,x-1); + south = dst.at<uchar>(y+1,x); + northeast = dst.at<uchar>(y-1,x+1); + southeast = dst.at<uchar>(y+1,x+1); + southwest = dst.at<uchar>(y+1,x-1); + northwest = dst.at<uchar>(y-1,x-1); + } + + + + } + cv::imshow("My Image",dst); + cv::waitKey(0); + + + + //cv::imshow("My Image",dst); + //cv::waitKey(0);*/ +} + diff --git a/pool/shard007/C++/0092988_WindowsEventEx.cpp b/pool/shard007/C++/0092988_WindowsEventEx.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f239bfcd68aac9c664c6f0e12e7ab663f74a131e --- /dev/null +++ b/pool/shard007/C++/0092988_WindowsEventEx.cpp @@ -0,0 +1,52 @@ +// Copyright (C) 2013 GlavSoft LLC. +// All rights reserved. +// +//------------------------------------------------------------------------- +// This file is part of the TightVNC software. Please visit our Web site: +// +// http://www.tightvnc.com/ +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//------------------------------------------------------------------------- +// + +#include "WindowsEventEx.h" +#include "util/Exception.h" +#include <Aclapi.h> + +WindowsEventEx::WindowsEventEx(const TCHAR *name) +: WindowsEvent(name) +{ + bool needToInit = GetLastError() != ERROR_ALREADY_EXISTS; + if (needToInit) { + setAccessToAll(getHandle()); + } +} + +void WindowsEventEx::setAccessToAll(HANDLE objHandle) +{ + DWORD errorCode = SetSecurityInfo(objHandle, SE_KERNEL_OBJECT, + DACL_SECURITY_INFORMATION, // Modify DACL + 0, + 0, + 0, // Pointer to DACL (0 = access to all) + 0); + if (errorCode != ERROR_SUCCESS && + errorCode != ERROR_NO_SECURITY_ON_OBJECT) { + StringStorage errMess; + errMess.format(_T("Cannot SetSecurityInfo with error = %d"), (int)errorCode); + throw Exception(errMess.getString()); + } +} diff --git a/pool/shard007/C++/0092995_EpochCache.cpp b/pool/shard007/C++/0092995_EpochCache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4134725485198dac4dabf281283df24aa40c7075 --- /dev/null +++ b/pool/shard007/C++/0092995_EpochCache.cpp @@ -0,0 +1,122 @@ +/*---------------------------------------------------------------------------- +* spp2pgs - Generates BluRay PG Stream from Subtitles or AviSynth scripts +* by Giton Xu <adm@subelf.net> +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see <http://www.gnu.org/licenses/>. +*----------------------------------------------------------------------------*/ + +#include "pch.h" +#include "EpochCache.h" + +namespace spp2pgs +{ + static inline unique_ptr<StreamEx> OpenTempFileWithSettings(S2PSettings const *settings) + { + return spp2pgs::OpenTempFile( + settings->TempOutputPath(), + settings->MaxCachingSize() + ); + } + + EpochCache::EpochCache(S2PContext const * context) + :S2PControllerBase(context), + tempFile(OpenTempFileWithSettings(context->Settings())) + { + } + + EpochCache::~EpochCache() + { + this->tempFile->Close(); + } + + CacheReceipt EpochCache::Write(Rect dataCrop, IndexedImage *image) + { + //Rect dataCrop = thumb->GetDataCrop(); + int imageSize = dataCrop.w * dataCrop.h; + + if (imageSize > 0 && !image->IsBlank()) + { + CacheReceipt receipt(tempFile->GetPosition()); + + int paletteSize = image->GetPaletteLength(); + Pixel32 *palette = image->GetPalette(); + char* imageData = image->GetDataBuffer(); + + DWORD toWrite = sizeof(paletteSize); + tempFile->Write(reinterpret_cast<byte*>(&paletteSize), 0, toWrite); + + toWrite = paletteSize * sizeof(Pixel32); + tempFile->Write(reinterpret_cast<byte*>(palette), 0, toWrite); + + toWrite = sizeof(imageSize); + tempFile->Write(reinterpret_cast<byte*>(&imageSize), 0, toWrite); + + int cropBottom = dataCrop.Bottom(); + toWrite = dataCrop.w; + for (int y = dataCrop.Top(); y < cropBottom; ++y) + { + char* line = imageData + y * image->GetStride(); + tempFile->Write(reinterpret_cast<byte*>(line), dataCrop.x, toWrite); + } + + return receipt; + } + else + { + return CacheReceipt(-1); + } + + } + + void EpochCache::Load(CacheReceipt receipt, Rect dataCrop, IndexedImage *image) + { + auto pos = receipt.GetPosition(); + + if (pos >= 0) + { + tempFile->SetPosition(pos); + + int paletteSize, imageSize; + DWORD toRead = sizeof(paletteSize); + tempFile->Read(reinterpret_cast<byte*>(&paletteSize), 0, toRead); + image->SetPaletteLength(paletteSize); + + Pixel32 *palette = image->GetPalette(); + char* imageData = image->GetDataBuffer(); + + toRead = paletteSize * sizeof(Pixel32); + tempFile->Read(reinterpret_cast<byte*>(palette), 0, toRead); + + toRead = sizeof(imageSize); + tempFile->Read(reinterpret_cast<byte*>(&imageSize), 0, toRead); + + assert(imageSize == dataCrop.Area()); + + int cropBottom = dataCrop.Bottom(); + toRead = dataCrop.w; + for (int y = dataCrop.Top(); y < cropBottom; ++y) + { + char* line = imageData + y * image->GetStride(); + tempFile->Read(reinterpret_cast<byte*>(line), dataCrop.x, toRead); + } + + image->AnnounceDirty(); + } + else + { + image->AnnounceBlank(); + } + } + +} \ No newline at end of file diff --git a/pool/shard007/C++/0092996_Arcc.cpp b/pool/shard007/C++/0092996_Arcc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..12e4eeda32dec5dfd466ec53076fab1d5377562e --- /dev/null +++ b/pool/shard007/C++/0092996_Arcc.cpp @@ -0,0 +1,64 @@ +/* + Arcc.cpp - Library for controller a RC Car. +*/ +#include "Arduino.h" +#include "Arcc.h" +// pins +const int STEERING_MOTOR_LEFT = 10; +const int STEERING_MOTOR_RIGHT = 9; +const int DRIVE_MOTOR_FORWARD = 5; +const int DRIVE_MOTOR_BACKWARD = 6; + +/** + * Arcc + * + * @constructor: The object for our RC car + */ +Arcc::Arcc() { + pinMode(STEERING_MOTOR_LEFT, OUTPUT); + pinMode(STEERING_MOTOR_RIGHT, OUTPUT); + pinMode(DRIVE_MOTOR_BACKWARD, OUTPUT); + pinMode(DRIVE_MOTOR_FORWARD, OUTPUT); +} + +/** + * Directions + * left + * right + * foward + * backward + * @param: {int} power 0 - 255 + */ +void Arcc::left(int power) { + int output = constrain(power, 0, 255); + analogWrite(STEERING_MOTOR_RIGHT, 0); + analogWrite(STEERING_MOTOR_LEFT, output); +} + +void Arcc::right(int power) { + int output = constrain(power, 0, 255); + analogWrite(STEERING_MOTOR_LEFT, 0); + analogWrite(STEERING_MOTOR_RIGHT, output); +} + +void Arcc::forward(int power) { + int output = constrain(power, 0, 255); + analogWrite(DRIVE_MOTOR_BACKWARD, 0); + analogWrite(DRIVE_MOTOR_FORWARD, output); +} + +void Arcc::backward(int power) { + int output = constrain(power, 0, 255); + analogWrite(DRIVE_MOTOR_FORWARD, 0); + analogWrite(DRIVE_MOTOR_BACKWARD, output); +} + +void Arcc::straight() { + analogWrite(STEERING_MOTOR_LEFT, 0); + analogWrite(STEERING_MOTOR_RIGHT, 0); +} + +void Arcc::stop() { + analogWrite(DRIVE_MOTOR_FORWARD, 0); + analogWrite(DRIVE_MOTOR_BACKWARD, 0); +} diff --git a/pool/shard007/C++/0093036_11173.cpp b/pool/shard007/C++/0093036_11173.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9af9f495b84e5d592ddec2fc48c211e4cbda0407 --- /dev/null +++ b/pool/shard007/C++/0093036_11173.cpp @@ -0,0 +1,29 @@ +#include <cstdio> +int main(){ + // freopen("in","r",stdin); + int T; scanf("%d",&T); + while(T--){ + int n,k; + scanf("%d %d",&n,&k); + + int ans = 0; + bool swap = false; + for(int i=30;i>=0;i--){ + if(not swap){ + if((1<<i)&k){ + ans += (1<<i); + swap = true; + } + }else{ + if(!((1<<i)&k)){ + ans += (1<<i); + swap = false; + }else{ + swap = true; + } + } + } + printf("%d\n",ans); + } + return 0; +} \ No newline at end of file diff --git a/pool/shard007/C++/0093039_Semaphore.cpp b/pool/shard007/C++/0093039_Semaphore.cpp new file mode 100644 index 0000000000000000000000000000000000000000..03387fe725bb864fe80cc3441879bb381b4439fc --- /dev/null +++ b/pool/shard007/C++/0093039_Semaphore.cpp @@ -0,0 +1,118 @@ +#include <AP_Common/AP_Common.h> +#include <AP_Math/AP_Math.h> +#include <AP_Param/AP_Param.h> +#include <AP_Progmem/AP_Progmem.h> + +#include <AP_HAL/AP_HAL.h> +#include <AP_HAL_AVR/AP_HAL_AVR.h> + +const AP_HAL::HAL& hal = AP_HAL::get_HAL(); + +/** + * You'll want to use a logic analyzer to watch the effects of this test. + * On the APM2 its pretty easy to hook up an analyzer to pins A0 through A3. + */ +#define PIN_A0 54 /* A0 */ +#define PIN_A1 55 /* A1 */ +#define PIN_A2 56 /* A2 */ +#define PIN_A3 57 /* A3 */ + +/** + * Create an AVRSemaphore for this test. + */ + +AP_HAL::Semaphore *sem; + +void blink_a0() { + volatile int i; + hal.gpio->write(PIN_A0, 1); + for (i = 0; i < 10; i++); + hal.gpio->write(PIN_A0, 0); +} + +void blink_a1() { + volatile int i; + hal.gpio->write(PIN_A1, 1); + for (i = 0; i < 10; i++); + hal.gpio->write(PIN_A1, 0); +} + + +void blink_a2() { + volatile int i; + hal.gpio->write(PIN_A2, 1); + for (i = 0; i < 10; i++); + hal.gpio->write(PIN_A2, 0); +} + +void blink_a3() { + volatile int i; + hal.gpio->write(PIN_A3, 1); + for (i = 0; i < 10; i++); + hal.gpio->write(PIN_A3, 0); +} + +void setup_pin(int pin_num) { + hal.console->printf_P(PSTR("Setup pin %d\r\n"), pin_num); + hal.gpio->pinMode(pin_num,HAL_GPIO_OUTPUT); + /* Blink so we can see setup on the logic analyzer.*/ + hal.gpio->write(pin_num,1); + hal.gpio->write(pin_num,0); +} + +void setup (void) { + hal.console->printf_P(PSTR("Starting Semaphore test\r\n")); + + setup_pin(PIN_A0); + setup_pin(PIN_A1); + setup_pin(PIN_A2); + setup_pin(PIN_A3); + + hal.console->printf_P(PSTR("Using Dataflash's Semaphore\r\n")); + + AP_HAL::SPIDeviceDriver *dataflash = hal.spi->device( + AP_HAL::SPIDevice_Dataflash); + + if (dataflash == NULL) { + hal.scheduler->panic(PSTR("Error: No SPIDevice_Dataflash driver!")); + } + + sem = dataflash->get_semaphore(); + if (sem == NULL) { + hal.scheduler->panic(PSTR("Error: No SPIDeviceDriver semaphore!")); + } + + hal.scheduler->register_timer_process(async_blinker, NULL); +} + + +static uint32_t async_last_run; + +void async_blinker(void *) +{ + uint32_t now = hal.scheduler->millis(); + if ((now - async_last_run) < 5) { + return; + } + async_last_run = now; + + if (sem->take_nonblocking()) { + blink_a0(); + sem->give(); + } else { + blink_a1(); + } +} + +void loop (void) { + + if (sem->take(1)) { + blink_a2(); + sem->give(); + } else { + /* This should never happen: */ + blink_a3(); + } +} + +AP_HAL_MAIN(); diff --git a/pool/shard007/C++/0093044_app_list_main_view.cc b/pool/shard007/C++/0093044_app_list_main_view.cc new file mode 100644 index 0000000000000000000000000000000000000000..e6f7a7c8a5db20c6cb9dd8b7b4d33284685ca124 --- /dev/null +++ b/pool/shard007/C++/0093044_app_list_main_view.cc @@ -0,0 +1,258 @@ +// Copyright 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 "ui/app_list/views/app_list_main_view.h" + +#include <algorithm> + +#include "base/bind.h" +#include "base/callback.h" +#include "base/files/file_path.h" +#include "base/message_loop/message_loop.h" +#include "base/strings/string_util.h" +#include "ui/app_list/app_list_constants.h" +#include "ui/app_list/app_list_folder_item.h" +#include "ui/app_list/app_list_item_model.h" +#include "ui/app_list/app_list_model.h" +#include "ui/app_list/app_list_view_delegate.h" +#include "ui/app_list/pagination_model.h" +#include "ui/app_list/search_box_model.h" +#include "ui/app_list/views/app_list_item_view.h" +#include "ui/app_list/views/contents_view.h" +#include "ui/app_list/views/search_box_view.h" +#include "ui/views/controls/textfield/textfield.h" +#include "ui/views/layout/box_layout.h" +#include "ui/views/widget/widget.h" + +namespace app_list { + +namespace { + +// Inner padding space in pixels of bubble contents. +const int kInnerPadding = 1; + +// The maximum allowed time to wait for icon loading in milliseconds. +const int kMaxIconLoadingWaitTimeInMs = 50; + +} // namespace + +//////////////////////////////////////////////////////////////////////////////// +// AppListMainView::IconLoader + +class AppListMainView::IconLoader : public AppListItemModelObserver { + public: + IconLoader(AppListMainView* owner, + AppListItemModel* item, + float scale) + : owner_(owner), + item_(item) { + item_->AddObserver(this); + + // Triggers icon loading for given |scale_factor|. + item_->icon().GetRepresentation(scale); + } + + virtual ~IconLoader() { + item_->RemoveObserver(this); + } + + private: + // AppListItemModelObserver overrides: + virtual void ItemIconChanged() OVERRIDE { + owner_->OnItemIconLoaded(this); + // Note that IconLoader is released here. + } + virtual void ItemTitleChanged() OVERRIDE {} + virtual void ItemHighlightedChanged() OVERRIDE {} + virtual void ItemIsInstallingChanged() OVERRIDE {} + virtual void ItemPercentDownloadedChanged() OVERRIDE {} + + AppListMainView* owner_; + AppListItemModel* item_; + + DISALLOW_COPY_AND_ASSIGN(IconLoader); +}; + +//////////////////////////////////////////////////////////////////////////////// +// AppListMainView: + +AppListMainView::AppListMainView(AppListViewDelegate* delegate, + PaginationModel* pagination_model, + gfx::NativeView parent) + : delegate_(delegate), + pagination_model_(pagination_model), + model_(delegate->GetModel()), + search_box_view_(NULL), + contents_view_(NULL), + weak_ptr_factory_(this) { + // Starts icon loading early. + PreloadIcons(parent); + + SetLayoutManager(new views::BoxLayout(views::BoxLayout::kVertical, + kInnerPadding, + kInnerPadding, + kInnerPadding)); + + search_box_view_ = new SearchBoxView(this, delegate); + AddChildView(search_box_view_); + AddContentsView(); +} + +void AppListMainView::AddContentsView() { + contents_view_ = + new ContentsView(this, + pagination_model_, + model_, + delegate_ ? delegate_->GetStartPageContents() : NULL); + AddChildView(contents_view_); + + search_box_view_->set_contents_view(contents_view_); + +#if defined(USE_AURA) + contents_view_->SetPaintToLayer(true); + contents_view_->SetFillsBoundsOpaquely(false); + contents_view_->layer()->SetMasksToBounds(true); +#endif +} + +AppListMainView::~AppListMainView() { + pending_icon_loaders_.clear(); +} + +void AppListMainView::ShowAppListWhenReady() { + if (pending_icon_loaders_.empty()) { + icon_loading_wait_timer_.Stop(); + GetWidget()->Show(); + return; + } + + if (icon_loading_wait_timer_.IsRunning()) + return; + + icon_loading_wait_timer_.Start( + FROM_HERE, + base::TimeDelta::FromMilliseconds(kMaxIconLoadingWaitTimeInMs), + this, &AppListMainView::OnIconLoadingWaitTimer); +} + +void AppListMainView::Close() { + icon_loading_wait_timer_.Stop(); + contents_view_->CancelDrag(); +} + +void AppListMainView::Prerender() { + contents_view_->Prerender(); +} + +void AppListMainView::ModelChanged() { + pending_icon_loaders_.clear(); + model_ = delegate_->GetModel(); + search_box_view_->ModelChanged(); + delete contents_view_; + contents_view_ = NULL; + pagination_model_->SelectPage(0, false /* animate */); + AddContentsView(); + Layout(); +} + +void AppListMainView::SetDragAndDropHostOfCurrentAppList( + ApplicationDragAndDropHost* drag_and_drop_host) { + contents_view_->SetDragAndDropHostOfCurrentAppList(drag_and_drop_host); +} + +void AppListMainView::PreloadIcons(gfx::NativeView parent) { + ui::ScaleFactor scale_factor = ui::SCALE_FACTOR_100P; + if (parent) + scale_factor = ui::GetScaleFactorForNativeView(parent); + + float scale = ui::GetImageScale(scale_factor); + // |pagination_model| could have -1 as the initial selected page and + // assumes first page (i.e. index 0) will be used in this case. + const int selected_page = std::max(0, pagination_model_->selected_page()); + + const int tiles_per_page = kPreferredCols * kPreferredRows; + const int start_model_index = selected_page * tiles_per_page; + const int end_model_index = std::min( + static_cast<int>(model_->item_list()->item_count()), + start_model_index + tiles_per_page); + + pending_icon_loaders_.clear(); + for (int i = start_model_index; i < end_model_index; ++i) { + AppListItemModel* item = model_->item_list()->item_at(i); + if (item->icon().HasRepresentation(scale)) + continue; + + pending_icon_loaders_.push_back(new IconLoader(this, item, scale)); + } +} + +void AppListMainView::OnIconLoadingWaitTimer() { + GetWidget()->Show(); +} + +void AppListMainView::OnItemIconLoaded(IconLoader* loader) { + ScopedVector<IconLoader>::iterator it = std::find( + pending_icon_loaders_.begin(), pending_icon_loaders_.end(), loader); + DCHECK(it != pending_icon_loaders_.end()); + pending_icon_loaders_.erase(it); + + if (pending_icon_loaders_.empty() && icon_loading_wait_timer_.IsRunning()) { + icon_loading_wait_timer_.Stop(); + GetWidget()->Show(); + } +} + +void AppListMainView::ActivateApp(AppListItemModel* item, int event_flags) { + // TODO(jennyz): Activate the folder via AppListModel notification. + if (item->GetAppType() == AppListFolderItem::kAppType) + contents_view_->ShowFolderContent(static_cast<AppListFolderItem*>(item)); + else + item->Activate(event_flags); +} + +void AppListMainView::GetShortcutPathForApp( + const std::string& app_id, + const base::Callback<void(const base::FilePath&)>& callback) { + delegate_->GetShortcutPathForApp(app_id, callback); +} + +void AppListMainView::QueryChanged(SearchBoxView* sender) { + base::string16 query; + TrimWhitespace(model_->search_box()->text(), TRIM_ALL, &query); + bool should_show_search = !query.empty(); + contents_view_->ShowSearchResults(should_show_search); + + if (should_show_search) + delegate_->StartSearch(); + else + delegate_->StopSearch(); +} + +void AppListMainView::OpenResult(SearchResult* result, int event_flags) { + delegate_->OpenSearchResult(result, event_flags); +} + +void AppListMainView::InvokeResultAction(SearchResult* result, + int action_index, + int event_flags) { + delegate_->InvokeSearchResultAction(result, action_index, event_flags); +} + +void AppListMainView::OnResultInstalled(SearchResult* result) { + // Clears the search to show the apps grid. The last installed app + // should be highlighted and made visible already. + search_box_view_->ClearSearch(); +} + +void AppListMainView::OnResultUninstalled(SearchResult* result) { + // Resubmit the query via a posted task so that all observers for the + // uninstall notification are notified. + base::MessageLoop::current()->PostTask( + FROM_HERE, + base::Bind(&AppListMainView::QueryChanged, + weak_ptr_factory_.GetWeakPtr(), + search_box_view_)); +} + +} // namespace app_list diff --git a/pool/shard007/C++/0093053_CWE762_Mismatched_Memory_Management_Routines__delete_array_class_malloc_62a.cpp b/pool/shard007/C++/0093053_CWE762_Mismatched_Memory_Management_Routines__delete_array_class_malloc_62a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..66dbd18e538e2b31fa47e305b55317691b153d01 --- /dev/null +++ b/pool/shard007/C++/0093053_CWE762_Mismatched_Memory_Management_Routines__delete_array_class_malloc_62a.cpp @@ -0,0 +1,106 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_class_malloc_62a.cpp +Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml +Template File: sources-sinks-62a.tmpl.cpp +*/ +/* + * @description + * CWE: 762 Mismatched Memory Management Routines + * BadSource: malloc Allocate data using malloc() + * GoodSource: Allocate data using new [] + * Sinks: + * GoodSink: Deallocate data using free() + * BadSink : Deallocate data using delete [] + * Flow Variant: 62 Data flow: data flows using a C++ reference from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_class_malloc_62 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSource(TwoIntsClass * &data); + +void bad() +{ + TwoIntsClass * data; + /* Initialize data*/ + data = NULL; + badSource(data); + /* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may + * require a call to free() to deallocate the memory */ + delete [] data; +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSource(TwoIntsClass * &data); + +static void goodG2B() +{ + TwoIntsClass * data; + /* Initialize data*/ + data = NULL; + goodG2BSource(data); + /* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may + * require a call to free() to deallocate the memory */ + delete [] data; +} + +/* goodB2G uses the BadSource with the GoodSink */ +void goodB2GSource(TwoIntsClass * &data); + +static void goodB2G() +{ + TwoIntsClass * data; + /* Initialize data*/ + data = NULL; + goodB2GSource(data); + /* FIX: Free memory using free() */ + free(data); +} + +void good() +{ + goodG2B(); + goodB2G(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +using namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_class_malloc_62; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard007/C++/0093055_Main.cpp b/pool/shard007/C++/0093055_Main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5b425003ddce98e60f3dc91daa0c2a6c9250fdfc --- /dev/null +++ b/pool/shard007/C++/0093055_Main.cpp @@ -0,0 +1,61 @@ +// Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt' + +#include "Engine/Scene/Impl/SceneObjectConstructor.h" +#include "Engine/Scene/Public/IDs.h" +#include "Engine/Scene/Public/Scene.h" +#include "Engine/Scene/Public/Surface.h" +#include "Engine/Scene/Public/Camera.h" + +namespace Engine +{ +namespace Scene +{ + +/* +================================================= + RegisterScene +================================================= +*/ + void RegisterScene () + { + using SOC = SceneObjectConstructor; + + auto factory = GetMainSystemInstance()->GlobalSystems()->modulesFactory; + + factory->Register( FreeCameraModuleID, &SOC::CreateFreeCamera ); + factory->Register( FreeVRCameraModuleID, &SOC::CreateFreeVRCamera ); + + factory->Register( WindowSurfaceModuleID, &SOC::CreateWindowSurface ); + factory->Register( VRSurfaceModuleID, &SOC::CreateVRSurface ); + + factory->Register( SceneManagerModuleID, &SOC::CreateSceneManager ); + factory->Register( SceneModuleID, &SOC::CreateSceneMainThread ); + factory->Register( SceneRendererModuleID, &SOC::CreateSceneRenderer ); + factory->Register( ScenePhysicsModuleID, &SOC::CreateScenePhysics ); + factory->Register( SceneLogicModuleID, &SOC::CreateSceneLogic ); + } + +/* +================================================= + UnregisterScene +================================================= +*/ + void UnregisterScene () + { + auto factory = GetMainSystemInstance()->GlobalSystems()->modulesFactory; + + factory->UnregisterAll( FreeCameraModuleID ); + factory->UnregisterAll( FreeVRCameraModuleID ); + + factory->UnregisterAll( WindowSurfaceModuleID ); + factory->UnregisterAll( VRSurfaceModuleID ); + + factory->UnregisterAll( SceneManagerModuleID ); + factory->UnregisterAll( SceneModuleID ); + factory->UnregisterAll( SceneRendererModuleID ); + factory->UnregisterAll( ScenePhysicsModuleID ); + factory->UnregisterAll( SceneLogicModuleID ); + } + +} // Scene +} // Engine diff --git a/pool/shard007/C++/0093060_VerboseTextConsole.manual.cpp b/pool/shard007/C++/0093060_VerboseTextConsole.manual.cpp new file mode 100644 index 0000000000000000000000000000000000000000..81b5a6363d8f9b6c591f042ba8f037eae9a05ca2 --- /dev/null +++ b/pool/shard007/C++/0093060_VerboseTextConsole.manual.cpp @@ -0,0 +1,49 @@ +#include <But/Log/Destination/VerboseTextConsole.hpp> +#include <But/Log/Field/Timestamp.hpp> +#include <But/Log/Field/LineNumber.hpp> +#include <But/Log/Field/Priority.hpp> +#include <But/Log/Field/FileName.hpp> +#include <But/Log/Destination/detail/args2FieldInfo.hpp> + +using But::Log::Backend::Tag; +using But::Log::Backend::FieldInfo; +using But::Log::Destination::detail::args2FieldInfo; +using Depth = But::Log::Destination::Common::VerboseTextStream::Depth; +using namespace But::Log::Field; + +struct Nested +{ + int value_; +}; + +inline auto toFieldInfo(Nested n) +{ + using But::Log::Backend::toFieldInfo; + return FieldInfo{ Tag{"Nested"}, { toFieldInfo(n.value_) } }; +} + + +struct DeeplyNested +{ + Nested nested_; +}; + +inline auto toFieldInfo(DeeplyNested dn) +{ + using But::Log::Backend::toFieldInfo; + return FieldInfo{ Tag{"DeeplyNested"}, { toFieldInfo(dn.nested_) } }; +} + + +int main() +{ + const auto nested = Nested{42}; + const auto deeplyNested = DeeplyNested{ nested }; + + But::Log::Destination::VerboseTextConsole c{ Depth{1} }; + c.log( args2FieldInfo( Timestamp{}, Priority::info, '@', FileName{__FILE__}, ':', LineNumber{__LINE__}, "full", nested ) ); + c.log( args2FieldInfo( Timestamp{}, Priority::info, '@', FileName{__FILE__}, ':', LineNumber{__LINE__}, "partial", deeplyNested ) ); + c.log( args2FieldInfo( FormattedString{"format test"}, "whatever..." ) ); + c.flush(); + c.reload(); +} diff --git a/pool/shard007/C++/0093061_TaskScheduler.cpp b/pool/shard007/C++/0093061_TaskScheduler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba8890c27041e4de4fe702cb5d66e1e2fb3056ae --- /dev/null +++ b/pool/shard007/C++/0093061_TaskScheduler.cpp @@ -0,0 +1,184 @@ +/* + * Copyright (C) 2016 John M. Harris, Jr. <johnmh@openblox.org> + * + * This file is part of OpenBlox. + * + * OpenBlox is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OpenBlox is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the Lesser GNU General Public License + * along with OpenBlox. If not, see <https://www.gnu.org/licenses/>. + */ + +#include "TaskScheduler.h" + +#include "OBEngine.h" + +#include "instance/RunService.h" + +#include <algorithm> + +#include "OBException.h" +#include "utility.h" + +namespace OB{ + TaskScheduler::TaskScheduler(OBEngine* eng){ + this->eng = eng; + + SortsTasks = true; + + numWaiting = 0; + } + + TaskScheduler::~TaskScheduler(){} + + bool operator==(const _ob_waiting_task& t1, const _ob_waiting_task& t2){ + return &t1 == &t2; + } + + bool TaskScheduler::GetSortsTasks(){ + return SortsTasks; + } + + void TaskScheduler::SetSortsTasks(bool sortsTasks){ + SortsTasks = sortsTasks; + } + + int TaskScheduler::GetNumSleepingJobs(){ + return tasks.size(); + } + + int TaskScheduler::GetNumWaitingJobs(){ + return numWaiting; + } + + void TaskScheduler::tick(){ + if(!tasks.empty()){ + /* This vector contains tasks that returned response code + * 1. These are pushed back onto the tasks vector after + * other tasks have been handled, or until a task returns + * an area code that marks the end of task handling for + * this tick. + */ + std::vector<_ob_waiting_task> tmpPopped; + + bool stopProcTasks = false; + + std::vector<_ob_waiting_task> runThisTick; + + ob_uint64 curTime = currentTimeMillis(); + while(!tasks.empty()){ + _ob_waiting_task t = tasks.back(); + + if(t.at < curTime){ + runThisTick.push_back(t); + tasks.pop_back(); + }else{ + break; + } + } + + numWaiting = runThisTick.size(); + + shared_ptr<Instance::RunService> rS = eng->getDataModel()->getRunService(); + + while(!runThisTick.empty() && !stopProcTasks){ + _ob_waiting_task t = runThisTick.back(); + runThisTick.pop_back(); + numWaiting--; + + if(t.getsPaused){ + if(!rS->IsRunning()){ + tmpPopped.push_back(t); + break; + } + } + + int retCode = t.task_fnc(t.metad, t.start); + + switch(retCode){ + case 1: { + tmpPopped.push_back(t); + break; + } + case 2: { + stopProcTasks = true; + break; + } + case 3: { + tmpPopped.push_back(t); + stopProcTasks = true; + break; + } + } + } + + if(!runThisTick.empty()){ + while(!runThisTick.empty()){ + tasks.push_back(runThisTick.back()); + runThisTick.pop_back(); + } + if(SortsTasks){ + sortTasks(); + } + } + + if(!tmpPopped.empty()){ + while(!tmpPopped.empty()){ + tasks.push_back(tmpPopped.back()); + tmpPopped.pop_back(); + } + if(SortsTasks){ + sortTasks(); + } + } + } + } + + void TaskScheduler::removeDMBound(){ + std::vector<_ob_waiting_task> tmpPopped; + while(!tasks.empty()){ + _ob_waiting_task t = tasks.back(); + + if(!t.dmBound){ + tmpPopped.push_back(t); + } + tasks.pop_back(); + } + + tasks = tmpPopped; + } + + void TaskScheduler::enqueue(ob_task_fnc fnc, void* metad, ob_uint64 at, bool getsPaused, bool dmBound){ + ob_uint64 curTime = currentTimeMillis(); + + _ob_waiting_task t; + t.start = curTime; + t.at = at; + t.metad = metad; + t.task_fnc = fnc; + t.getsPaused = getsPaused; + t.dmBound = dmBound; + + tasks.push_back(t); + + if(SortsTasks){ + sortTasks(); + } + } + + bool __ob_taskscheduler_sort_cmp(const _ob_waiting_task& t1, const _ob_waiting_task& t2){ + return t1.at > t2.at; + } + + void TaskScheduler::sortTasks(){ + std::sort(tasks.begin(), tasks.end(), __ob_taskscheduler_sort_cmp); + } +} diff --git a/pool/shard007/C++/0093062_boss_curator.cpp b/pool/shard007/C++/0093062_boss_curator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..55c9cf2baa2b7dbc0f13d5b5782d20682910847b --- /dev/null +++ b/pool/shard007/C++/0093062_boss_curator.cpp @@ -0,0 +1,212 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +/* ScriptData +SDName: Boss_Curator +SD%Complete: 100 +SDComment: +SDCategory: Karazhan +EndScriptData */ + +#include "ScriptMgr.h" +#include "ScriptedCreature.h" + +enum Curator +{ + SAY_AGGRO = 0, + SAY_SUMMON = 1, + SAY_EVOCATE = 2, + SAY_ENRAGE = 3, + SAY_KILL = 4, + SAY_DEATH = 5, + + //Flare spell info + SPELL_ASTRAL_FLARE_PASSIVE = 30234, //Visual effect + Flare damage + + //Curator spell info + SPELL_HATEFUL_BOLT = 30383, + SPELL_EVOCATION = 30254, + SPELL_ENRAGE = 30403, //Arcane Infusion: Transforms Curator and adds damage. + SPELL_BERSERK = 26662, +}; + + + + +class boss_curator : public CreatureScript +{ +public: + boss_curator() : CreatureScript("boss_curator") { } + + CreatureAI* GetAI(Creature* creature) const override + { + return new boss_curatorAI(creature); + } + + struct boss_curatorAI : public ScriptedAI + { + boss_curatorAI(Creature* creature) : ScriptedAI(creature) + { + Initialize(); + } + + void Initialize() + { + AddTimer = 10000; + HatefulBoltTimer = 15000; //This time may be wrong + BerserkTimer = 720000; //12 minutes + Enraged = false; + Evocating = false; + } + + uint32 AddTimer; + uint32 HatefulBoltTimer; + uint32 BerserkTimer; + + bool Enraged; + bool Evocating; + + void Reset() override + { + Initialize(); + + me->ApplySpellImmune(0, IMMUNITY_DAMAGE, SPELL_SCHOOL_MASK_ARCANE, true); + } + + void KilledUnit(Unit* /*victim*/) override + { + Talk(SAY_KILL); + } + + void JustDied(Unit* /*killer*/) override + { + Talk(SAY_DEATH); + } + + void EnterCombat(Unit* /*who*/) override + { + Talk(SAY_AGGRO); + } + + void UpdateAI(uint32 diff) override + { + if (!UpdateVictim()) + return; + + //always decrease BerserkTimer + if (BerserkTimer <= diff) + { + //if evocate, then break evocate + if (Evocating) + { + if (me->HasAura(SPELL_EVOCATION)) + me->RemoveAurasDueToSpell(SPELL_EVOCATION); + + Evocating = false; + } + + //may not be correct SAY (generic hard enrage) + Talk(SAY_ENRAGE); + + me->InterruptNonMeleeSpells(true); + DoCast(me, SPELL_BERSERK); + + //don't know if he's supposed to do summon/evocate after hard enrage (probably not) + Enraged = true; + } else BerserkTimer -= diff; + + if (Evocating) + { + //not supposed to do anything while evocate + if (me->HasAura(SPELL_EVOCATION)) + return; + else + Evocating = false; + } + + if (!Enraged) + { + if (AddTimer <= diff) + { + //Summon Astral Flare + Creature* AstralFlare = DoSpawnCreature(17096, float(rand32() % 37), float(rand32() % 37), 0, 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 5000); + Unit* target = NULL; + target = SelectTarget(SELECT_TARGET_RANDOM, 0); + + if (AstralFlare && target) + { + AstralFlare->CastSpell(AstralFlare, SPELL_ASTRAL_FLARE_PASSIVE, false); + AstralFlare->AI()->AttackStart(target); + } + + //Reduce Mana by 10% of max health + if (int32 mana = me->GetMaxPower(POWER_MANA)) + { + mana /= 10; + me->ModifyPower(POWER_MANA, -mana); + + //if this get's us below 10%, then we evocate (the 10th should be summoned now) + if (me->GetPower(POWER_MANA)*100 / me->GetMaxPower(POWER_MANA) < 10) + { + Talk(SAY_EVOCATE); + me->InterruptNonMeleeSpells(false); + DoCast(me, SPELL_EVOCATION); + Evocating = true; + //no AddTimer cooldown, this will make first flare appear instantly after evocate end, like expected + return; + } + else + { + if (urand(0, 1) == 0) + { + Talk(SAY_SUMMON); + } + } + } + + AddTimer = 10000; + } else AddTimer -= diff; + + if (!HealthAbovePct(15)) + { + Enraged = true; + DoCast(me, SPELL_ENRAGE); + Talk(SAY_ENRAGE); + } + } + + if (HatefulBoltTimer <= diff) + { + if (Enraged) + HatefulBoltTimer = 7000; + else + HatefulBoltTimer = 15000; + + if (Unit* target = SelectTarget(SELECT_TARGET_TOPAGGRO, 1)) + DoCast(target, SPELL_HATEFUL_BOLT); + } else HatefulBoltTimer -= diff; + + DoMeleeAttackIfReady(); + } + }; +}; + +void AddSC_boss_curator() +{ + new boss_curator(); +} diff --git a/pool/shard007/C++/0093065_libSensor.cpp b/pool/shard007/C++/0093065_libSensor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3676ba8804bf89777ac969a598ee6ffdf6cb8ef4 --- /dev/null +++ b/pool/shard007/C++/0093065_libSensor.cpp @@ -0,0 +1,85 @@ +#include <stdint.h> +#include <wiringPi.h> +#include <wiringPiI2C.h> +#include "libSensor.h" +#include <stdio.h> +#include <cmath> + +#define MPU6050_GYRO_XOUT_H 0x43 // R +#define MPU6050_GYRO_YOUT_H 0x45 // R +#define MPU6050_GYRO_ZOUT_H 0x47 // R + +#define MPU6050_ACCEL_XOUT_H 0x3B // R +#define MPU6050_ACCEL_YOUT_H 0x3D // R +#define MPU6050_ACCEL_ZOUT_H 0x3F // R + +#define MPU6050_PWR_MGMT_1 0x6B // R/W +#define MPU6050_I2C_ADDRESS 0x68 // I2C + +Sensor::Sensor() +{ + fd = wiringPiI2CSetup(MPU6050_I2C_ADDRESS); + if (fd == -1) + return; + + wiringPiI2CReadReg8 (fd, MPU6050_PWR_MGMT_1); + wiringPiI2CWriteReg16(fd, MPU6050_PWR_MGMT_1, 0); +} + +int8_t Sensor::getGyroX() +{ + return (int8_t) wiringPiI2CReadReg8(fd, MPU6050_GYRO_XOUT_H); +} + +int8_t Sensor::getGyroY() +{ + return (int8_t) wiringPiI2CReadReg8(fd, MPU6050_GYRO_YOUT_H); +} + +int8_t Sensor::getGyroZ() +{ + return (int8_t) wiringPiI2CReadReg8(fd, MPU6050_GYRO_ZOUT_H); +} + +int8_t Sensor::getAccelX() +{ + return (int8_t) wiringPiI2CReadReg8(fd, MPU6050_ACCEL_XOUT_H); +} + +int8_t Sensor::getAccelY() +{ + return (int8_t) wiringPiI2CReadReg8(fd, MPU6050_ACCEL_YOUT_H); +} + +int8_t Sensor::getAccelZ() +{ + return (int8_t) wiringPiI2CReadReg8(fd, MPU6050_ACCEL_ZOUT_H); +} + +float Sensor::getAngleX() +{ + int x = getAccelX(); + int y = getAccelY(); + int z = getAccelZ(); + float ax = atan(x/(sqrt(y*y+z*z)))* 180/M_PI; + return ax; +} + +float Sensor::getAngleY() +{ + int x = getAccelX(); + int y = getAccelY(); + int z = getAccelZ(); + float ay = atan(y/(sqrt(x*x+z*z)))* 180/M_PI; + return ay; +} + +float Sensor::getAngleZ() +{ + int x = getAccelX(); + int y = getAccelY(); + int z = getAccelZ(); + float az = atan((sqrt(y*y+x*x))/z)* 180/M_PI; + return az; +} + diff --git a/pool/shard007/C++/0093069_psitiplabel.cpp b/pool/shard007/C++/0093069_psitiplabel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d827c1232f74eb20a9e49dc8950cb35637a642fa --- /dev/null +++ b/pool/shard007/C++/0093069_psitiplabel.cpp @@ -0,0 +1,241 @@ +#include "psitiplabel.h" + +#include <QApplication> +#include <QAbstractTextDocumentLayout> +#include <QTextFrame> +#include <QStyle> +#include <QStyleOption> +#include <QStylePainter> +#include <QTimer> +#include <QToolTip> +#include <QTextEdit> + +#include "psirichtext.h" + +PsiTipLabel *PsiTipLabel::instance_ = 0; + +PsiTipLabel* PsiTipLabel::instance() +{ + return instance_; +} + +PsiTipLabel::PsiTipLabel(QWidget* parent) + : QFrame(parent, Qt::ToolTip) + , doc(0) +{ + delete instance_; + instance_ = this; +} + +void PsiTipLabel::init(const QString& text) +{ + setText(text); + initUi(); + resize(sizeHint()); + qApp->installEventFilter(this); + startHideTimer(); + setWindowOpacity(style()->styleHint(QStyle::SH_ToolTipLabel_Opacity, 0, this) / 255.0); + setPalette(QToolTip::palette()); +} + +void PsiTipLabel::setText(const QString& text) +{ + theText_ = text; + isRichText = false; + if (doc) { + if (Qt::mightBeRichText(theText_)) { + isRichText = true; + PsiRichText::install(doc); + PsiRichText::setText(doc, theText_); + } + else { + doc->setPlainText(theText_); + } + } +} + +void PsiTipLabel::initUi() +{ + margin = 1 + style()->pixelMetric(QStyle::PM_ToolTipLabelFrameWidth, 0, this); + setFrameStyle(QFrame::NoFrame); + + // doc = new QTextDocument(this); + // QTextDocumentLayout is private in Qt4 + // and it's impossible to set wrapping mode directly. + // So we create this QTextEdit instance and use its QTextDocument, + // just because QTextEdit can set the wrapping mode. + // Yes, this is crazy... + QTextEdit *edit = new QTextEdit(this); + edit->hide(); + edit->setWordWrapMode(QTextOption::WordWrap); + doc = edit->document(); + doc->setUndoRedoEnabled(false); + doc->setDefaultFont(font()); + + ensurePolished(); + setText(theText_); +} + +void PsiTipLabel::startHideTimer() +{ + hideTimer.start(10000, this); +} + +QString PsiTipLabel::theText() const +{ + return theText_; +} +/* +QSize PsiTipLabel::sizeForWidth(int w) const +{ + QRect br; + + int hextra = 2 * margin; + int vextra = hextra; + + if (isRichText) { + hextra = 1; + vextra = 1; + } + + PsiRichText::ensureTextLayouted(doc, w); + const qreal oldTextWidth = doc->textWidth(); + + doc->adjustSize(); + br = QRect(QPoint(0, 0), doc->size().toSize()); + doc->setTextWidth(oldTextWidth); + + QFontMetrics fm(font()); + QSize extra(hextra + 1, vextra); + + // Make it look good with the default ToolTip font on Mac, which has a small descent. + if (fm.descent() == 2 && fm.ascent() >= 11) + vextra++; + + const QSize contentsSize(br.width() + hextra, br.height() + vextra); + return contentsSize; +} +*/ +QSize PsiTipLabel::sizeHint() const +{ + QTextFrameFormat fmt = doc->rootFrame()->frameFormat(); + fmt.setMargin(0); + doc->rootFrame()->setFrameFormat(fmt); + // PsiRichText::ensureTextLayouted(doc, -1); + + doc->adjustSize(); + // br = QRect(QPoint(0, 0), doc->size().toSize()); + // this way helps to fight empty space on the right: + QSize docSize = QSize(static_cast<int>(doc->idealWidth()), doc->size().toSize().height()); + + QFontMetrics fm(font()); + QSize extra(2*margin + 2, 2*margin + 1); // "+" for tip's frame + // Make it look good with the default ToolTip font on Mac, which has a small descent. + if (fm.descent() == 2 && fm.ascent() >= 11) + ++extra.rheight(); + + return docSize + extra; +} + +QSize PsiTipLabel::minimumSizeHint() const +{ + return sizeHint(); + // qWarning("PsiTipLabel::minimumSizeHint"); + // ensurePolished(); + // QSize sh = sizeForWidth(-1); + // QSize msh(-1, -1); + // + // msh.rheight() = sizeForWidth(QWIDGETSIZE_MAX).height(); // height for one line + // msh.rwidth() = sizeForWidth(0).width(); // wrap ? size of biggest word : min doc size + // if (sh.height() < msh.height()) + // msh.rheight() = sh.height(); + // + // return msh; +} + +void PsiTipLabel::paintEvent(QPaintEvent *) +{ + QStylePainter p(this); + QStyleOptionFrame opt; + opt.init(this); + p.drawPrimitive(QStyle::PE_PanelTipLabel, opt); + p.end(); + + // stolen from QLabel::paintEvent + QPainter painter(this); + drawFrame(&painter); + QRect cr = contentsRect(); + cr.adjust(margin, margin, -margin, -margin); + + PsiRichText::ensureTextLayouted(doc, width() - 2*margin); + QAbstractTextDocumentLayout *layout = doc->documentLayout(); + // QRect lr = rect(); + QRect lr = cr; + + QAbstractTextDocumentLayout::PaintContext context; + + // Adjust the palette + context.palette = palette(); + if (foregroundRole() != QPalette::Text && isEnabled()) + context.palette.setColor(QPalette::Text, context.palette.color(foregroundRole())); + + painter.save(); + painter.translate(lr.x() + 1, lr.y() + 1); + painter.setClipRect(lr.translated(-lr.x() - 1, -lr.y() - 1)); + layout->draw(&painter, context); + painter.restore(); +} + +PsiTipLabel::~PsiTipLabel() +{ + instance_ = 0; +} + +void PsiTipLabel::hideTip() +{ + hide(); + // timer based deletion to prevent animation + deleteTimer.start(250, this); +} + +void PsiTipLabel::enterEvent(QEvent*) +{ + hideTip(); +} + +void PsiTipLabel::timerEvent(QTimerEvent *e) +{ + if (e->timerId() == hideTimer.timerId()) + hideTip(); + else if (e->timerId() == deleteTimer.timerId()) + deleteLater(); +} + +bool PsiTipLabel::eventFilter(QObject *, QEvent *e) +{ + switch (e->type()) { + case QEvent::KeyPress: + case QEvent::KeyRelease: { + int key = static_cast<QKeyEvent *>(e)->key(); + Qt::KeyboardModifiers mody = static_cast<QKeyEvent *>(e)->modifiers(); + + if ((mody & Qt::KeyboardModifierMask) + || (key == Qt::Key_Shift || key == Qt::Key_Control + || key == Qt::Key_Alt || key == Qt::Key_Meta)) + break; + } + case QEvent::Leave: + case QEvent::WindowActivate: + case QEvent::WindowDeactivate: + case QEvent::MouseButtonPress: + case QEvent::MouseButtonRelease: + case QEvent::MouseButtonDblClick: + case QEvent::FocusIn: + case QEvent::FocusOut: + case QEvent::Wheel: + hideTip(); + default: + ; + } + return false; +} diff --git a/pool/shard007/C++/0093072_equal.cc b/pool/shard007/C++/0093072_equal.cc new file mode 100644 index 0000000000000000000000000000000000000000..3671a3aac3996eb8a4aafa3f0563cca3531a84aa --- /dev/null +++ b/pool/shard007/C++/0093072_equal.cc @@ -0,0 +1,48 @@ +// 2006-08-22 Paolo Carlini <pcarlini@suse.de> +// +// Copyright (C) 2006-2017 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// <http://www.gnu.org/licenses/>. + +// 5.1.4.4 class template subtract_with_carry_01 [tr.rand.eng.sub1] +// 5.1.1 Table 16 + +#include <tr1/random> +#include <testsuite_hooks.h> + +void +test01() +{ + using namespace std::tr1; + + subtract_with_carry_01<float, 24, 10, 24> u; + subtract_with_carry_01<float, 24, 10, 24> v; + + VERIFY( u == v ); + + for (int i = 0; i < 100; ++i) + { + u(); + v(); + } + VERIFY( u == v ); +} + +int main() +{ + test01(); + return 0; +} diff --git a/pool/shard007/C++/0093075_MSDoppler.cc b/pool/shard007/C++/0093075_MSDoppler.cc new file mode 100644 index 0000000000000000000000000000000000000000..e2bc131bfa18ce6000909ed177440ffb45ec7ece --- /dev/null +++ b/pool/shard007/C++/0093075_MSDoppler.cc @@ -0,0 +1,200 @@ +//# MSDoppler.cc: The MeasurementSet DOPPLER Table +//# Copyright (C) 1999,2000 +//# Associated Universities, Inc. Washington DC, USA. +//# +//# This library is free software; you can redistribute it and/or modify it +//# under the terms of the GNU Library General Public License as published by +//# the Free Software Foundation; either version 2 of the License, or (at your +//# option) any later version. +//# +//# This library is distributed in the hope that it will be useful, but WITHOUT +//# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +//# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public +//# License for more details. +//# +//# You should have received a copy of the GNU Library General Public License +//# along with this library; if not, write to the Free Software Foundation, +//# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA. +//# +//# Correspondence concerning AIPS++ should be addressed as follows: +//# Internet email: aips2-request@nrao.edu. +//# Postal address: AIPS++ Project Office +//# National Radio Astronomy Observatory +//# 520 Edgemont Road +//# Charlottesville, VA 22903-2475 USA +//# +//# $Id$ + +#include <casacore/ms/MeasurementSets/MSDoppler.h> + +#include <casacore/casa/BasicSL/String.h> +#include <casacore/tables/Tables/SetupNewTab.h> +#include <casacore/tables/Tables/TableDesc.h> +#include <casacore/tables/Tables/ColDescSet.h> +#include <casacore/tables/Tables/ScaColDesc.h> +#include <casacore/tables/Tables/ScalarColumn.h> +#include <casacore/tables/Tables/ArrColDesc.h> +#include <casacore/tables/DataMan/StManAipsIO.h> +#include <casacore/tables/DataMan/ForwardCol.h> +#include <casacore/casa/Arrays/Vector.h> +#include <casacore/casa/Logging/LogIO.h> +#include <casacore/casa/Exceptions/Error.h> + +namespace casacore { //# NAMESPACE CASACORE - BEGIN + +MSDoppler::MSDoppler():hasBeenDestroyed_p(True) { } + +MSDoppler::MSDoppler(const String &tableName, + TableOption option) + : MSTable<PredefinedColumns, + PredefinedKeywords>(tableName, option),hasBeenDestroyed_p(False) +{ + // verify that the now opened table is valid + addVelDef(); + if (! validate(this->tableDesc())) + throw (AipsError("MSDoppler(String &, TableOption) - " + "table is not a valid MSDoppler")); +} + +void MSDoppler::addVelDef() +{ + // For a transition period: add the VELDEF column + // silently if it is not there - 2000/09/12, remove next MS update. + if (tableDesc().isColumn(columnName(TRANSITION_ID))) { + // we probably have a MSDoppler table + if (!tableDesc().isColumn(columnName(VELDEF))) { + if (!isWritable()) { + throw (AipsError("Missing VELDEF column in MSDoppler table -" + "please open MS table R/W to have it added")); + } else { + TableDesc td; + addColumnToDesc(td,VELDEF); + addColumn(td[0]); + ScalarColumn<Double> velDef(*this,columnName(VELDEF)); + velDef.fillColumn(0); + } + } + } +} + +MSDoppler::MSDoppler(const String& tableName, const String &tableDescName, + TableOption option) + : MSTable<PredefinedColumns, + PredefinedKeywords>(tableName, tableDescName,option), + hasBeenDestroyed_p(False) +{ + // verify that the now opened table is valid + addVelDef(); + if (! validate(this->tableDesc())) + throw (AipsError("MSDoppler(String &, String &, TableOption) - " + "table is not a valid MSDoppler")); +} + +MSDoppler::MSDoppler(SetupNewTable &newTab, uInt nrrow, + Bool initialize) + : MSTable<PredefinedColumns, + PredefinedKeywords>(newTab, nrrow, initialize), + hasBeenDestroyed_p(False) +{ + // verify that the now opened table is valid + addVelDef(); + if (! validate(this->tableDesc())) + throw (AipsError("MSDoppler(SetupNewTable &, uInt, Bool) - " + "table is not a valid MSDoppler")); +} + +MSDoppler::MSDoppler(const Table &table) + : MSTable<PredefinedColumns, + PredefinedKeywords>(table), hasBeenDestroyed_p(False) +{ + // verify that the now opened table is valid + addVelDef(); + if (! validate(this->tableDesc())) + throw (AipsError("MSDoppler(const Table &) - " + "table is not a valid MSDoppler")); +} + +MSDoppler::MSDoppler(const MSDoppler &other) + : MSTable<PredefinedColumns, + PredefinedKeywords>(other), + hasBeenDestroyed_p(False) +{ + // verify that other is valid + if (&other != this) + addVelDef(); + if (! validate(this->tableDesc())) + throw (AipsError("MSDoppler(const MSDoppler &) - " + "table is not a valid MSDoppler")); +} + +MSDoppler::~MSDoppler() +{ +// check to make sure that this MSDoppler is still valid + if (!hasBeenDestroyed_p && !validate()) { + // the table is otherwise OK, so ensure that it is written if necessary + this->flush(); + LogIO os; + os << LogIO::WARN + << "~MSDoppler() - Table written is not a valid MSDoppler" + << LogIO::POST; + } + hasBeenDestroyed_p = True; +} + + +MSDoppler& MSDoppler::operator=(const MSDoppler &other) +{ + if (&other != this) { + MSTable<PredefinedColumns, + PredefinedKeywords>::operator=(other); + hasBeenDestroyed_p=other.hasBeenDestroyed_p; + } + return *this; +} + +void MSDoppler::init() +{ + if (! columnMap_p.ndefined()) { + // the PredefinedColumns + // + colMapDef(DOPPLER_ID,"DOPPLER_ID", TpInt, + "Doppler tracking id","",""); + // SOURCE_ID + colMapDef(SOURCE_ID, "SOURCE_ID", TpInt, + "Pointer to SOURCE table","",""); + // TRANSITION_ID + colMapDef(TRANSITION_ID,"TRANSITION_ID",TpInt, + "Pointer to list of transitions in SOURCE table","",""); + // VELDEF + colMapDef(VELDEF, "VELDEF", TpDouble, + "Velocity Definition for Doppler shift","m/s","Doppler"); + // PredefinedKeywords + + // init requiredTableDesc + TableDesc requiredTD; + // all required keywords + uInt i; + for (i = UNDEFINED_KEYWORD+1; + i <= NUMBER_PREDEFINED_KEYWORDS; i++) { + addKeyToDesc(requiredTD, PredefinedKeywords(i)); + } + + // all required columns + for (i = UNDEFINED_COLUMN+1; + i <= NUMBER_REQUIRED_COLUMNS; i++) { + addColumnToDesc(requiredTD, PredefinedColumns(i)); + } + requiredTD_p=new TableDesc(requiredTD); + } +} + + +MSDoppler MSDoppler::referenceCopy(const String& newTableName, + const Block<String>& writableColumns) const +{ + return MSDoppler(MSTable<PredefinedColumns,PredefinedKeywords>:: + referenceCopy(newTableName,writableColumns)); +} + +} //# NAMESPACE CASACORE - END + diff --git a/pool/shard007/C++/0093082_packet_queue.cc b/pool/shard007/C++/0093082_packet_queue.cc new file mode 100644 index 0000000000000000000000000000000000000000..7649fe5a6198a167c494db28f9987a32a101449f --- /dev/null +++ b/pool/shard007/C++/0093082_packet_queue.cc @@ -0,0 +1,278 @@ +/* + * Copyright (c) 2012,2015 ARM Limited + * All rights reserved. + * + * The license below extends only to copyright in the software and shall + * not be construed as granting a license to any other intellectual + * property including but not limited to intellectual property relating + * to a hardware implementation of the functionality of the software + * licensed hereunder. You may use the software subject to the license + * terms below provided that you ensure that this notice is replicated + * unmodified and in its entirety in all distributions of the software, + * modified or unmodified, in source code or in binary form. + * + * Copyright (c) 2006 The Regents of The University of Michigan + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer; + * redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution; + * neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Authors: Ali Saidi + * Andreas Hansson + */ + +#include "mem/packet_queue.hh" + +#include "base/trace.hh" +#include "debug/Drain.hh" +#include "debug/PacketQueue.hh" + +using namespace std; + +PacketQueue::PacketQueue(EventManager& _em, const std::string& _label, + const std::string& _sendEventName, + bool disable_sanity_check) + : em(_em), sendEvent([this]{ processSendEvent(); }, _sendEventName), + _disableSanityCheck(disable_sanity_check), + label(_label), waitingOnRetry(false) +{ +} + +PacketQueue::~PacketQueue() +{ +} + +void +PacketQueue::retry() +{ + DPRINTF(PacketQueue, "Queue %s received retry\n", name()); + assert(waitingOnRetry); + waitingOnRetry = false; + sendDeferredPacket(); +} + +bool +PacketQueue::hasAddr(Addr addr) const +{ + // caller is responsible for ensuring that all packets have the + // same alignment + for (const auto& p : transmitList) { + if (p.pkt->getAddr() == addr) + return true; + } + return false; +} + +bool +PacketQueue::checkFunctional(PacketPtr pkt) +{ + pkt->pushLabel(label); + + auto i = transmitList.begin(); + bool found = false; + + while (!found && i != transmitList.end()) { + // If the buffered packet contains data, and it overlaps the + // current packet, then update data + found = pkt->checkFunctional(i->pkt); + ++i; + } + + pkt->popLabel(); + + return found; +} + +void +PacketQueue::schedSendTiming(PacketPtr pkt, Tick when, bool force_order) +{ + DPRINTF(PacketQueue, "%s for %s address %x size %d when %lu ord: %i\n", + __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize(), when, + force_order); + + // we can still send a packet before the end of this tick + assert(when >= curTick()); + + // express snoops should never be queued + assert(!pkt->isExpressSnoop()); + + // add a very basic sanity check on the port to ensure the + // invisible buffer is not growing beyond reasonable limits + if (!_disableSanityCheck && transmitList.size() > 100) { + panic("Packet queue %s has grown beyond 100 packets\n", + name()); + } + + // nothing on the list + if (transmitList.empty()) { + transmitList.emplace_front(when, pkt); + schedSendEvent(when); + return; + } + + // we should either have an outstanding retry, or a send event + // scheduled, but there is an unfortunate corner case where the + // x86 page-table walker and timing CPU send out a new request as + // part of the receiving of a response (called by + // PacketQueue::sendDeferredPacket), in which we end up calling + // ourselves again before we had a chance to update waitingOnRetry + // assert(waitingOnRetry || sendEvent.scheduled()); + + // this belongs in the middle somewhere, so search from the end to + // order by tick; however, if force_order is set, also make sure + // not to re-order in front of some existing packet with the same + // address + auto i = transmitList.end(); + --i; + while (i != transmitList.begin() && when < i->tick && + !(force_order && i->pkt->getAddr() == pkt->getAddr())) + --i; + + // emplace inserts the element before the position pointed to by + // the iterator, so advance it one step + transmitList.emplace(++i, when, pkt); +} + +void +PacketQueue::schedSendEvent(Tick when) +{ + // if we are waiting on a retry just hold off + if (waitingOnRetry) { + DPRINTF(PacketQueue, "Not scheduling send as waiting for retry\n"); + assert(!sendEvent.scheduled()); + return; + } + + if (when != MaxTick) { + // we cannot go back in time, and to be consistent we stick to + // one tick in the future + when = std::max(when, curTick() + 1); + // @todo Revisit the +1 + + if (!sendEvent.scheduled()) { + em.schedule(&sendEvent, when); + } else if (when < sendEvent.when()) { + // if the new time is earlier than when the event + // currently is scheduled, move it forward + em.reschedule(&sendEvent, when); + } + } else { + // we get a MaxTick when there is no more to send, so if we're + // draining, we may be done at this point + if (drainState() == DrainState::Draining && + transmitList.empty() && !sendEvent.scheduled()) { + + DPRINTF(Drain, "PacketQueue done draining," + "processing drain event\n"); + signalDrainDone(); + } + } +} + +void +PacketQueue::sendDeferredPacket() +{ + // sanity checks + assert(!waitingOnRetry); + assert(deferredPacketReady()); + + DeferredPacket dp = transmitList.front(); + + // take the packet of the list before sending it, as sending of + // the packet in some cases causes a new packet to be enqueued + // (most notaly when responding to the timing CPU, leading to a + // new request hitting in the L1 icache, leading to a new + // response) + transmitList.pop_front(); + + // use the appropriate implementation of sendTiming based on the + // type of queue + waitingOnRetry = !sendTiming(dp.pkt); + + // if we succeeded and are not waiting for a retry, schedule the + // next send + if (!waitingOnRetry) { + schedSendEvent(deferredPacketReadyTime()); + } else { + // put the packet back at the front of the list + transmitList.emplace_front(dp); + } +} + +void +PacketQueue::processSendEvent() +{ + assert(!waitingOnRetry); + sendDeferredPacket(); +} + +DrainState +PacketQueue::drain() +{ + if (transmitList.empty()) { + return DrainState::Drained; + } else { + DPRINTF(Drain, "PacketQueue not drained\n"); + return DrainState::Draining; + } +} + +ReqPacketQueue::ReqPacketQueue(EventManager& _em, MasterPort& _masterPort, + const std::string _label) + : PacketQueue(_em, _label, name(_masterPort, _label)), + masterPort(_masterPort) +{ +} + +bool +ReqPacketQueue::sendTiming(PacketPtr pkt) +{ + return masterPort.sendTimingReq(pkt); +} + +SnoopRespPacketQueue::SnoopRespPacketQueue(EventManager& _em, + MasterPort& _masterPort, + const std::string _label) + : PacketQueue(_em, _label, name(_masterPort, _label)), + masterPort(_masterPort) +{ +} + +bool +SnoopRespPacketQueue::sendTiming(PacketPtr pkt) +{ + return masterPort.sendTimingSnoopResp(pkt); +} + +RespPacketQueue::RespPacketQueue(EventManager& _em, SlavePort& _slavePort, + const std::string _label) + : PacketQueue(_em, _label, name(_slavePort, _label)), + slavePort(_slavePort) +{ +} + +bool +RespPacketQueue::sendTiming(PacketPtr pkt) +{ + return slavePort.sendTimingResp(pkt); +} diff --git a/pool/shard007/C++/0093089_test_SAT.cpp b/pool/shard007/C++/0093089_test_SAT.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c220ba3c566950a1f3019e4733fbbecbc5c3d0d0 --- /dev/null +++ b/pool/shard007/C++/0093089_test_SAT.cpp @@ -0,0 +1,104 @@ +/******************************************************************** +Copyright (c) 2010-2015, Regents of the University of Colorado + +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 University of Colorado 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 "Expr.h" +#include "ExprUtil.h" + +#include "SAT.h" + +#include <cassert> +#include <iostream> + +using namespace std; + +int main(void) { + Expr::Manager * man = new Expr::Manager(); + Expr::Manager::View * v = man->newView(); + + SAT::Clause ca, cb, cc; + ID a = v->newVar("a"); + ID b = v->newVar("b"); + ID c = v->newVar("c"); + + ca.push_back(a); + ca.push_back(v->apply(Expr::Not, b)); + + cb.push_back(b); + cb.push_back(v->apply(Expr::Not, c)); + + cc.push_back(c); + + SAT::Manager * sman = new SAT::Manager(*man); + SAT::Manager::View * sview = sman->newView(*v); + + // global constraints on globally visible variables + sman->add(ca); + sman->add(cb); + sman->add(cc); + + Expr::IDVector assumps; + assumps.push_back(v->apply(Expr::Not, a)); + assumps.push_back(v->apply(Expr::Not, b)); + + // only care about values for these variables + SAT::Assignment asgn; + asgn.insert(SAT::Assignment::value_type(a, SAT::Unknown)); + asgn.insert(SAT::Assignment::value_type(b, SAT::Unknown)); + asgn.insert(SAT::Assignment::value_type(c, SAT::Unknown)); + + // assumps is shrunk to a core of lits + bool rv = sview->sat(&assumps, NULL, &assumps); + assert (!rv); + cout << rv << " " << assumps.size() << endl; + + // which should be sufficient to still yield unsat + rv = sview->sat(&assumps, NULL, &assumps); + assert (!rv); + cout << rv << " " << assumps.size() << endl; + + // but w/o the assumps, it's sat + rv = sview->sat(NULL, &asgn, NULL); + assert (rv); + cout << rv << endl; + for (SAT::Assignment::iterator it = asgn.begin(); it != asgn.end(); it++) { + assert (it->second == SAT::True); + cout << stringOf(*v, it->first) << " " << it->second << endl; + } + + delete sview; + delete sman; + + delete v; + delete man; +} diff --git a/pool/shard007/C++/0093092_TestCFG.cpp b/pool/shard007/C++/0093092_TestCFG.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fcf99f74da5532c2d124826babc36cebea0accbd --- /dev/null +++ b/pool/shard007/C++/0093092_TestCFG.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "TestCFG.h" + +#include "ControlFlow.h" +#include "DexClass.h" +#include "IRCode.h" +#include "IRTypeChecker.h" +#include "Show.h" +#include "Trace.h" +#include "Walkers.h" + +/** + * This isn't a real optimization pass. It just tests the CFG. + * this should only run in redex-unstable + */ +void TestCFGPass::run_pass(DexStoresVector& stores, + ConfigFiles& /* unused */, + PassManager& mgr) { + const auto& scope = build_class_scope(stores); + DexMethod* example = + nullptr; // static_cast<DexMethod*>(DexMethod::get_method()); + // always_assert(example != nullptr && example->is_def()); + walk::code(scope, [example](DexMethod* m, IRCode& code) { + if (example != nullptr && m != example) { + return; + } + code.sanity_check(); + + const auto& before_code = show(&code); + + // build and linearize the CFG + TRACE(CFG, 5, "IRCode before:\n%s", SHOW(&code)); + code.build_cfg(/* editable */ true); + TRACE(CFG, 5, "%s", SHOW(code.cfg())); + code.clear_cfg(); + TRACE(CFG, 5, "IRCode after:\n%s", SHOW(&code)); + + // Run the IR type checker + IRTypeChecker checker(m); + checker.run(); + if (!checker.good()) { + std::string msg = checker.what(); + TRACE(CFG, 1, + "%s: Inconsistency in Dex code. %s" + "Before Code:\n%s\n" + "After Code:\n%s\n", + SHOW(m), msg.c_str(), before_code.c_str(), SHOW(&code)); + always_assert(checker.good()); + } + }); +} + +static TestCFGPass s_pass; diff --git a/pool/shard007/C++/0093095_v1_3.cpp b/pool/shard007/C++/0093095_v1_3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c5f56db75999a27bc1f277dfb337a04b38df0bd --- /dev/null +++ b/pool/shard007/C++/0093095_v1_3.cpp @@ -0,0 +1,202 @@ +/** + * @file set_avatar.cpp + * + * @copyright Copyright 2014 Mediafire + * + * This file was generated by gen_api_template.py. Do NOT edit by hand. + */ +// #define OUTPUT_DEBUG +#include "v1_3.hpp" + +#include <string> + +#include "mediafire_sdk/api/error.hpp" +#include "mediafire_sdk/api/ptree_helpers.hpp" +#include "mediafire_sdk/utils/string.hpp" +#include "mediafire_sdk/api/session_token_api_base.hpp" + +#include "boost/property_tree/json_parser.hpp" + +namespace v1_3 = mf::api::user::set_avatar::v1_3; + + +namespace { +std::string AsString(const v1_3::Action & value) +{ + if (value == v1_3::Action::SetDefault) + return "set_default"; + if (value == v1_3::Action::Remove) + return "remove"; + return mf::utils::to_string(static_cast<uint32_t>(value)); +} +} // namespace + +#include "mediafire_sdk/api/type_helpers.hpp" + +namespace mf { +namespace api { +/** API action path "user" */ +namespace user { +namespace set_avatar { +namespace v1_3 { + +const std::string api_path("/api/1.3/user/set_avatar"); + +// Impl ------------------------------------------------------------------------ + +class Impl : public SessionTokenApiBase<Response> +{ +public: + Impl(); + + boost::optional<Action> action_; + boost::optional<std::string> quickkey_; + boost::optional<std::string> url_; + virtual void BuildUrl( + std::string * path, + std::map<std::string, std::string> * query_parts + ) const override; + + virtual void ParseResponse( Response * response ) override; + + mf::http::SharedBuffer::Pointer GetPostData(); + + mf::api::RequestMethod GetRequestMethod() const + { + return mf::api::RequestMethod::Post; + } +}; + +Impl::Impl() +{ +} + +void Impl::BuildUrl( + std::string * path, + std::map<std::string, std::string> * query_parts + ) const +{ + *path = api_path + ".php"; +} + +void Impl::ParseResponse( Response * response ) +{ + // This function uses return defines for readability and maintainability. +# define return_error(error_type, error_message) \ + { \ + SetError(response, error_type, error_message); \ + return; \ + } + + // create_content_parse_single optional no default + { + std::string optarg; + if ( GetIfExists( + response->pt, + "response.quick_key", + &optarg) ) + { + response->quickkey = optarg; + } + } + + // create_content_parse_single optional no default + { + uint64_t optarg; + if ( GetIfExists( + response->pt, + "response.new_device_revision", + &optarg) ) + { + response->new_device_revision = optarg; + } + } + +# undef return_error +} + +mf::http::SharedBuffer::Pointer Impl::GetPostData() +{ + std::map<std::string, std::string> parts; + + if (action_) + parts["action"] = AsString(*action_); + if (quickkey_) + parts["quick_key"] = *quickkey_; + if (url_) + parts["url"] = *url_; + + std::string post_data = MakePost(api_path + ".php", parts); + AddDebugText(" POST data: " + post_data + "\n"); + return mf::http::SharedBuffer::Create(post_data); +} + +// Request --------------------------------------------------------------------- + +Request::Request() : + impl_(new Impl()) +{ +} + +void Request::SetCallback( CallbackType callback_function ) +{ + impl_->SetCallback(callback_function); +} + +void Request::HandleContent( + const std::string & url, + const mf::http::Headers & headers, + const std::string & content + ) +{ + impl_->HandleContent(url, headers, content); +} + +void Request::HandleError( + const std::string & url, + std::error_code ec, + const std::string & error_string + ) +{ + impl_->HandleError(url, ec, error_string); +} + +std::string Request::Url(const std::string & hostname) const +{ + return impl_->Url(hostname); +} + +void Request::SetSessionToken( + std::string session_token, + std::string time, + int secret_key + ) +{ + impl_->SetSessionToken(session_token, time, secret_key); +} + +void Request::SetAction(Action action) +{ + impl_->action_ = action; +} + +void Request::SetQuickkey(std::string quickkey) +{ + impl_->quickkey_ = quickkey; +} + +void Request::SetUrl(std::string url) +{ + impl_->url_ = url; +} + +mf::http::SharedBuffer::Pointer Request::GetPostData() +{ + return impl_->GetPostData(); +} + +} // namespace v1_3 +} // namespace set_avatar +} // namespace user +} // namespace api +} // namespace mf diff --git a/pool/shard007/C++/0093098_messageoutputwindow.cpp b/pool/shard007/C++/0093098_messageoutputwindow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d02157e55573be7a2242213876d326f92d633ed8 --- /dev/null +++ b/pool/shard007/C++/0093098_messageoutputwindow.cpp @@ -0,0 +1,136 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of Qt Creator. +** +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +****************************************************************************/ + +#include "messageoutputwindow.h" +#include "outputwindow.h" +#include "icontext.h" +#include "coreconstants.h" + +#include <coreplugin/icore.h> +#include <utils/utilsicons.h> + +#include <QFont> +#include <QToolButton> + +namespace Core { +namespace Internal { + +const char zoomSettingsKey[] = "Core/MessageOutput/Zoom"; + +MessageOutputWindow::MessageOutputWindow() +{ + m_widget = new OutputWindow(Context(Constants::C_GENERAL_OUTPUT_PANE), zoomSettingsKey); + m_widget->setReadOnly(true); + + connect(this, &IOutputPane::zoomInRequested, m_widget, &Core::OutputWindow::zoomIn); + connect(this, &IOutputPane::zoomOutRequested, m_widget, &Core::OutputWindow::zoomOut); + connect(this, &IOutputPane::resetZoomRequested, m_widget, &Core::OutputWindow::resetZoom); + connect(this, &IOutputPane::fontChanged, m_widget, &OutputWindow::setBaseFont); + connect(this, &IOutputPane::wheelZoomEnabledChanged, m_widget, &OutputWindow::setWheelZoomEnabled); + + setupFilterUi("MessageOutputPane.Filter"); + setFilteringEnabled(true); + setupContext(Constants::C_GENERAL_OUTPUT_PANE, m_widget); +} + +MessageOutputWindow::~MessageOutputWindow() +{ + delete m_widget; +} + +bool MessageOutputWindow::hasFocus() const +{ + return m_widget->window()->focusWidget() == m_widget; +} + +bool MessageOutputWindow::canFocus() const +{ + return true; +} + +void MessageOutputWindow::setFocus() +{ + m_widget->setFocus(); +} + +void MessageOutputWindow::clearContents() +{ + m_widget->clear(); +} + +QWidget *MessageOutputWindow::outputWidget(QWidget *parent) +{ + m_widget->setParent(parent); + return m_widget; +} + +QString MessageOutputWindow::displayName() const +{ + return tr("General Messages"); +} + +void MessageOutputWindow::append(const QString &text) +{ + m_widget->appendMessage(text, Utils::GeneralMessageFormat); +} + +int MessageOutputWindow::priorityInStatusBar() const +{ + return -1; +} + +bool MessageOutputWindow::canNext() const +{ + return false; +} + +bool MessageOutputWindow::canPrevious() const +{ + return false; +} + +void MessageOutputWindow::goToNext() +{ + +} + +void MessageOutputWindow::goToPrev() +{ + +} + +bool MessageOutputWindow::canNavigate() const +{ + return false; +} + +void MessageOutputWindow::updateFilter() +{ + m_widget->updateFilterProperties(filterText(), filterCaseSensitivity(), filterUsesRegexp(), + filterIsInverted()); +} + +} // namespace Internal +} // namespace Core diff --git a/pool/shard007/C++/0093099_Strings.cpp b/pool/shard007/C++/0093099_Strings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..443cc58e88baf174d8a46b457c88dad7b423bc1e --- /dev/null +++ b/pool/shard007/C++/0093099_Strings.cpp @@ -0,0 +1,48 @@ +#include "gb-include.h" + +#include "Strings.h" + +char *getString ( long i ) { + + static char *s_nextp = NULL; + static char *s_nexti = -1; + + // boundary check + if ( i < 0 ) return NULL; + + // was this call predicted? + if ( i == s_nexti ) { + // return NULL if none left + if ( s_nextp >= m_end ) return NULL; + // set next string ptr + s_nextp = m_s + gbstrlen ( m_s ) + 1; + s_nexti++; + // return current + return m_s; + } + + // otherwise reset + s_nextp = NULL; + s_nexti = -1; + + // scan from beginning + char *p = m_s; + long count = 0; + while ( p < m_end ) { + // break on match + if ( count == i ) break; + // advance p + p += gbstrlen ( p ) + 1; + count++; + } + + // return NULL if no match + if ( p >= m_end ) return NULL; + + // set statics + s_nextp = p + gbstrlen ( p ) + 1; + s_nexti = count + 1; + + // return now + return p; +} diff --git a/pool/shard007/C++/0093102_QNodeViewItemSocket.cpp b/pool/shard007/C++/0093102_QNodeViewItemSocket.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d5e066b93873ab179f0edb52e282731d2d888635 --- /dev/null +++ b/pool/shard007/C++/0093102_QNodeViewItemSocket.cpp @@ -0,0 +1,53 @@ +/* +Copyright (C) 2017 Rodrigo Jose Hernandez Cordoba + +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 "qlayout.h" +#include "qpainter.h" +#include "qstyle.h" +#include "qstyleoption.h" +#include "QNodeViewItemSocket.h" + +QNodeViewItemSocket::QNodeViewItemSocket(QWidget *parent, Qt::WindowFlags f) : QWidget(parent,f), mSocketColor("green") +{ + setAttribute(Qt::WA_StaticContents); + setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); + setMinimumSize(10, 10); +} + +QNodeViewItemSocket::~QNodeViewItemSocket() +{ +} + +void QNodeViewItemSocket::setSocketColor(const QColor & color) +{ + mSocketColor = color; +} + +const QColor & QNodeViewItemSocket::socketColor() const +{ + return mSocketColor; +} + +void QNodeViewItemSocket::paintEvent(QPaintEvent * event) +{ + int diameter = ((size().width() < size().height()) ? size().width() : size().height()); + QStyleOption opt; + QPainter p(this); + opt.init(this); + p.setBrush(mSocketColor); + p.setPen(mSocketColor); + p.drawEllipse(((size().width()-diameter+1)/2), ((size().height() - diameter+1) / 2),diameter-1,diameter-1); + style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); +} diff --git a/pool/shard007/C++/0093103_RegMozCtlDlg.cpp b/pool/shard007/C++/0093103_RegMozCtlDlg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..31a2df4569531792507542158667581d495d7e61 --- /dev/null +++ b/pool/shard007/C++/0093103_RegMozCtlDlg.cpp @@ -0,0 +1,258 @@ +// RegMozCtlDlg.cpp : implementation file +// + +#include "stdafx.h" +#include "RegMozCtl.h" +#include "RegMozCtlDlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CRegMozCtlDlg dialog + +CRegMozCtlDlg::CRegMozCtlDlg(CWnd* pParent /*=NULL*/) + : CDialog(CRegMozCtlDlg::IDD, pParent) +{ + //{{AFX_DATA_INIT(CRegMozCtlDlg) + m_szMozillaDir = _T(""); + //}}AFX_DATA_INIT + // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 + m_hIcon = AfxGetApp()->LoadIcon(IDI_MOZILLA); + + GetCurrentDirectory(1024, m_szMozillaDir.GetBuffer(1024)); + m_szMozillaDir.ReleaseBuffer(); +} + +void CRegMozCtlDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CRegMozCtlDlg) + DDX_Control(pDX, IDC_TASKLIST, m_cTaskList); + DDX_Text(pDX, IDC_MOZILLADIR, m_szMozillaDir); + //}}AFX_DATA_MAP +} + +BEGIN_MESSAGE_MAP(CRegMozCtlDlg, CDialog) + //{{AFX_MSG_MAP(CRegMozCtlDlg) + ON_WM_PAINT() + ON_WM_QUERYDRAGICON() + ON_BN_CLICKED(IDC_REGISTER, OnRegister) + ON_BN_CLICKED(IDC_UNREGISTER, OnUnregister) + ON_BN_CLICKED(IDC_PICKDIR, OnPickDir) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CRegMozCtlDlg message handlers + +BOOL CRegMozCtlDlg::OnInitDialog() +{ + // Set the icon for this dialog. The framework does this automatically + // when the application's main window is not a dialog + SetIcon(m_hIcon, TRUE); // Set big icon + SetIcon(m_hIcon, FALSE); // Set small icon + + // Get values from the registry + TCHAR szValue[1024]; + DWORD dwSize = sizeof(szValue) / sizeof(szValue[0]); + CRegKey cKey; + cKey.Create(HKEY_LOCAL_MACHINE, MOZ_CONTROL_REG_KEY); + + memset(szValue, 0, sizeof(szValue)); + if (cKey.QueryValue(szValue, MOZ_CONTROL_REG_VALUE_BIN_DIR_PATH, &dwSize) == ERROR_SUCCESS) + { + m_szMozillaDir = CString(szValue); + } + + CDialog::OnInitDialog(); + + CRegTask::PopulateTasks(m_cTaskMgr); + + // Add icons to image list +// m_cImageList.Create(16, 16, ILC_MASK, 0, 5); +// m_cImageList.Add(AfxGetApp()->LoadIcon(IDI_DOESNTCONTAINIE)); +// m_cImageList.Add(AfxGetApp()->LoadIcon(IDI_CONTAINSIE)); +// m_cImageList.Add(AfxGetApp()->LoadIcon(IDI_CONTAINSMOZILLA)); +// m_cImageList.Add(AfxGetApp()->LoadIcon(IDI_UNKNOWNSTATUS)); + + // Associate image list with file list +// m_cFileList.SetImageList(&m_cImageList, LVSIL_SMALL); + + struct ColumnData + { + TCHAR *sColumnTitle; + int nPercentageWidth; + int nFormat; + }; + + ColumnData aColData[] = + { + { _T("Task"), 70, LVCFMT_LEFT }, + { _T("Status"), 30, LVCFMT_LEFT } + }; + + // Get the size of the file list control and neatly + // divide it into columns + + CRect rcList; + m_cTaskList.GetClientRect(&rcList); + + int nColTotal = sizeof(aColData) / sizeof(aColData[0]); + int nWidthRemaining = rcList.Width(); + + for (int nCol = 0; nCol < nColTotal; nCol++) + { + ColumnData *pData = &aColData[nCol]; + + int nColWidth = (rcList.Width() * pData->nPercentageWidth) / 100; + if (nCol == nColTotal - 1) + { + nColWidth = nWidthRemaining; + } + else if (nColWidth > nWidthRemaining) + { + nColWidth = nWidthRemaining; + } + + m_cTaskList.InsertColumn(nCol, pData->sColumnTitle, pData->nFormat, nColWidth); + + nWidthRemaining -= nColWidth; + if (nColWidth <= 0) + { + break; + } + } + + for (int i = 0; i < m_cTaskMgr.GetTaskCount(); i++) + { + CRegTask *pTask = m_cTaskMgr.GetTask(i); + m_cTaskList.InsertItem(i, pTask->GetDescription()); + } + + return TRUE; // return TRUE unless you set the focus to a control +} + +// If you add a minimize button to your dialog, you will need the code below +// to draw the icon. For MFC applications using the document/view model, +// this is automatically done for you by the framework. + +void CRegMozCtlDlg::OnPaint() +{ + if (IsIconic()) + { + CPaintDC dc(this); // device context for painting + + SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); + + // Center icon in client rectangle + int cxIcon = GetSystemMetrics(SM_CXICON); + int cyIcon = GetSystemMetrics(SM_CYICON); + CRect rect; + GetClientRect(&rect); + int x = (rect.Width() - cxIcon + 1) / 2; + int y = (rect.Height() - cyIcon + 1) / 2; + + // Draw the icon + dc.DrawIcon(x, y, m_hIcon); + } + else + { + CDialog::OnPaint(); + } +} + +// The system calls this to obtain the cursor to display while the user drags +// the minimized window. +HCURSOR CRegMozCtlDlg::OnQueryDragIcon() +{ + return (HCURSOR) m_hIcon; +} + +void CRegMozCtlDlg::OnRegister() +{ + RegisterMozillaControl(TRUE); +} + +void CRegMozCtlDlg::OnUnregister() +{ + RegisterMozillaControl(FALSE); +} + +void CRegMozCtlDlg::RegisterMozillaControl(BOOL bRegister) +{ + UpdateData(); + + m_cTaskMgr.SetValue(c_szValueBinDirPath, m_szMozillaDir); + + for (int i = 0; i < m_cTaskMgr.GetTaskCount(); i++) + { + CRegTask *pTask = m_cTaskMgr.GetTask(i); + pTask->DoTask(); + } + + AfxMessageBox(bRegister ? _T("Register completed") : _T("Unregister completed")); +} + +void CRegMozCtlDlg::OnPickDir() +{ + BROWSEINFO bi; + TCHAR szFolder[MAX_PATH + 1]; + + memset(szFolder, 0, sizeof(szFolder)); + + memset(&bi, 0, sizeof(bi)); + bi.hwndOwner = GetSafeHwnd(); + bi.pidlRoot = NULL; + bi.pszDisplayName = szFolder; + bi.lpszTitle = _T("Pick a folder to scan"); + + // Open the folder browser dialog + LPITEMIDLIST pItemList = SHBrowseForFolder(&bi); + if (pItemList) + { + IMalloc *pShellAllocator = NULL; + + SHGetMalloc(&pShellAllocator); + if (pShellAllocator) + { + char szPath[MAX_PATH + 1]; + + if (SHGetPathFromIDList(pItemList, szPath)) + { + // Chop off the end path separator + int nPathSize = strlen(szPath); + if (nPathSize > 0) + { + if (szPath[nPathSize - 1] == '\\') + { + szPath[nPathSize - 1] = '\0'; + } + } + + m_szMozillaDir = CString(szPath); + + UpdateData(FALSE); + } + + pShellAllocator->Free(pItemList); + pShellAllocator->Release(); + } + } +} + + +CString CRegMozCtlDlg::GetSystemPath() +{ + // TODO + return _T(""); +} + +BOOL CRegMozCtlDlg::SetSystemPath(const CString &szNewPath) +{ + // TODO + return TRUE; +} diff --git a/pool/shard007/C++/0093107_I2C_Dev.cpp b/pool/shard007/C++/0093107_I2C_Dev.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fc188f175ab8140b120e9608589b3f1e69b27856 --- /dev/null +++ b/pool/shard007/C++/0093107_I2C_Dev.cpp @@ -0,0 +1,219 @@ +#include "I2C_Dev.h" +#include "Log.h" +#include "Debug.h" + +#include <cstring> +#include <errno.h> +#include <unistd.h> +#include <linux/i2c-dev.h> +#include <sys/ioctl.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> + +struct i2c_msg +{ + uint16_t addr = 0; + uint16_t flags = 0; +#define I2C_M_TEN 0x0010 +#define I2C_M_RD 0x0001 +#define I2C_M_NOSTART 0x4000 +#define I2C_M_REV_DIR_ADDR 0x2000 +#define I2C_M_IGNORE_NAK 0x1000 +#define I2C_M_NO_RD_ACK 0x0800 +#define I2C_M_RECV_LEN 0x0400 + uint16_t len = 0; + uint8_t* buf = nullptr; +}; + + +namespace util +{ +namespace hw +{ + + +I2C_Dev::I2C_Dev() +{ +} + +I2C_Dev::~I2C_Dev() +{ + if (m_fd >= 0) + { + ::close(m_fd); + m_fd = -1; + } +} + +ts::Result<void> I2C_Dev::init(std::string const& device) +{ + QLOG_TOPIC("I2C_Dev::init"); + close(); + + m_fd = ::open(device.c_str(), O_RDWR); + if (m_fd < 0) + { + return ts::Error("Can't open " + device + ": " + strerror(errno)); + } + return ts::success; +} + +void I2C_Dev::close() +{ + QLOG_TOPIC("I2C_Dev::close"); + + if (m_fd >= 0) + { + ::close(m_fd); + m_fd = -1; + } +} + +bool I2C_Dev::read(uint8_t address, uint8_t* data, size_t size) +{ + QLOG_TOPIC("I2C_Dev::read"); + QASSERT(m_fd >= 0); + + if (m_is_used.exchange(true) == true) + { + QLOGE("SPI bus in use"); + return false; + } + + struct i2c_rdwr_ioctl_data io; + memset(&io, 0, sizeof(i2c_rdwr_ioctl_data)); + + struct i2c_msg msg; + //memset(&msg, 0, sizeof(i2c_msg)); //no need, it's already initialized with defaults + + msg.addr = address; + msg.flags = I2C_M_RD; + msg.len = size; + msg.buf = reinterpret_cast<decltype(i2c_msg::buf)>(data); + + io.msgs = &msg; + io.nmsgs = 1; + if (ioctl(m_fd, I2C_RDWR, &io) < 0) + { + QLOGW("read failed: {}", strerror(errno)); + m_is_used = false; + return false; + } + m_is_used = false; + return true; +} +bool I2C_Dev::write(uint8_t address, uint8_t const* data, size_t size) +{ + QLOG_TOPIC("I2C_Dev::write"); + QASSERT(m_fd >= 0); + + if (m_is_used.exchange(true) == true) + { + QLOGE("SPI bus in use"); + return false; + } + + struct i2c_rdwr_ioctl_data io; + memset(&io, 0, sizeof(i2c_rdwr_ioctl_data)); + + struct i2c_msg msg; + //memset(&msg, 0, sizeof(i2c_msg)); //no need, it's already initialized with defaults + + msg.addr = address; + msg.flags = 0; + msg.len = size; + msg.buf = decltype(i2c_msg::buf)(data); + io.msgs = &msg; + io.nmsgs = 1; + if (ioctl(m_fd, I2C_RDWR, &io) < 0) + { + QLOGW("write failed: {}", strerror(errno)); + m_is_used = false; + return false; + } + m_is_used = false; + return true; +} + +bool I2C_Dev::read_register(uint8_t address, uint8_t reg, uint8_t* data, size_t size) +{ + QLOG_TOPIC("I2C_Dev::read_register"); + QASSERT(m_fd >= 0); + + if (m_is_used.exchange(true) == true) + { + QLOGE("SPI bus in use"); + return false; + } + + struct i2c_rdwr_ioctl_data io; + memset(&io, 0, sizeof(i2c_rdwr_ioctl_data)); + + struct i2c_msg msg[2]; + //memset(&msg, 0, sizeof(i2c_msg)); //no need, it's already initialized with defaults + + msg[0].addr = address; + msg[0].flags = 0; + msg[0].len = 1; + msg[0].buf = decltype(i2c_msg::buf)(®); + + msg[1].addr = address; + msg[1].flags = I2C_M_RD; + msg[1].len = size; + msg[1].buf = decltype(i2c_msg::buf)(data); + + io.msgs = msg; + io.nmsgs = 2; + if (ioctl(m_fd, I2C_RDWR, &io) < 0) + { + QLOGW("read register {} failed: {}", reg, strerror(errno)); + m_is_used = false; + return false; + } + m_is_used = false; + return true; +} +bool I2C_Dev::write_register(uint8_t address, uint8_t reg, uint8_t const* data, size_t size) +{ + QLOG_TOPIC("I2C_Dev::write_register"); + QASSERT(m_fd >= 0); + + if (m_is_used.exchange(true) == true) + { + QLOGE("SPI bus in use"); + return false; + } + + struct i2c_rdwr_ioctl_data io; + memset(&io, 0, sizeof(i2c_rdwr_ioctl_data)); + + struct i2c_msg msg; + //memset(&msg, 0, sizeof(i2c_msg)); //no need, it's already initialized with defaults + + m_buffer.resize(size + 1); + + m_buffer[0] = reg; + if (data) + { + std::copy(data, data + size, m_buffer.begin() + 1); + } + + msg.addr = address; + msg.flags = 0; + msg.len = size + 1; + msg.buf = decltype(i2c_msg::buf)(m_buffer.data()); + io.msgs = &msg; + io.nmsgs = 1; + if (ioctl(m_fd, I2C_RDWR, &io) < 0) + { + QLOGW("write register {} failed: {}", reg, strerror(errno)); + m_is_used = false; + return false; + } + m_is_used = false; + return true; +} + +} +} diff --git a/pool/shard007/C++/0093116_renderer_task.cc b/pool/shard007/C++/0093116_renderer_task.cc new file mode 100644 index 0000000000000000000000000000000000000000..86021b4355788ab5351d86b528b6eaf55cf4ed8c --- /dev/null +++ b/pool/shard007/C++/0093116_renderer_task.cc @@ -0,0 +1,207 @@ +// 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. + +#include "chrome/browser/task_management/providers/web_contents/renderer_task.h" + +#include "base/i18n/rtl.h" +#include "base/numerics/safe_conversions.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/favicon/favicon_utils.h" +#include "chrome/browser/process_resource_usage.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_info_cache.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/task_management/task_manager_observer.h" +#include "chrome/grit/generated_resources.h" +#include "content/public/browser/render_process_host.h" +#include "content/public/browser/web_contents.h" +#include "content/public/browser/web_contents_delegate.h" +#include "content/public/common/service_registry.h" +#include "ui/base/l10n/l10n_util.h" + +namespace task_management { + +namespace { + +// Creates the Mojo service wrapper that will be used to sample the V8 memory +// usage and the the WebCache resource stats of the render process hosted by +// |render_process_host|. +ProcessResourceUsage* CreateRendererResourcesSampler( + content::RenderProcessHost* render_process_host) { + ResourceUsageReporterPtr service; + content::ServiceRegistry* service_registry = + render_process_host->GetServiceRegistry(); + if (service_registry) + service_registry->ConnectToRemoteService(mojo::GetProxy(&service)); + return new ProcessResourceUsage(service.Pass()); +} + +// Gets the profile name associated with the browser context of the given +// |render_process_host| from the profile info cache. +base::string16 GetRendererProfileName( + const content::RenderProcessHost* render_process_host) { + Profile* profile = + Profile::FromBrowserContext(render_process_host->GetBrowserContext()); + DCHECK(profile); + ProfileInfoCache& cache = + g_browser_process->profile_manager()->GetProfileInfoCache(); + size_t index = + cache.GetIndexOfProfileWithPath(profile->GetOriginalProfile()->GetPath()); + if (index != std::string::npos) + return cache.GetNameOfProfileAtIndex(index); + + return base::string16(); +} + +inline bool IsRendererResourceSamplingDisabled(int64 flags) { + return (flags & (REFRESH_TYPE_V8_MEMORY | REFRESH_TYPE_WEBCACHE_STATS)) == 0; +} + +} // namespace + +RendererTask::RendererTask(const base::string16& title, + const gfx::ImageSkia* icon, + content::WebContents* web_contents) + : Task(title, icon, web_contents->GetRenderProcessHost()->GetHandle()), + web_contents_(web_contents), + render_process_host_(web_contents->GetRenderProcessHost()), + renderer_resources_sampler_( + CreateRendererResourcesSampler(render_process_host_)), + render_process_id_(render_process_host_->GetID()), + v8_memory_allocated_(0), + v8_memory_used_(0), + webcache_stats_(), + profile_name_(GetRendererProfileName(render_process_host_)) { +} + +RendererTask::~RendererTask() { +} + +void RendererTask::Activate() { + if (!web_contents_->GetDelegate()) + return; + + web_contents_->GetDelegate()->ActivateContents(web_contents_); +} + +void RendererTask::Refresh(const base::TimeDelta& update_interval, + int64 refresh_flags) { + Task::Refresh(update_interval, refresh_flags); + + if (IsRendererResourceSamplingDisabled(refresh_flags)) + return; + + // The renderer resources refresh is performed asynchronously, we will invoke + // it and record the current values (which might be invalid at the moment. We + // can safely ignore that and count on future refresh cycles potentially + // having valid values). + renderer_resources_sampler_->Refresh(base::Closure()); + + v8_memory_allocated_ = base::saturated_cast<int64>( + renderer_resources_sampler_->GetV8MemoryAllocated()); + v8_memory_used_ = base::saturated_cast<int64>( + renderer_resources_sampler_->GetV8MemoryUsed()); + webcache_stats_ = renderer_resources_sampler_->GetWebCoreCacheStats(); +} + +Task::Type RendererTask::GetType() const { + return Task::RENDERER; +} + +int RendererTask::GetChildProcessUniqueID() const { + return render_process_id_; +} + +base::string16 RendererTask::GetProfileName() const { + return profile_name_; +} + +int64 RendererTask::GetV8MemoryAllocated() const { + return v8_memory_allocated_; +} + +int64 RendererTask::GetV8MemoryUsed() const { + return v8_memory_used_; +} + +bool RendererTask::ReportsWebCacheStats() const { + return true; +} + +blink::WebCache::ResourceTypeStats RendererTask::GetWebCacheStats() const { + return webcache_stats_; +} + +// static +base::string16 RendererTask::GetTitleFromWebContents( + content::WebContents* web_contents) { + DCHECK(web_contents); + base::string16 title = web_contents->GetTitle(); + if (title.empty()) { + GURL url = web_contents->GetURL(); + title = base::UTF8ToUTF16(url.spec()); + // Force URL to be LTR. + title = base::i18n::GetDisplayStringInLTRDirectionality(title); + } else { + // Since the title could later be concatenated with + // IDS_TASK_MANAGER_TAB_PREFIX (for example), we need to explicitly set the + // title to be LTR format if there is no strong RTL charater in it. + // Otherwise, if IDS_TASK_MANAGER_TAB_PREFIX is an RTL word, the + // concatenated result might be wrong. For example, http://mail.yahoo.com, + // whose title is "Yahoo! Mail: The best web-based Email!", without setting + // it explicitly as LTR format, the concatenated result will be "!Yahoo! + // Mail: The best web-based Email :BAT", in which the capital letters "BAT" + // stands for the Hebrew word for "tab". + base::i18n::AdjustStringForLocaleDirection(&title); + } + return title; +} + +// static +const gfx::ImageSkia* RendererTask::GetFaviconFromWebContents( + content::WebContents* web_contents) { + DCHECK(web_contents); + + // Tag the web_contents with a |ContentFaviconDriver| (if needed) so that + // we can use it to retrieve the favicon if there is one. + favicon::CreateContentFaviconDriverForWebContents(web_contents); + gfx::Image image = + favicon::ContentFaviconDriver::FromWebContents(web_contents)-> + GetFavicon(); + if (image.IsEmpty()) + return nullptr; + + return image.ToImageSkia(); +} + +// static +const base::string16 RendererTask::PrefixRendererTitle( + const base::string16& title, + bool is_app, + bool is_extension, + bool is_incognito, + bool is_background) { + int message_id = IDS_TASK_MANAGER_TAB_PREFIX; + + if (is_incognito && !is_app && !is_extension) { + message_id = IDS_TASK_MANAGER_TAB_INCOGNITO_PREFIX; + } else if (is_app) { + if (is_background) + message_id = IDS_TASK_MANAGER_BACKGROUND_PREFIX; + else if (is_incognito) + message_id = IDS_TASK_MANAGER_APP_INCOGNITO_PREFIX; + else + message_id = IDS_TASK_MANAGER_APP_PREFIX; + } else if (is_extension) { + if (is_incognito) + message_id = IDS_TASK_MANAGER_EXTENSION_INCOGNITO_PREFIX; + else + message_id = IDS_TASK_MANAGER_EXTENSION_PREFIX; + } + + return l10n_util::GetStringFUTF16(message_id, title); +} + +} // namespace task_management diff --git a/pool/shard007/C++/0093117_dataset_local.cpp b/pool/shard007/C++/0093117_dataset_local.cpp new file mode 100644 index 0000000000000000000000000000000000000000..be12220e8cba25849ca362978fab9fd9f98bdcbb --- /dev/null +++ b/pool/shard007/C++/0093117_dataset_local.cpp @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2016-2017, The OpenThread Authors. + * 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. + */ + +/** + * @file + * This file implements common methods for manipulating MeshCoP Datasets. + * + */ + +#include "dataset_local.hpp" + +#include <stdio.h> + +#include "common/code_utils.hpp" +#include "common/instance.hpp" +#include "common/locator-getters.hpp" +#include "common/logging.hpp" +#include "common/settings.hpp" +#include "meshcop/dataset.hpp" +#include "meshcop/meshcop_tlvs.hpp" +#include "thread/mle_tlvs.hpp" + +namespace ot { +namespace MeshCoP { + +DatasetLocal::DatasetLocal(Instance &aInstance, Tlv::Type aType) + : InstanceLocator(aInstance) + , mUpdateTime(0) + , mType(aType) + , mTimestampPresent(false) +{ + mTimestamp.Init(); +} + +void DatasetLocal::Clear(void) +{ + Get<Settings>().DeleteOperationalDataset(IsActive()); + mTimestamp.Init(); + mTimestampPresent = false; + mSaved = false; +} + +otError DatasetLocal::Restore(Dataset &aDataset) +{ + const Timestamp *timestamp; + otError error; + + mTimestampPresent = false; + + error = Read(aDataset); + SuccessOrExit(error); + + mSaved = true; + timestamp = aDataset.GetTimestamp(); + + if (timestamp != NULL) + { + mTimestamp = *timestamp; + mTimestampPresent = true; + } + +exit: + return error; +} + +otError DatasetLocal::Read(Dataset &aDataset) const +{ + DelayTimerTlv *delayTimer; + uint32_t elapsed; + otError error; + + error = Get<Settings>().ReadOperationalDataset(IsActive(), aDataset); + VerifyOrExit(error == OT_ERROR_NONE, aDataset.mLength = 0); + + if (mType == Tlv::kActiveTimestamp) + { + aDataset.Remove(Tlv::kPendingTimestamp); + aDataset.Remove(Tlv::kDelayTimer); + } + else + { + delayTimer = static_cast<DelayTimerTlv *>(aDataset.Get(Tlv::kDelayTimer)); + VerifyOrExit(delayTimer); + + elapsed = TimerMilli::Elapsed(mUpdateTime); + + if (delayTimer->GetDelayTimer() > elapsed) + { + delayTimer->SetDelayTimer(delayTimer->GetDelayTimer() - elapsed); + } + else + { + delayTimer->SetDelayTimer(0); + } + } + + aDataset.mUpdateTime = TimerMilli::GetNow(); + +exit: + return error; +} + +otError DatasetLocal::Read(otOperationalDataset &aDataset) const +{ + Dataset dataset(mType); + otError error; + + memset(&aDataset, 0, sizeof(aDataset)); + + error = Read(dataset); + SuccessOrExit(error); + + dataset.Get(aDataset); + +exit: + return error; +} + +otError DatasetLocal::Save(const otOperationalDataset &aDataset) +{ + otError error = OT_ERROR_NONE; + Dataset dataset(mType); + + error = dataset.Set(aDataset); + SuccessOrExit(error); + + error = Save(dataset); + SuccessOrExit(error); + +exit: + return error; +} + +otError DatasetLocal::Save(const Dataset &aDataset) +{ + const Timestamp *timestamp; + otError error = OT_ERROR_NONE; + + if (aDataset.GetSize() == 0) + { + // do not propagate error back + Get<Settings>().DeleteOperationalDataset(IsActive()); + mSaved = false; + otLogInfoMeshCoP("%s dataset deleted", mType == Tlv::kActiveTimestamp ? "Active" : "Pending"); + } + else + { + SuccessOrExit(error = Get<Settings>().SaveOperationalDataset(IsActive(), aDataset)); + mSaved = true; + otLogInfoMeshCoP("%s dataset set", mType == Tlv::kActiveTimestamp ? "Active" : "Pending"); + } + + timestamp = aDataset.GetTimestamp(); + + if (timestamp != NULL) + { + mTimestamp = *timestamp; + mTimestampPresent = true; + } + else + { + mTimestampPresent = false; + } + + mUpdateTime = TimerMilli::GetNow(); + +exit: + return error; +} + +int DatasetLocal::Compare(const Timestamp *aCompare) +{ + int rval = 1; + + if (aCompare == NULL) + { + if (!mTimestampPresent) + { + rval = 0; + } + else + { + rval = -1; + } + } + else + { + if (!mTimestampPresent) + { + rval = 1; + } + else + { + rval = mTimestamp.Compare(*aCompare); + } + } + + return rval; +} + +} // namespace MeshCoP +} // namespace ot diff --git a/pool/shard007/C++/0093122_quic_test_output_impl.cc b/pool/shard007/C++/0093122_quic_test_output_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..0e711a4846307908fae4a01d6ac02e140f22473b --- /dev/null +++ b/pool/shard007/C++/0093122_quic_test_output_impl.cc @@ -0,0 +1,73 @@ +// NOLINT(namespace-envoy) + +// This file is part of the QUICHE platform implementation, and is not to be +// consumed or referenced directly by other Envoy code. It serves purely as a +// porting layer for QUICHE. + +#include "test/extensions/quic_listeners/quiche/platform/quic_test_output_impl.h" + +#include <cstdlib> + +#include "common/filesystem/filesystem_impl.h" + +#include "absl/time/clock.h" +#include "absl/time/time.h" +#include "fmt/printf.h" +#include "gtest/gtest.h" +#include "quiche/quic/platform/api/quic_logging.h" + +namespace quic { +namespace { + +void QuicRecordTestOutputToFile(const std::string& filename, QuicStringPiece data) { + const char* output_dir_env = std::getenv("QUIC_TEST_OUTPUT_DIR"); + if (output_dir_env == nullptr) { + QUIC_LOG(WARNING) << "Could not save test output since QUIC_TEST_OUTPUT_DIR is not set"; + return; + } + + std::string output_dir = output_dir_env; + if (output_dir.empty()) { + QUIC_LOG(WARNING) << "Could not save test output since QUIC_TEST_OUTPUT_DIR is empty"; + return; + } + + if (output_dir.back() != '/') { + output_dir += '/'; + } + + Envoy::Filesystem::InstanceImplPosix file_system; + if (!file_system.directoryExists(output_dir)) { + QUIC_LOG(ERROR) << "Directory does not exist while writing test output: " << output_dir; + return; + } + + const std::string output_path = output_dir + filename; + Envoy::Filesystem::FilePtr file = file_system.createFile(output_path); + if (!file->open().rc_) { + QUIC_LOG(ERROR) << "Failed to open test output file: " << output_path; + return; + } + + if (file->write(data).rc_ != static_cast<ssize_t>(data.size())) { + QUIC_LOG(ERROR) << "Failed to write to test output file: " << output_path; + } else { + QUIC_LOG(INFO) << "Recorded test output into " << output_path; + } + + file->close(); +} +} // namespace + +void QuicRecordTestOutputImpl(QuicStringPiece identifier, QuicStringPiece data) { + const testing::TestInfo* test_info = testing::UnitTest::GetInstance()->current_test_info(); + + std::string timestamp = absl::FormatTime("%Y%m%d%H%M%S", absl::Now(), absl::LocalTimeZone()); + + std::string filename = fmt::sprintf("%s.%s.%s.%s.qtr", test_info->name(), + test_info->test_case_name(), identifier.data(), timestamp); + + QuicRecordTestOutputToFile(filename, data); +} + +} // namespace quic diff --git a/pool/shard007/C++/0093138_ConfigStorage.cpp b/pool/shard007/C++/0093138_ConfigStorage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6c9c385415e3e4ee740fca9806d683d644d394c4 --- /dev/null +++ b/pool/shard007/C++/0093138_ConfigStorage.cpp @@ -0,0 +1,168 @@ +#ifdef _WIN32 +#pragma warning(disable:4996) +#define _D_SCL_SECURE_NO_WARNINGS +#endif + +#include "ConfigStorage.h" +#include <qdiriterator.h> +#include "Configurator.h" +#include <boost/property_tree/ptree.hpp> +#include <boost/property_tree/xml_parser.hpp> +#include "Logger.h" +#include <climits> + +ConfigStorage::ConfigStorage() +{ + QString configsPath = Configurator::getConfigFilesPath(); + QDirIterator iter(configsPath, QStringList() << "*.xml", QDir::Files | QDir::NoDotAndDotDot, QDirIterator::NoIteratorFlags); + + while (iter.hasNext()) + { + iter.next(); + QString xmlFilePath = iter.filePath(); + if (!readXMLConfig(xmlFilePath)) + Logger::log("Invalid config file - " + xmlFilePath.toStdString(), Logger::Error);; + } +} + + +ConfigStorage::~ConfigStorage() +{ +} + + +bool ConfigStorage::readXMLConfig(const QString& path) +{ + boost::property_tree::ptree tree; + try + { + boost::property_tree::read_xml(path.toStdString(), tree, boost::property_tree::xml_parser::no_comments); + std::string configName = tree.get<std::string>("Config.<xmlattr>.name"); + std::string vendor = tree.get<std::string>("Config.Vendor"); + std::string product = tree.get<std::string>("Config.Product"); + std::string versionMin = tree.get<std::string>("Config.Version.min"); + std::string versionMax = tree.get<std::string>("Config.Version.max"); + ConfigMapShared a_map = std::make_shared<ConfigMap>(path.toStdString(), configName, vendor, product, versionMin, versionMax); + + std::string uiType = tree.get<std::string>("Config.UI.<xmlattr>.type", "none"); + if ("none" != uiType) + { + std::string ui_path = tree.get<std::string>("Config.UI.path"); + int fontHeight = tree.get<int>("Config.UI.font_height", 8); + boost::property_tree::ptree placeholdersTree = tree.get_child("Config.UI.placeholders", boost::property_tree::ptree()); + ConfigMap::UI_PlaceholderList placeholdersList; + for (const std::pair<std::string, boost::property_tree::ptree> &a_placeholder : placeholdersTree) + { + ConfigMap::UI_Placeholder item; + item.m_variableName = a_placeholder.second.get<std::string>("<xmlattr>.v"); + item.m_x = a_placeholder.second.get<int>("<xmlattr>.x"); + item.m_y = a_placeholder.second.get<int>("<xmlattr>.y"); + placeholdersList.push_back(item); + } + a_map->setUI_Config(uiType, ui_path, placeholdersList, fontHeight); + } + + boost::property_tree::ptree values[ConfigMap::REGISTER_PULL_COUNT] = { + tree.get_child("Config.InputValues", boost::property_tree::ptree()), + tree.get_child("Config.OutValues", boost::property_tree::ptree()), + tree.get_child("Config.Coils", boost::property_tree::ptree()) + }; + + for (ConfigMap::RegisterType i = ConfigMap::REGISTER_PULL_FIRST; i < ConfigMap::REGISTER_PULL_COUNT; i = ConfigMap::NEXT(i)) + { + boost::property_tree::ptree& a_value = values[i]; + for (const std::pair<std::string, boost::property_tree::ptree> &p : a_value) + { + std::string name = p.first; + ConfigMap::Parameter a_parameter; + a_parameter.m_type = i; + a_parameter.m_description = p.second.get_value<std::string>(); + a_parameter.m_registerNumber = p.second.get<int>("<xmlattr>.R"); + a_map->getInterval(i).add(a_parameter.m_registerNumber); + int b = p.second.get<int>("<xmlattr>.B", -1); + a_parameter.m_decodeMethod = p.second.get<std::string>("<xmlattr>.D", ""); + if (b != -1) + { + a_parameter.m_isBool = true; + a_parameter.m_bitNumber = b; + } + else + { + a_parameter.m_isBool = false; + } + + a_parameter.m_minValue = p.second.get<int>("<xmlattr>.min", INT_MIN); + a_parameter.m_maxValue = p.second.get<int>("<xmlattr>.max", INT_MAX); + + boost::property_tree::ptree errorDetectionSection = p.second.get_child("errors", boost::property_tree::ptree()); + for (const std::pair<std::string, boost::property_tree::ptree> &a_error : errorDetectionSection) + { + std::string type = a_error.first; + std::string description = a_error.second.get<std::string>("<xmlattr>.d", "error"); + int value = a_error.second.get<int>("<xmlattr>.v"); //mandatory + a_parameter.m_errorDetector.addError(type, description, value); + } + + boost::property_tree::ptree enumSection = p.second.get_child("enum", boost::property_tree::ptree()); + for (const std::pair<std::string, boost::property_tree::ptree> &a_item : enumSection) + { + std::string description = a_item.second.get<std::string>("<xmlattr>.d", "error"); + int value = a_item.second.get<int>("<xmlattr>.v"); //mandatory + a_parameter.m_enumeration.push_back(std::pair<std::string,int>(description,value)); + } + + a_map->addVariable(name, a_parameter); + } + } + + push_back(a_map); + } + catch (boost::property_tree::xml_parser_error& err) + { + Logger::log(err.message(), Logger::Error); + return false; + } + catch (boost::property_tree::ptree_bad_data& err) + { + Logger::log(err.what(), Logger::Error); + return false; + } + catch (boost::property_tree::ptree_bad_path& err) + { + Logger::log(err.what(), Logger::Error); + return false; + } + + return true; +} + +std::vector<std::string> ConfigStorage::getNames(void) const +{ + std::vector<std::string> rc; + for (const auto a_config : *this) + { + rc.emplace_back(a_config->getName()); + } + return rc; +} + +ConfigMapShared ConfigStorage::getConfig(int n) const +{ + std::list<ConfigMapShared>::const_iterator it; + for (it = begin(); it != end(); it++) + if (n-- == 0) + { + return (*it); + } + return ConfigMapShared(); +} + +ConfigMapShared ConfigStorage::getConfig(const std::string& name) const +{ + for (const auto& it : *this) + { + if (it->getName() == name) + return it; + } + return ConfigMapShared(); +} \ No newline at end of file diff --git a/pool/shard007/C++/0093141_logger.cpp b/pool/shard007/C++/0093141_logger.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1edad0e70636108cb814fe4c86499d325e1fb50 --- /dev/null +++ b/pool/shard007/C++/0093141_logger.cpp @@ -0,0 +1,255 @@ +#include "logger.h" + +#include "../fc.h" + +#include "igc.h" +#include "kml.h" +#include "raw.h" +#include "aero.h" + +FIL log_file; +uint32_t logger_next = 0; +uint8_t logger_flight_number; +uint32_t logger_flight_day; + +void logger_init() +{ + fc.logger_state = LOGGER_IDLE; + + uint8_t sec, min, hour, day, wday, month; + uint16_t year; + uint32_t today; + + + datetime_from_epoch(time_get_local(), &sec, &min, &hour, &day, &wday, &month, &year); + today = datetime_to_epoch(0, 0, 0, day, month, year); + + eeprom_busy_wait(); + eeprom_read_block((void *)&logger_flight_day, &config_ro.flight_date, sizeof(logger_flight_day)); + logger_flight_number = eeprom_read_byte(&config_ro.flight_number); + + if (logger_flight_day != today) + { + logger_flight_number = 0; + logger_flight_day = today; + + eeprom_busy_wait(); + eeprom_update_block((void *)&logger_flight_day, &config_ro.flight_date, sizeof(logger_flight_day)); + eeprom_update_byte(&config_ro.flight_number, logger_flight_number); + } + + DEBUG("date is: "); + print_datetime(today); + DEBUG("flight number is: %d\n", logger_flight_number); + +} + +void logger_next_flight() +{ + uint8_t sec, min, hour, day, wday, month; + uint16_t year; + uint32_t today; + + + datetime_from_epoch(time_get_local(), &sec, &min, &hour, &day, &wday, &month, &year); + today = datetime_to_epoch(0, 0, 0, day, month, year); + + if (today == logger_flight_day) + { + logger_flight_number++; + + eeprom_busy_wait(); + eeprom_update_byte(&config_ro.flight_number, logger_flight_number); + } + else + { + logger_flight_number = 0; + logger_flight_day = today; + + eeprom_busy_wait(); + eeprom_update_block((void *)&logger_flight_day, &config_ro.flight_date, sizeof(logger_flight_day)); + eeprom_update_byte(&config_ro.flight_number, logger_flight_number); + } + + DEBUG("date is: "); + print_datetime(today); + DEBUG("flight number is: %d\n", logger_flight_number); +} + +void logger_step() +{ + if (!logger_active()) + return; + + if (logger_next > task_get_ms_tick()) + return; + + if (!fc.vario.valid) + return; + + //RAW is running as fast as it can! + if (config.logger.format != LOGGER_RAW && config.logger.format != LOGGER_AERO) + { + if (fc.gps_data.new_sample & FC_GPS_NEW_SAMPLE_LOGGER) + { + logger_next = task_get_ms_tick() + 1000; + fc.gps_data.new_sample &= ~FC_GPS_NEW_SAMPLE_LOGGER; + } + } + + switch (config.logger.format) + { + case(LOGGER_IGC): + igc_step(); + break; + + case(LOGGER_KML): + kml_step(); + break; + + case(LOGGER_RAW): + raw_step(); + break; + + case(LOGGER_AERO): + aero_step(); + break; + } +} + +/** + * printf-like function to send output to the GPS log . + * + * \param format a printf-like format string that must reside in PROGMEM. + * + */ +void logger_comment(const char *format, ...) +{ + va_list arp; + char text[80]; + + if (!logger_active()) + return; + + va_start(arp, format); + vsnprintf_P(text, sizeof(text), format, arp); + va_end(arp); + + switch (config.logger.format) + { + case(LOGGER_IGC): + igc_comment(text); + break; + + case(LOGGER_KML): + kml_comment(text); + break; + + case(LOGGER_RAW): + case(LOGGER_AERO): + DEBUG("%s\n", text); + break; + } +} + +void logger_start() +{ + if (!config.logger.enabled) + return; + + logger_next_flight(); + + if (!storage_ready()) + { + gui_showmessage_P(PSTR("SD card error!")); + + fc.logger_state = LOGGER_ERROR; + + return; + } + + uint8_t sec; + uint8_t min; + uint8_t hour; + uint8_t day; + uint8_t wday; + uint8_t month; + uint16_t year; + + datetime_from_epoch(time_get_utc(), &sec, &min, &hour, &day, &wday, &month, &year); + + char path[128]; + + //base dir + sprintf_P(path, PSTR("%S"), LOG_DIR_P); + f_mkdir(path); + //year + sprintf_P(path, PSTR("%S/%04u"), LOG_DIR_P, year, month, day); + f_mkdir(path); + //month-day + sprintf_P(path, PSTR("%S/%04u/%02u-%02u"), LOG_DIR_P, year, month, day); + f_mkdir(path); + + switch (config.logger.format) + { + case(LOGGER_IGC): + fc.logger_state = igc_start(path); + break; + + case(LOGGER_KML): + fc.logger_state = kml_start(path); + break; + + case(LOGGER_RAW): + fc.logger_state = raw_start(path); + break; + + case(LOGGER_AERO): + fc.logger_state = aero_start(path); + break; + } +} + +//logger is active or it is waiting for gps +bool logger_active() +{ + return (fc.logger_state == LOGGER_ACTIVE || fc.logger_state == LOGGER_WAIT_FOR_GPS); +} + +bool logger_error() +{ + return fc.logger_state == LOGGER_ERROR; +} + +void logger_stop() +{ + if (!logger_active()) + return; + + if (fc.logger_state == LOGGER_WAIT_FOR_GPS) + { + logger_comment(PSTR("No GPS fix during flight!")); + } + + fc.logger_state = LOGGER_IDLE; + + switch (config.logger.format) + { + case(LOGGER_IGC): + igc_stop(); + break; + + case(LOGGER_KML): + kml_stop(); + break; + + case(LOGGER_RAW): + raw_stop(); + break; + + case(LOGGER_AERO): + aero_stop(); + break; + } +} + diff --git a/pool/shard007/C++/0093152_main_draw.cpp b/pool/shard007/C++/0093152_main_draw.cpp new file mode 100644 index 0000000000000000000000000000000000000000..723c8c6794edadaefb086ea8d5b215c43ae794ba --- /dev/null +++ b/pool/shard007/C++/0093152_main_draw.cpp @@ -0,0 +1,21 @@ +#include <iostream> +#include <random> + +#include "array2d.hpp" +#include "maze.hpp" +#include SPECIFIC_HEADER + +int main() +{ + auto dim = Dimension{80,80}; + auto start_pt = Point{0,0}; + auto end_pt = Point{79,79}; + + Array2D array2d(dim); + generate_maze(array2d.data(), dim, start_pt, end_pt, std::random_device{}()); + array2d.print(std::cout); + + return array2d.data()[start_pt.y][start_pt.x] == to_char(MazeElement::Start) + && array2d.data()[end_pt.y][end_pt.x] == to_char(MazeElement::End); +} + diff --git a/pool/shard007/C++/0093154_JitArm64_SystemRegisters.cpp b/pool/shard007/C++/0093154_JitArm64_SystemRegisters.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7c72a0ccac80049761802164eb50fcf8ba29323e --- /dev/null +++ b/pool/shard007/C++/0093154_JitArm64_SystemRegisters.cpp @@ -0,0 +1,60 @@ +// Copyright 2014 Dolphin Emulator Project +// Licensed under GPLv2 +// Refer to the license.txt file included. + +#include "Common/Arm64Emitter.h" +#include "Common/Common.h" + +#include "Core/Core.h" +#include "Core/CoreTiming.h" +#include "Core/PowerPC/PowerPC.h" +#include "Core/PowerPC/PPCTables.h" +#include "Core/PowerPC/JitArm64/Jit.h" +#include "Core/PowerPC/JitArm64/JitAsm.h" + +FixupBranch JitArm64::JumpIfCRFieldBit(int field, int bit, bool jump_if_set) +{ + ARM64Reg WA = gpr.GetReg(); + ARM64Reg XA = EncodeRegTo64(WA); + + FixupBranch branch; + switch (bit) + { + case CR_SO_BIT: // check bit 61 set + LDR(INDEX_UNSIGNED, XA, X29, PPCSTATE_OFF(cr_val[field])); + branch = jump_if_set ? TBNZ(XA, 61) : TBZ(XA, 61); + break; + case CR_EQ_BIT: // check bits 31-0 == 0 + LDR(INDEX_UNSIGNED, WA, X29, PPCSTATE_OFF(cr_val[field])); + branch = jump_if_set ? CBZ(WA) : CBNZ(WA); + break; + case CR_GT_BIT: // check val > 0 + LDR(INDEX_UNSIGNED, XA, X29, PPCSTATE_OFF(cr_val[field])); + CMP(XA, SP); + branch = B(jump_if_set ? CC_GT : CC_LE); + break; + case CR_LT_BIT: // check bit 62 set + LDR(INDEX_UNSIGNED, XA, X29, PPCSTATE_OFF(cr_val[field])); + branch = jump_if_set ? TBNZ(XA, 62) : TBZ(XA, 62); + break; + default: + _assert_msg_(DYNA_REC, false, "Invalid CR bit"); + } + + gpr.Unlock(WA); + return branch; +} + +void JitArm64::mtmsr(UGeckoInstruction inst) +{ + INSTRUCTION_START + // Don't interpret this, if we do we get thrown out + //JITDISABLE(bJITSystemRegistersOff) + + STR(INDEX_UNSIGNED, gpr.R(inst.RS), X29, PPCSTATE_OFF(msr)); + + gpr.Flush(FlushMode::FLUSH_ALL); + fpr.Flush(FlushMode::FLUSH_ALL); + + WriteExit(js.compilerPC + 4); +} diff --git a/pool/shard007/C++/0093156_BattlefieldMgr.cpp b/pool/shard007/C++/0093156_BattlefieldMgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..39a9da09504896982ba59cd8a0eb0fa946eaf4a2 --- /dev/null +++ b/pool/shard007/C++/0093156_BattlefieldMgr.cpp @@ -0,0 +1,158 @@ +/* + * Copyright (C) 2008-2017 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "BattlefieldMgr.h" +#include "BattlefieldWG.h" +#include "BattlefieldTB.h" +#include "Log.h" +#include "Player.h" + +BattlefieldMgr::BattlefieldMgr() +{ + _updateTimer = 0; +} + +BattlefieldMgr::~BattlefieldMgr() +{ + for (BattlefieldSet::iterator itr = _battlefieldSet.begin(); itr != _battlefieldSet.end(); ++itr) + delete *itr; + + _battlefieldMap.clear(); +} + +BattlefieldMgr* BattlefieldMgr::instance() +{ + static BattlefieldMgr instance; + return &instance; +} + +void BattlefieldMgr::InitBattlefield() +{ + Battlefield* wg = new BattlefieldWG(); + // respawn, init variables + if (!wg->SetupBattlefield()) + { + TC_LOG_INFO("bg.battlefield", "Battlefield: Wintergrasp init failed."); + delete wg; + } + else + { + _battlefieldSet.push_back(wg); + TC_LOG_INFO("bg.battlefield", "Battlefield: Wintergrasp successfully initiated."); + } + + Battlefield* tb = new BattlefieldTB; + // respawn, init variables + if (!tb->SetupBattlefield()) + { + TC_LOG_DEBUG("bg.battlefield", "Battlefield: Tol Barad init failed."); + delete tb; + } + else + { + _battlefieldSet.push_back(tb); + TC_LOG_DEBUG("bg.battlefield", "Battlefield: Tol Barad successfully initiated."); + } +} + +void BattlefieldMgr::AddZone(uint32 zoneId, Battlefield* bf) +{ + _battlefieldMap[zoneId] = bf; +} + +void BattlefieldMgr::HandlePlayerEnterZone(Player* player, uint32 zoneId) +{ + BattlefieldMap::iterator itr = _battlefieldMap.find(zoneId); + if (itr == _battlefieldMap.end()) + return; + + Battlefield* bf = itr->second; + if (!bf->IsEnabled() || bf->HasPlayer(player)) + return; + + bf->HandlePlayerEnterZone(player, zoneId); + TC_LOG_DEBUG("bg.battlefield", "%s entered battlefield id %u", player->GetGUID().ToString().c_str(), bf->GetTypeId()); +} + +void BattlefieldMgr::HandlePlayerLeaveZone(Player* player, uint32 zoneId) +{ + BattlefieldMap::iterator itr = _battlefieldMap.find(zoneId); + if (itr == _battlefieldMap.end()) + return; + + // teleport: remove once in removefromworld, once in updatezone + if (!itr->second->HasPlayer(player)) + return; + + itr->second->HandlePlayerLeaveZone(player, zoneId); + TC_LOG_DEBUG("bg.battlefield", "Player %s left battlefield id %u", player->GetGUID().ToString().c_str(), itr->second->GetTypeId()); +} + +Battlefield* BattlefieldMgr::GetBattlefieldToZoneId(uint32 zoneId) +{ + BattlefieldMap::iterator itr = _battlefieldMap.find(zoneId); + if (itr == _battlefieldMap.end()) + { + // no handle for this zone, return + return nullptr; + } + + if (!itr->second->IsEnabled()) + return nullptr; + + return itr->second; +} + +Battlefield* BattlefieldMgr::GetBattlefieldByBattleId(uint32 battleId) +{ + for (BattlefieldSet::iterator itr = _battlefieldSet.begin(); itr != _battlefieldSet.end(); ++itr) + { + if ((*itr)->GetBattleId() == battleId) + return *itr; + } + return nullptr; +} + +Battlefield* BattlefieldMgr::GetBattlefieldByQueueId(uint64 queueId) +{ + for (Battlefield* bf : _battlefieldSet) + if (bf->GetQueueId() == queueId) + return bf; + + return NULL; +} + +ZoneScript* BattlefieldMgr::GetZoneScript(uint32 zoneId) +{ + BattlefieldMap::iterator itr = _battlefieldMap.find(zoneId); + if (itr != _battlefieldMap.end()) + return itr->second; + + return nullptr; +} + +void BattlefieldMgr::Update(uint32 diff) +{ + _updateTimer += diff; + if (_updateTimer > BATTLEFIELD_OBJECTIVE_UPDATE_INTERVAL) + { + for (BattlefieldSet::iterator itr = _battlefieldSet.begin(); itr != _battlefieldSet.end(); ++itr) + if ((*itr)->IsEnabled()) + (*itr)->Update(_updateTimer); + _updateTimer = 0; + } +} diff --git a/pool/shard007/C++/0093157_bullet_gvr_utils.cpp b/pool/shard007/C++/0093157_bullet_gvr_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5451fa869b633805f979c92aaffd35546c09f0d3 --- /dev/null +++ b/pool/shard007/C++/0093157_bullet_gvr_utils.cpp @@ -0,0 +1,120 @@ +/* Copyright 2015 Samsung Electronics Co., LTD + * + * 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 "bullet_gvr_utils.h" + +#include <BulletCollision/CollisionShapes/btShapeHull.h> + +namespace gvr { + +btCollisionShape *convertCollider2CollisionShape(Collider *collider) { + btCollisionShape *shape = NULL; + + if (collider->shape_type() == COLLIDER_SHAPE_BOX) { + return convertBoxCollider2CollisionShape(static_cast<BoxCollider *>(collider)); + } else if (collider->shape_type() == COLLIDER_SHAPE_SPHERE) { + return convertSphereCollider2CollisionShape(static_cast<SphereCollider *>(collider)); + } else if (collider->shape_type() == COLLIDER_SHAPE_MESH) { + return convertMeshCollider2CollisionShape(static_cast<MeshCollider *>(collider)); + } + + return NULL; +} + +btCollisionShape *convertSphereCollider2CollisionShape(SphereCollider *collider) { + btCollisionShape *shape = NULL; + + if (collider != NULL) { + shape = new btSphereShape(btScalar(collider->get_radius())); + } + + return shape; +} + +btCollisionShape *convertBoxCollider2CollisionShape(BoxCollider *collider) { + btCollisionShape *shape = NULL; + + if (collider != NULL) { + shape = new btBoxShape(btVector3(collider->get_half_extents().x, + collider->get_half_extents().y, + collider->get_half_extents().z)); + } + + return shape; +} + +btCollisionShape *convertMeshCollider2CollisionShape(MeshCollider *collider) { + btCollisionShape *shape = NULL; + + if (collider != NULL) { + shape = createConvexHullShapeFromMesh(collider->mesh()); + } + + return shape; +} + +btConvexHullShape *createConvexHullShapeFromMesh(Mesh *mesh) { + btConvexHullShape *hull_shape = NULL; + + if (mesh != NULL) { + btConvexHullShape *initial_hull_shape = NULL; + btShapeHull *hull_shape_optimizer = NULL; + unsigned short vertex_index; + + initial_hull_shape = new btConvexHullShape(); + + for (int i = 0; i < mesh->indices().size(); i++) { + vertex_index = mesh->indices()[i]; + + btVector3 vertex(mesh->vertices()[vertex_index].x, + mesh->vertices()[vertex_index].y, + mesh->vertices()[vertex_index].z); + + initial_hull_shape->addPoint(vertex); + } + + btScalar margin(initial_hull_shape->getMargin()); + hull_shape_optimizer = new btShapeHull(initial_hull_shape); + hull_shape_optimizer->buildHull(margin); + + hull_shape = new btConvexHullShape( + (btScalar *) hull_shape_optimizer->getVertexPointer(), + hull_shape_optimizer->numVertices()); + } else { + LOGD("createConvexHullShapeFromMesh(): NULL mesh object"); + } + + return hull_shape; +} + +btTransform convertTransform2btTransform(const Transform *t) { + btQuaternion rotation(t->rotation_x(), t->rotation_y(), t->rotation_z(), t->rotation_w()); + + btVector3 position(t->position_x(), t->position_y(), t->position_z()); + + btTransform transform(rotation, position); + + return transform; +} + +void convertBtTransform2Transform(btTransform bulletTransform, Transform *transform) { + btVector3 pos = bulletTransform.getOrigin(); + btQuaternion rot = bulletTransform.getRotation(); + + transform->set_position(pos.getX(), pos.getY(), pos.getZ()); + transform->set_rotation(rot.getW(), rot.getX(), rot.getY(), rot.getZ()); +} + +} diff --git a/pool/shard007/C++/0093158_test_extras.cpp b/pool/shard007/C++/0093158_test_extras.cpp new file mode 100644 index 0000000000000000000000000000000000000000..58afbaa6fa3e7db338d7be691125c31804e382e4 --- /dev/null +++ b/pool/shard007/C++/0093158_test_extras.cpp @@ -0,0 +1,76 @@ +#include "catch.hpp" +#include "LuaBinding.h" + +void run( lua_State* L, const char* code ); + +using namespace ManualBind; + +class Extra +{ +}; + +using ExtraPtr = std::shared_ptr<Extra>; + +struct ExtraBinding : public Binding<ExtraBinding,Extra> +{ + static constexpr const char* class_name = "Extra"; + + static void setExtraMeta( lua_State* L ) + { + lua_pushliteral( L, "Alara" ); + lua_setfield( L, -2, "DEF_NAME" ); + } +}; + +TEST_CASE( "Can set extra elements in class meta table." ) { + + lua_State* L = luaL_newstate(); + + ExtraBinding::register_class( L ); + + ExtraPtr pp = std::make_shared<Extra>(); + + ExtraBinding::push( L, pp ); + lua_setglobal( L, "person" ); + + run( L, "name = person.DEF_NAME" ); + + lua_getglobal( L, "name" ); + std::string name( lua_tostring( L, -1 ) ); + + REQUIRE( name == "Alara" ); + + lua_close( L ); +} + +TEST_CASE( "Lua can assign extra elements per instance." ) { + + lua_State* L = luaL_newstate(); + + ExtraBinding::register_class( L ); + + ExtraPtr p1 = std::make_shared<Extra>(); + ExtraBinding::push( L, p1 ); + lua_setglobal( L, "p1" ); + + ExtraPtr p2 = std::make_shared<Extra>(); + ExtraBinding::push( L, p2 ); + lua_setglobal( L, "p2" ); + + run( L, "p1.perinstance = 'Nigel'" ); + + run( L, "name = p1.perinstance" ); + + lua_getglobal( L, "name" ); + std::string name( lua_tostring( L, -1 ) ); + + REQUIRE( name == "Nigel" ); + + run( L, "name = p2.perinstance" ); + + lua_getglobal( L, "name" ); + + REQUIRE( lua_type( L, -1 ) == LUA_TNIL ); + + lua_close( L ); +}; diff --git a/pool/shard007/C++/0093167_main.cpp b/pool/shard007/C++/0093167_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f02181422f22b1cae5086b08aa984fb06937e58b --- /dev/null +++ b/pool/shard007/C++/0093167_main.cpp @@ -0,0 +1,81 @@ +#include "NodoArbolBinario.h" +#include "Evaluador.h" +#include <iostream> // std::cin, std::cout +#include <list> // std::list +using namespace std; + + +//Devuelve la suma de todos los numeros del arbol con la raiz dada. +int suma(NodoArbolBinario* raiz) +{ + int contador;//VARIABLE QUE CONTAVILIZA EL NUMERO DE LOS NODOS + + if(raiz == NULL)//CQASO BASE EN CONDICIONES QUE EL NODO SEA NULL + return 0; + + contador = raiz->num;//CUERPO DONDE SE IGUALA EL CONTADOR AL NUMERO DEL NODO + + contador += suma(raiz->hijo_izq)+ suma(raiz->hijo_der); // LLAMADA RECURSIVA PARA SUMAR EL NUMERO DE AMBOS HIJOS + + return contador; //RETORNA LA VARIABLE QUE CONTABILIZO TODOS LOS VALORES DEL ARBOL + +} + +//Devuelve la cantidad de nodos que tiene el arbol con la raiz dada. +int cantidadNodos(NodoArbolBinario* raiz) +{ + int contador=0; //VARIABLE INICIALIZADA EN 0 POR SE CONTABLE + + if(raiz==NULL) //CASO BASE QUE DEVUELVE 0 SI EL NODO ES NULL + return 0; + + contador ++; //CUERPO DE LA VARIABLE CONTADOR POSTINCREMENTO + + contador += cantidadNodos(raiz->hijo_izq) + cantidadNodos(raiz->hijo_der);//LLAMADA RECURSIVA DONDE SE SUMA EN UNO EL CONTADOR + + return contador; //RETORNA LA VARIABLE CONTABLE; +} + +//Devuelve el promedio de los numeros que tiene el arbol con la raiz dada. +int promedio(NodoArbolBinario* raiz) +{ + return suma(raiz) / cantidadNodos(raiz); +} + +//Devuelve la cantidad de pasos que tiene que dar el algoritmo para llegar a un numero dado. +//Ejemplo: http://www.comp.nus.edu.sg/~stevenha/visualization/bst.html +//Para llegar al nodo 7 se ocupan 3 pasos (15,6,7) +//Para llegar al nodo 5 se ocupan 4 pasos (15,6,4,5) +//Para llegar al nodo 15 se ocupa 1 paso (15) +int cuantosPasos(NodoArbolBinario* raiz,int num) +{ + int contador =1; // VARIABLE CONTADOR DE PASOS + + if(raiz==NULL) // CASO BASE RETORNA EL CONTADOR + return contador; + + if(raiz->num == num) // CUERPO, SI ES IGUAL EL NUMERO BUSCADO DE RETORNA 1 + return contador; + + + if(num>raiz->num) // SE CONDICIONA SI EL NUMERO ES MAYOR QUE LA RAIZ + contador += cuantosPasos(raiz->hijo_der,num); // RECURSIVAMENTE BUSCAMOS LOS HIJOS POR LA DERECHA Y SE SUMAN LOS PASOS + + if(num<raiz->num) // SE CONDICIONA SI EL NUMERO ES MENOR QUE LA RAIZ + contador += cuantosPasos(raiz->hijo_izq,num); // RECURSIVAMENTE BUSCAMOS LOS HIJOS DE LA IZQUIERDA Y SE SUMAN LOS PASOS + + return contador; // RETORNA LOS PASOS +} + +//Devuelve verdadero si el arbol dado esta ordenado estilo AVL, de lo contrario devuelve falso. +bool esAVL(NodoArbolBinario* raiz) +{ + return false; +} + +int main () +{ + //Funcion evaluadora + evaluar(); + return 1; +} diff --git a/pool/shard007/C++/0093171_EventBridge.cpp b/pool/shard007/C++/0093171_EventBridge.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a94dc1789bd7a4f93d678efe6cc1ea29e74d1547 --- /dev/null +++ b/pool/shard007/C++/0093171_EventBridge.cpp @@ -0,0 +1,165 @@ +/* +Copyright_License { + + XCSoar Glide Computer - http://www.xcsoar.org/ + Copyright (C) 2000-2021 The XCSoar Project + A detailed list of copyright holders can be found in the file "AUTHORS". + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +} +*/ + +#include "org_xcsoar_EventBridge.h" +#include "Product.hpp" +#include "ui/event/Queue.hpp" +#include "ui/event/Idle.hpp" +#include "ui/event/Globals.hpp" +#include "system/Clock.hpp" +#include "util/Compiler.h" + +using namespace UI; + +/** + * @see http://developer.android.com/reference/android/view/KeyEvent.html + */ +enum { + KEYCODE_BACK = 0x04, + KEYCODE_0 = 0x07, + KEYCODE_9 = 0x10, + KEYCODE_A = 0x1d, + KEYCODE_Z = 0x36, + KEYCODE_ESCAPE = 0x6f, +}; + +static constexpr unsigned KEYCODE_DPAD_UP = 0x13; +static constexpr unsigned KEYCODE_DPAD_DOWN = 0x14; + +static unsigned +TranslateKeyCode(unsigned key_code) +{ + if (key_code == KEYCODE_BACK) + /* the "back" key acts as escape */ + return KEYCODE_ESCAPE; + + if (key_code >= KEYCODE_0 && key_code <= KEYCODE_9) + return '0' + (key_code - KEYCODE_0); + + if (key_code >= KEYCODE_A && key_code <= KEYCODE_Z) + /* return upper-case character, because InputEvents::findKey() + calls ToUpperASCII() */ + return 'A' + (key_code - KEYCODE_A); + + return key_code; +} + +constexpr +static bool +IsCursorKey(unsigned key_code) +{ + return key_code == KEYCODE_DPAD_UP || key_code == KEYCODE_DPAD_DOWN; +} + +gcc_visibility_default +void +Java_org_xcsoar_EventBridge_onKeyDown(JNIEnv *env, jclass cls, jint key_code) +{ + if (event_queue == nullptr) + /* XCSoar not yet initialised */ + return; + + if (!has_cursor_keys && IsCursorKey(key_code)) + /* enable this flag as soon as we see the first cursor event; used + by HasCursorKeys() */ + has_cursor_keys = true; + + event_queue->Push(Event(Event::KEY_DOWN, TranslateKeyCode(key_code))); + ResetUserIdle(); +} + +gcc_visibility_default +void +Java_org_xcsoar_EventBridge_onKeyUp(JNIEnv *env, jclass cls, jint key_code) +{ + if (event_queue == nullptr) + /* XCSoar not yet initialised */ + return; + + event_queue->Push(Event(Event::KEY_UP, TranslateKeyCode(key_code))); + ResetUserIdle(); +} + +gcc_visibility_default +void +Java_org_xcsoar_EventBridge_onMouseDown(JNIEnv *env, jclass cls, + jint x, jint y) +{ + if (event_queue == nullptr) + /* XCSoar not yet initialised */ + return; + + event_queue->Push(Event(Event::MOUSE_DOWN, PixelPoint(x, y))); + ResetUserIdle(); +} + +gcc_visibility_default +void +Java_org_xcsoar_EventBridge_onMouseUp(JNIEnv *env, jclass cls, + jint x, jint y) +{ + if (event_queue == nullptr) + /* XCSoar not yet initialised */ + return; + + event_queue->Push(Event(Event::MOUSE_UP, PixelPoint(x, y))); + ResetUserIdle(); +} + +gcc_visibility_default +void +Java_org_xcsoar_EventBridge_onMouseMove(JNIEnv *env, jclass cls, + jint x, jint y) +{ + if (event_queue == nullptr) + /* XCSoar not yet initialised */ + return; + + event_queue->Purge(Event::MOUSE_MOTION); + event_queue->Push(Event(Event::MOUSE_MOTION, PixelPoint(x, y))); + ResetUserIdle(); +} + +gcc_visibility_default +void +Java_org_xcsoar_EventBridge_onPointerDown(JNIEnv *env, jclass cls) +{ + if (event_queue == nullptr) + /* XCSoar not yet initialised */ + return; + + event_queue->Push(Event(Event::POINTER_DOWN)); + ResetUserIdle(); +} + +gcc_visibility_default +void +Java_org_xcsoar_EventBridge_onPointerUp(JNIEnv *env, jclass cls) +{ + if (event_queue == nullptr) + /* XCSoar not yet initialised */ + return; + + event_queue->Push(Event(Event::POINTER_UP)); + ResetUserIdle(); +} diff --git a/pool/shard007/C++/0093179_main.cc b/pool/shard007/C++/0093179_main.cc new file mode 100644 index 0000000000000000000000000000000000000000..e783b53bb289410c09ca13ac9a66291b6d04905a --- /dev/null +++ b/pool/shard007/C++/0093179_main.cc @@ -0,0 +1,100 @@ +// Copyright (c) 2016, reginell. All rights reserved. +// Use of this source code is governed by a BSD license that can be +// found in the LICENSE file. +// +// Subject: Algorithms and Data structures (AaDs). + +#include <cmath> +#include <cstddef> +#include <iomanip> +#include <iostream> +#include <vector> + +using usize = std::size_t; +using i32 = int; +using f64 = double; + +template <typename T, typename Y> +constexpr inline T implicit_cast(const Y& value) noexcept { + return value; +} + +template <class T> +using vec = std::vector<T, std::allocator<T>>; + +f64 f(f64 x) noexcept { return std::pow(x, 2) + 5 * std::cos(x) - 3; } + +f64 MD(f64 a, f64 b, f64 e) noexcept { + f64 x[3], y[3]{}; + x[0] = a; + x[1] = b; + y[0] = f(x[0]); + + do { + x[2] = (x[0] + x[1]) / 2; + y[2] = f(x[2]); + const f64 v = y[0] * y[2]; + + if (v > 0) { + x[0] = x[2]; + y[0] = y[2]; + } else { + x[1] = x[2]; + y[1] = y[2]; + } + } while ((x[1] - x[0]) > e); + + return (x[0] + x[1]) / 2; +} + +int main() { + i32 a, b; + f64 m, e; + + std::cout << "a = "; + std::cin >> a; + std::cout << "b = "; + std::cin >> b; + std::cout << "m = "; + std::cin >> m; + std::cout << "e = "; + std::cin >> e; + + const f64 h{(b * 1.0 - a) / m}; + f64 X = a; + f64 y{f(X)}; + + std::cout.flags(std::ios::right); + std::cout.precision(4); //-V112 + + std::cout << std::setw(9) << "X" + << "\t" << std::setw(9) << "Y" << std::endl; + std::cout << std::setw(9) << X << "\t" << std::setw(9) << y << std::endl; + + X += h; + f64 u{y}; + + auto z = vec<f64>(implicit_cast<usize>(m) + 1); + usize i{0}; + + while (X <= b) { + y = f(X); + std::cout << std::setw(9) << X << "\t" << std::setw(9) << y << std::endl; + + if ((u > 0 && y < 0) || (u < 0 && y > 0)) { + z[i++] = MD(X - h, X, e); + } + + u = y; + X += h; + } + + const usize k{i}; + std::cout << std::endl; + + for (i = 0; i < k; i++) + std::cout << "X" << i + 1 << " = " << z[i] << ", e = " << std::fabs(f(z[i])) + << std::endl; + + return 0; +} diff --git a/pool/shard007/C++/0093209_utility-test.cpp b/pool/shard007/C++/0093209_utility-test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7c3f9f45795ad656399e504d69129867277fa208 --- /dev/null +++ b/pool/shard007/C++/0093209_utility-test.cpp @@ -0,0 +1,38 @@ +/** + * @file utility-test.cpp + * @author Beren Oguz <berenoguz@gmail.com> + * @date 07-29-2015 + * @copyright Beren Oguz (c) 2015 + * @license This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "kafka.hpp" + +using namespace kafka; +using namespace kafka::lib; + +int main() +{ + try{ + Generator generator; + File file("Kafkafile", File::in); + ConfigFile config_file(file); + Config config = std::move(config_file.get_config()); + generator.take_config(std::move(config)); + } + catch(const BadConfigFile& error){ + std::cerr << "Configuration file error: " << error.what() << "! Please provide necessary changes to your Kafkafile or other configuration file." << std::endl; + std::cerr << "Aborting..." << std::endl; + } +} diff --git a/pool/shard007/C++/0093210_url_request_util.cc b/pool/shard007/C++/0093210_url_request_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..e86e14bf78e3e08230f50f49b9da3db9e0cf1fbc --- /dev/null +++ b/pool/shard007/C++/0093210_url_request_util.cc @@ -0,0 +1,166 @@ +// Copyright 2015 The Chromium Embedded Framework Authors. +// Portions 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 "libcef/browser/extensions/url_request_util.h" + +#include <string> + +#include "base/files/file_path.h" +#include "base/memory/weak_ptr.h" +#include "base/path_service.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" +#include "base/task_runner_util.h" +#include "chrome/common/chrome_paths.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/resource_request_info.h" +#include "extensions/browser/component_extension_resource_manager.h" +#include "extensions/browser/extension_protocols.h" +#include "extensions/browser/extensions_browser_client.h" +#include "extensions/browser/info_map.h" +#include "extensions/browser/url_request_util.h" +#include "extensions/common/file_util.h" +#include "net/base/mime_util.h" +#include "net/base/net_errors.h" +#include "net/http/http_request_headers.h" +#include "net/http/http_response_headers.h" +#include "net/http/http_response_info.h" +#include "net/url_request/url_request.h" +#include "net/url_request/url_request_simple_job.h" +#include "ui/base/resource/resource_bundle.h" + +using content::BrowserThread; +using content::ResourceType; +using extensions::ExtensionsBrowserClient; + +namespace { + +// A request for an extension resource in a Chrome .pak file. These are used +// by component extensions. +class URLRequestResourceBundleJob : public net::URLRequestSimpleJob { + public: + URLRequestResourceBundleJob(net::URLRequest* request, + net::NetworkDelegate* network_delegate, + const base::FilePath& filename, + int resource_id, + const std::string& content_security_policy, + bool send_cors_header) + : net::URLRequestSimpleJob(request, network_delegate), + filename_(filename), + resource_id_(resource_id), + weak_factory_(this) { + // Leave cache headers out of resource bundle requests. + response_info_.headers = extensions::BuildHttpHeaders( + content_security_policy, send_cors_header, base::Time()); + } + + // Overridden from URLRequestSimpleJob: + int GetRefCountedData( + std::string* mime_type, + std::string* charset, + scoped_refptr<base::RefCountedMemory>* data, + const net::CompletionCallback& callback) const override { + const ResourceBundle& rb = ResourceBundle::GetSharedInstance(); + *data = rb.LoadDataResourceBytes(resource_id_); + + // Add the Content-Length header now that we know the resource length. + response_info_.headers->AddHeader( + base::StringPrintf("%s: %s", net::HttpRequestHeaders::kContentLength, + base::UintToString((*data)->size()).c_str())); + + std::string* read_mime_type = new std::string; + bool posted = base::PostTaskAndReplyWithResult( + BrowserThread::GetBlockingPool(), FROM_HERE, + base::Bind(&net::GetMimeTypeFromFile, filename_, + base::Unretained(read_mime_type)), + base::Bind(&URLRequestResourceBundleJob::OnMimeTypeRead, + weak_factory_.GetWeakPtr(), mime_type, charset, *data, + base::Owned(read_mime_type), callback)); + DCHECK(posted); + + return net::ERR_IO_PENDING; + } + + void GetResponseInfo(net::HttpResponseInfo* info) override { + *info = response_info_; + } + + private: + ~URLRequestResourceBundleJob() override {} + + void OnMimeTypeRead(std::string* out_mime_type, + std::string* charset, + scoped_refptr<base::RefCountedMemory> data, + std::string* read_mime_type, + const net::CompletionCallback& callback, + bool read_result) { + *out_mime_type = *read_mime_type; + if (base::StartsWith(*read_mime_type, "text/", + base::CompareCase::INSENSITIVE_ASCII)) { + // All of our HTML files should be UTF-8 and for other resource types + // (like images), charset doesn't matter. + DCHECK(base::IsStringUTF8(base::StringPiece( + reinterpret_cast<const char*>(data->front()), data->size()))); + *charset = "utf-8"; + } + int result = read_result ? net::OK : net::ERR_INVALID_URL; + callback.Run(result); + } + + // We need the filename of the resource to determine the mime type. + base::FilePath filename_; + + // The resource bundle id to load. + int resource_id_; + + net::HttpResponseInfo response_info_; + + mutable base::WeakPtrFactory<URLRequestResourceBundleJob> weak_factory_; +}; + +} // namespace + +namespace extensions { +namespace url_request_util { + +net::URLRequestJob* MaybeCreateURLRequestResourceBundleJob( + net::URLRequest* request, + net::NetworkDelegate* network_delegate, + const base::FilePath& directory_path, + const std::string& content_security_policy, + bool send_cors_header) { + base::FilePath resources_path; + base::FilePath relative_path; + // Try to load extension resources from chrome resource file if + // directory_path is a descendant of resources_path. This path structure is + // set up by CefExtensionSystem::ComponentExtensionInfo. + if (PathService::Get(chrome::DIR_RESOURCES, &resources_path) && + // Since component extension resources are included in + // component_extension_resources.pak file in resources_path, calculate + // extension relative path against resources_path. + resources_path.AppendRelativePath(directory_path, &relative_path)) { + base::FilePath request_path = + extensions::file_util::ExtensionURLToRelativeFilePath(request->url()); + int resource_id = 0; + if (ExtensionsBrowserClient::Get() + ->GetComponentExtensionResourceManager() + ->IsComponentExtensionResource( + directory_path, request_path, &resource_id)) { + relative_path = relative_path.Append(request_path); + relative_path = relative_path.NormalizePathSeparators(); + return new URLRequestResourceBundleJob(request, + network_delegate, + relative_path, + resource_id, + content_security_policy, + send_cors_header); + } + } + return NULL; +} + +} // namespace url_request_util +} // namespace extensions diff --git a/pool/shard007/C++/0093218_xsimtestbench_arch.cpp b/pool/shard007/C++/0093218_xsimtestbench_arch.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9c76787f66d2f60c0251b3b0ad19d733299801ed --- /dev/null +++ b/pool/shard007/C++/0093218_xsimtestbench_arch.cpp @@ -0,0 +1,60 @@ +static const char * HSimCopyRightNotice = "Copyright 2004-2005, Xilinx Inc. All rights reserved."; +#ifdef __MINGW32__ +#include "xsimMinGW.h" +#else +#include "xsim.h" +#endif +#include "C:/Xilinx92i/vhdl/hdp/nt/ieee/std_logic_1164/std_logic_1164.h" +#include "C:/Xilinx92i/vhdl/hdp/nt/ieee/std_logic_arith/std_logic_arith.h" +#include "C:/Xilinx92i/vhdl/hdp/nt/std/textio/textio.h" +#include "C:/Xilinx92i/vhdl/hdp/nt/ieee/std_logic_unsigned/std_logic_unsigned.h" +#include "C:/Xilinx92i/vhdl/hdp/nt/ieee/std_logic_textio/std_logic_textio.h" + +class _top : public HSim__s6 { +public: + _top() : HSim__s6(false, "_top", "_top", 0, 0, HSim::VhdlDesignEntity) {} + HSimConfigDecl * topModuleInstantiate() { + HSimConfigDecl * cfgvh = 0; + cfgvh = new HSimConfigDecl("default"); + (*cfgvh).registerFuseLibList(""); + + HSim__s6 * topvh = 0; + extern HSim__s6 * createWork_sr_testbench_arch(const char*); + topvh = createWork_sr_testbench_arch("sr"); + topvh->constructPorts(); + topvh->checkTopLevelPortsConstrainted(); + topvh->vhdlArchImplement(); + topvh->architectureInstantiate(cfgvh); + addChild(topvh); + return cfgvh; +} +}; + +main(int argc, char **argv) { + HSimDesign::initDesign(); + globalKernel->getOptions(argc,argv); + HSim__s6 * _top_i = 0; + try { + IeeeStd_logic_1164=new Ieee_std_logic_1164("std_logic_1164"); + IeeeStd_logic_arith=new Ieee_std_logic_arith("std_logic_arith"); + StdTextio=new Std_textio("TEXTIO"); + IeeeStd_logic_unsigned=new Ieee_std_logic_unsigned("STD_LOGIC_UNSIGNED"); + IeeeStd_logic_textio=new Ieee_std_logic_textio("STD_LOGIC_TEXTIO"); + HSimConfigDecl *cfg; + _top_i = new _top(); + cfg = _top_i->topModuleInstantiate(); + return globalKernel->runTcl(cfg, _top_i, "_top", argc, argv); + } + catch (HSimError& msg){ + try { + globalKernel->error(msg.ErrMsg); + return 1; + } + catch(...) {} + return 1; + } + catch (...){ + globalKernel->fatalError(); + return 1; + } +} diff --git a/pool/shard007/C++/0093219_intensity_image.cpp b/pool/shard007/C++/0093219_intensity_image.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a3f881b3f1509ebd63dab3155cb00c4f86546ae0 --- /dev/null +++ b/pool/shard007/C++/0093219_intensity_image.cpp @@ -0,0 +1,235 @@ +/* FLIM-CUDA-Primatives + * P Barber <paul.barber@oncology.ox.ac.uk>, 2017 + * Sum the time data at each pixel to produce an intensity image + * Main CPU code. + */ + +// includes, system +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <math.h> +#include <time.h> + +// includes, CUDA +#include <cuda_runtime.h> + +// includes, project +#include <helper_cuda.h> +#include <helper_functions.h> // helper functions for SDK examples + +#include "../../libics/inc/libics.h" + +//////////////////////////////////////////////////////////////////////////////// +// declarations, forward +extern "C" +void computeGold(float *reference, float *idata, size_t ntimepts, size_t width, size_t height); + +extern "C" +void executeCudaKernel(size_t threadsPerBlock, size_t blocksPerGrid, float *g_idata, float *g_odata, size_t ntimepts, size_t width, size_t height); + +//////////////////////////////////////////////////////////////////////////////// +// Macro to time CPU operations +clock_t time_start, time_msec, time_diff; +#define time_this(a) time_start=clock(); a; time_diff = clock() - time_start; time_msec = time_diff * 1000 / CLOCKS_PER_SEC; printf("%s: %d ms\n", #a, time_msec); + +//////////////////////////////////////////////////////////////////////////////// +//! Test code to run the Kernel +int +runTest(int argc, char **argv) +{ + bool bTestResult = true; + ICS *icsHandle; + Ics_Error icsError; + Ics_DataType dataType; + size_t bufSize; + int ndims; + size_t dims[ICS_MAXDIM], ntimepts, width, height; + + printf("%s Starting...\n\n", argv[0]); + + // setup some CUDA timers + StopWatchInterface *hostToDeviceTimer = 0; + StopWatchInterface *timer = 0; + StopWatchInterface *DeviceToHostTimer = 0; + sdkCreateTimer(&hostToDeviceTimer); + sdkCreateTimer(&timer); + sdkCreateTimer(&DeviceToHostTimer); + + // use command-line specified CUDA device, otherwise use device with highest Gflops/s + int devID = findCudaDevice(argc, (const char **)argv); + + // size_t width = 128; + // size_t height = 128; + // size_t ntimepts = 256; + //size_t mem_size = height * width * ntimepts * sizeof(float); + //size_t image_size = height * width * sizeof(float); + // + // // allocate host memory + //float *h_idata = (float*)malloc(mem_size); + + // initalize the memory + //for (size_t y = 0; y < height; ++y) + // { + // float *row_start = h_idata + y * width * ntimepts; + // for (unsigned int x = 0; x < width; ++x) + // { + // float *time = row_start + x * ntimepts; + // for (unsigned int t = 0; t < ntimepts; ++t) + // { + // time[t] = (float)(255-t); + // } + // } + //} + + // load an image + char filename[] = "../../data/Csarseven.ics"; + icsError = IcsOpen(&icsHandle, filename, "r"); + if (icsError != IcsErr_Ok) + { + printf("Could not open %s: %s\n", filename, IcsGetErrorText(icsError)); + goto OpenError; + } + + IcsGetLayout(icsHandle, &dataType, &ndims, dims); + bufSize = IcsGetDataSize(icsHandle); + ntimepts = dims[0]; + width = dims[1]; + height = dims[2]; + + size_t mem_size = height * width * ntimepts * sizeof(float); + size_t image_size = height * width * sizeof(float); + size_t total_pixels = height * width; + + // allocate host memory + float *h_idata = (float*)malloc(mem_size); + unsigned short *data = (unsigned short *)malloc(bufSize); + icsError = IcsGetData(icsHandle, data, bufSize); + if (icsError != IcsErr_Ok) + { + printf("IcsGetData error: %s\n", IcsGetErrorText(icsError)); + goto GetDataError; + } + + // convert data to float + for (size_t t = 0; t < total_pixels*ntimepts; t++) { + h_idata[t] = (float)data[t]; + } + + sdkStartTimer(&hostToDeviceTimer); + + // allocate device memory + float *d_idata; + checkCudaErrors(cudaMalloc(&d_idata, mem_size)); + + // copy host memory to device + checkCudaErrors(cudaMemcpy(d_idata, h_idata, mem_size, cudaMemcpyHostToDevice)); + + sdkStopTimer(&hostToDeviceTimer); + + // allocate device memory for result + float *d_odata; + checkCudaErrors(cudaMalloc((void **) &d_odata, image_size)); + + // setup execution parameters + unsigned int threadsPerBlock = (unsigned int)width; + unsigned int blocksPerGrid = ((unsigned int)(width*height) + threadsPerBlock - 1) / threadsPerBlock; + + // Warm-up + executeCudaKernel(blocksPerGrid, threadsPerBlock, d_idata, d_odata, ntimepts, width, height); + checkCudaErrors(cudaDeviceSynchronize()); + + sdkStartTimer(&timer); + + executeCudaKernel(blocksPerGrid, threadsPerBlock, d_idata, d_odata, ntimepts, width, height); + checkCudaErrors(cudaDeviceSynchronize()); + + // check if kernel execution generated and error + getLastCudaError("Kernel execution failed"); + + sdkStopTimer(&timer); + sdkStartTimer(&DeviceToHostTimer); + + // allocate mem for the result on host side + float *h_odata = (float *) malloc(image_size); + + // copy result from device to host + checkCudaErrors(cudaMemcpy(h_odata, d_odata, image_size, cudaMemcpyDeviceToHost)); + + sdkStopTimer(&DeviceToHostTimer); + + // Report timings + printf("GPU:\n"); + printf("Host To Device time: %f (ms)\n", sdkGetTimerValue(&hostToDeviceTimer)); + printf("Processing time: %f (ms)\n", sdkGetTimerValue(&timer)); + printf("Device To Host time: %f (ms)\n", sdkGetTimerValue(&DeviceToHostTimer)); + sdkDeleteTimer(&hostToDeviceTimer); + sdkDeleteTimer(&timer); + sdkDeleteTimer(&DeviceToHostTimer); + + // Save result image + ICS *icsOutHandle; + size_t outDims[2]; + outDims[0] = height; + outDims[1] = width; + + IcsOpen(&icsOutHandle, "../../data/intensity_image_GPU.ics", "w2"); + IcsSetLayout(icsOutHandle, Ics_real32, 2, outDims); + IcsSetData(icsOutHandle, h_odata, image_size); + IcsClose(icsOutHandle); + + // compute reference solution + float *reference = (float *) malloc(image_size); + printf("CPU:\n"); + time_this(computeGold(h_idata, reference, ntimepts, width, height)); + + IcsOpen(&icsOutHandle, "../../data/intensity_image_CPU.ics", "w2"); + IcsSetLayout(icsOutHandle, Ics_real32, 2, outDims); + IcsSetData(icsOutHandle, reference, image_size); + IcsClose(icsOutHandle); + + + // check result + //if (checkCmdLineFlag(argc, (const char **) argv, "regression")) + //{ + // // write file for regression test + // sdkWriteFile("./data/regression.dat", h_odata, num_threads, 0.0f, false); + //} + //else + //{ + // // custom output handling when no regression test running + // // in this case check if the result is equivalent to the expected soluion + // bTestResult = compareData(reference, h_odata, num_threads, 0.0f, 0.0f); + //} + + // cleanup memory + free(h_idata); + free(h_odata); + free(reference); + checkCudaErrors(cudaFree(d_idata)); + checkCudaErrors(cudaFree(d_odata)); + + // cudaDeviceReset causes the driver to clean up all state. While + // not mandatory in normal operation, it is good practice. It is also + // needed to ensure correct operation when the application is being + // profiled. Calling cudaDeviceReset causes all profile data to be + // flushed before the application exits + cudaDeviceReset(); + + GetDataError: + free(data); + IcsClose(icsHandle); + + OpenError: + return(bTestResult ? EXIT_SUCCESS : EXIT_FAILURE); +} + +//////////////////////////////////////////////////////////////////////////////// +//! Program main +int +main(int argc, char **argv) +{ + int ret = runTest(argc, argv); + + exit(ret); +} diff --git a/pool/shard007/C++/0093224_sshmanager_cli.cpp b/pool/shard007/C++/0093224_sshmanager_cli.cpp new file mode 100644 index 0000000000000000000000000000000000000000..da46df45952056af1f02375161367cb7dca54322 --- /dev/null +++ b/pool/shard007/C++/0093224_sshmanager_cli.cpp @@ -0,0 +1,61 @@ +/********************************************************************** + SSHManager - Manages a collection of SSHConnections + + Copyright (C) 2010-2012 by David C. Lonie + + This source code is released under the New BSD License, (the "License"). + + 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. + ***********************************************************************/ + +#ifdef ENABLE_SSH + +#include <globalsearch/sshmanager_cli.h> + +#include <globalsearch/sshconnection_cli.h> + +namespace GlobalSearch { + + SSHManagerCLI::SSHManagerCLI(unsigned int connections, + OptBase *parent) + : SSHManager(parent), + m_conn(new SSHConnectionCLI()), + m_semaphore(new QSemaphore (connections)) + { + } + + SSHManagerCLI::~SSHManagerCLI() + { + delete m_conn; + delete m_semaphore; + } + + void SSHManagerCLI::makeConnections(const QString &host, + const QString &user, + const QString &pass, + unsigned int port) + { + m_host = host; + m_user = user; + m_port = port; + m_conn->setLoginDetails(host, user, pass, port); + } + + SSHConnection *SSHManagerCLI::getFreeConnection() + { + m_semaphore->acquire(); + return m_conn; + } + + void SSHManagerCLI::unlockConnection(SSHConnection* ssh) + { + m_semaphore->release(); + } + +} // end namespace GlobalSearch + +#endif // ENABLE_SSH diff --git a/pool/shard007/C++/0093226_Timer.cpp b/pool/shard007/C++/0093226_Timer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..12532e9255977530f4a480ce50c298325f8ae449 --- /dev/null +++ b/pool/shard007/C++/0093226_Timer.cpp @@ -0,0 +1,142 @@ +// +// +// MIT License +// +// Copyright (c) 2017 Stellacore Corporation. +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject +// to the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +// KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN +// AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +// + + +/*! \file +\brief Definitions for sys::Timer +*/ + + +#include "libsys/Timer.h" + +#include <iomanip> +#include <sstream> + + +namespace sys +{ +//====================================================================== + +inline +std::string +intervalString + ( std::string const & iname + , double const & ivalue + ) +{ + std::ostringstream oss; + oss << std::fixed << std::setprecision(9); + oss << std::setw(25u) << iname << ": " << std::setw(14u) << ivalue; + return oss.str(); +} + +std::string +Timer::Interval :: infoString + ( std::string const & title + ) const +{ + std::ostringstream oss; + + if (! title.empty()) + { + oss << title << " "; + } + + if (isDone()) + { + // actual interval time + oss << intervalString(theInfo, duration()); + } + else + { + // in progress running time + double const delta(sys::time::relativeNow() - theStart); + oss << intervalString(theInfo, delta) << " (active)"; + } + + return oss.str(); +} + +// +// +// + +double +Timer :: total + () const +{ + double sum(0.); + for (size_t nn(0u) ; nn < theIntervals.size() ; ++nn) + { + Interval const & ival = theIntervals[nn]; + sum += ival.duration(); + } + return sum; +} + +std::string +Timer :: infoString + ( std::string const & title + ) const +{ + std::ostringstream oss; + if (! title.empty()) + { + oss << title << '\n'; + } + + // include each interval + double sum(0.); + for (size_t nn(0u) ; nn < theIntervals.size() ; ++nn) + { + Interval const & ival = theIntervals[nn]; + + if (0u < nn) + { + oss << '\n'; + } + if (ival.isDone()) + { + sum += ival.duration(); + } + oss << ival.infoString(); + } + + // add total time + if (1u < theIntervals.size()) + { + oss << '\n'; + oss << intervalString("--- total ---", sum); + } + + return oss.str(); +} + +//====================================================================== +} + diff --git a/pool/shard007/C++/0093227_tfhelpwindow.cpp b/pool/shard007/C++/0093227_tfhelpwindow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..de0e6d93eccafa9b536b0103cdf335602ab99a1a --- /dev/null +++ b/pool/shard007/C++/0093227_tfhelpwindow.cpp @@ -0,0 +1,185 @@ +/********************************************************************************* + * + * Inviwo - Interactive Visualization Workshop + * + * Copyright (c) 2018-2021 Inviwo Foundation + * 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. + * + * 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 <modules/qtwidgets/tfhelpwindow.h> +#include <inviwo/core/util/document.h> +#include <inviwo/core/common/inviwoapplication.h> +#include <modules/qtwidgets/inviwoqtutils.h> + +#include <warn/push> +#include <warn/ignore/all> +#include <QAction> +#include <QMenu> +#include <QVBoxLayout> +#include <QTextEdit> +#include <warn/pop> + +namespace inviwo { + +TFHelpWindow::TFHelpWindow(QWidget* parent) + : InviwoDockWidget("Help: Transfer Function Editor", parent, "TFHelpWidget") { + setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); + resize(utilqt::emToPx(this, QSizeF(60, 60))); // default size + + auto centralWidget = new QWidget(); + auto vLayout = new QVBoxLayout(centralWidget); + vLayout->setSpacing(utilqt::refSpacePx(this)); + vLayout->setContentsMargins(0, 0, 0, 0); + + auto textedit = new QTextEdit(this); + vLayout->addWidget(textedit); + centralWidget->setLayout(vLayout); + setWidget(centralWidget); + + textedit->setReadOnly(true); + textedit->setUndoRedoEnabled(false); + textedit->setAcceptRichText(true); + + const std::string contents = R"(<h1 style='color:white;'>Transfer Function Editor</h1> +<p>The Transfer Function Editor allows to create and modify a 1D transfer +function (TF) for mapping scalar values to color and opacity. A TF consists of +multiple TF points each associated with a scalar value, i.e. its position, a rgb +color, and an alpha value. The TF is shown in the left area along with the +histogram of the input data. Scalar values are mapped to the horizontal axis +while the vertical axis corresponds to the opacity.</p> + +<h3>Adding TF Points</h3> +<p>TF points are added by pressing <CTRL> and the left mouse button or via +the context menu.</p> +<p>Points can also be duplicated via the context menu, which will offset the new +points slightly to the right.</p> + +<h3>Deleting TF Points</h3> +<p>To delete a point press <Backspace> or <Delete> or use the +context menu.</p> + +<h3>Manipulating TF Points</h3> +<p>Points can be adjusted using the left mouse button or using the Scalar and +Alpha fields on the right-hand side. When using the mouse to move TF points, +<SHIFT> can be used to restrict the movement to either horizontal or +vertical. If <ALT> is pressed while dragging a selection, instead of +moving the selected points, a scaling of the bounding box of the selected points +is applied</p> +<p>Alternatively, the arrow keys move TF points left/right or up/down. +<SHIFT> increases the step size while <ALT> reduces it.</p> + +<h3>Selecting Multiple Points</h3> +<p>Multiple points are selected by a rubber band selection or holding +<CTRL> while left clicking on individual points</p> +<p>A selection can be grouped and recalled later via the context menu or using +<CTRL>+<1>,<2>,<3>, ...,<0> for grouping and +<1>,<2>,<3>, ...,<0> without any modifier for +selecting the respective group. Pressing <SHIFT> while selecting a group +will add the elements of the group to the current selection.</p> + +<h3>Masking the TF</h3> +<p>Parts of the TF can be masked out, i.e. alpha is implicitly set to zero outside +the mask. The context menu provides functionality for setting the begin and end points +of the mask as well as clearing it.</p> + +<h3>On Transfer Function Level</h3> +<p>The entire transfer function can be cleared at once, i.e. all TF points are deleted, +or reset to the properties' default state via the context menu. Furthermore, TFs can be +exported and imported.</p>)"; + + Document doc; + auto html = doc.append("html"); + html.append("head").append("style", + "a { color: #c8ccd0; font-weight: normal;}\n" + "body, table, div, p, dl " + "{color: #9d9995; background-color: #323235; font: 400 14px/18px" + "Calibra, sans-serif;}\n " + "h1, h2, h3, h4 {color: #c8ccd0; margin-bottom:3px;}"); + html.append("body", contents, {{"style", "margin: 7px;"}}); + + std::string str = doc; + textedit->setHtml(utilqt::toQString(str)); +} + +TFMenuHelper::TFMenuHelper() { + if (utilqt::getApplicationMainWindow()) { + showAction_ = std::make_unique<QAction>(QString("&Transfer Function"), nullptr); + QObject::connect(showAction_.get(), &QAction::triggered, this, [this]() { + auto window = getWindow(); + window->activateWindow(); + window->raise(); + window->show(); + }); + + // insert menu entry in the help menu before the "&About" + auto helpMenu = utilqt::getMenu("&Help", true); + auto menuActions = helpMenu->actions(); + if (menuActions.empty()) { + helpMenu->addAction(showAction_.get()); + } else { + // insert action before last entry + helpMenu->insertAction(menuActions.last(), showAction_.get()); + } + } +} + +TFMenuHelper::~TFMenuHelper() { + if (utilqt::getApplicationMainWindow()) { + // remove menu action from help menu and delete help window since + // the MainWindow is parent and will not delete the the window until after + // module has been de-initialized. + // Destructors will remove the created widgets, actions and signals + + if (auto helpMenu = utilqt::getMenu("&Help")) { + helpMenu->removeAction(showAction_.get()); + } + } +} + +TFHelpWindow* TFMenuHelper::getWindow() const { + if (!helpWindow_) { + auto win = utilqt::getApplicationMainWindow(); + helpWindow_ = std::make_unique<TFHelpWindow>(win); + helpWindow_->setVisible(false); + helpWindow_->setFloating(true); + helpWindow_->loadState(); + + // release unique pointer of window when it is about to be destroyed by Qt + QObject::connect(helpWindow_.get(), &TFHelpWindow::destroyed, this, + [this]() { helpWindow_.release(); }); + } + + return helpWindow_.get(); +} + +QAction* TFMenuHelper::getAction() const { return showAction_.get(); } + +void TFMenuHelper::showWindow() const { + auto window = getWindow(); + window->activateWindow(); + window->raise(); + window->show(); +} + +} // namespace inviwo diff --git a/pool/shard007/C++/0093231_tstdtmod.cpp b/pool/shard007/C++/0093231_tstdtmod.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4e71c45760207d554112e7f18b9c13cfa49f1fa6 --- /dev/null +++ b/pool/shard007/C++/0093231_tstdtmod.cpp @@ -0,0 +1,228 @@ +/******************************************************************** + * COPYRIGHT: + * Copyright (c) 2002-2014, International Business Machines Corporation and + * others. All Rights Reserved. + ********************************************************************/ + +/* Created by weiv 05/09/2002 */ + +#include <stdarg.h> + +#include "unicode/tstdtmod.h" +#include "cmemory.h" +#include <stdio.h> + +TestLog::~TestLog() {} + +IcuTestErrorCode::~IcuTestErrorCode() { + // Safe because our handleFailure() does not throw exceptions. + if(isFailure()) { handleFailure(); } +} + +UBool IcuTestErrorCode::logIfFailureAndReset(const char *fmt, ...) { + if(isFailure()) { + char buffer[4000]; + va_list ap; + va_start(ap, fmt); + vsprintf(buffer, fmt, ap); + va_end(ap); + UnicodeString msg(testName, -1, US_INV); + msg.append(UNICODE_STRING_SIMPLE(" failure: ")).append(UnicodeString(errorName(), -1, US_INV)); + msg.append(UNICODE_STRING_SIMPLE(" - ")).append(UnicodeString(buffer, -1, US_INV)); + testClass.errln(msg); + reset(); + return TRUE; + } else { + reset(); + return FALSE; + } +} + +UBool IcuTestErrorCode::logDataIfFailureAndReset(const char *fmt, ...) { + if(isFailure()) { + char buffer[4000]; + va_list ap; + va_start(ap, fmt); + vsprintf(buffer, fmt, ap); + va_end(ap); + UnicodeString msg(testName, -1, US_INV); + msg.append(UNICODE_STRING_SIMPLE(" failure: ")).append(UnicodeString(errorName(), -1, US_INV)); + msg.append(UNICODE_STRING_SIMPLE(" - ")).append(UnicodeString(buffer, -1, US_INV)); + testClass.dataerrln(msg); + reset(); + return TRUE; + } else { + reset(); + return FALSE; + } +} + +void IcuTestErrorCode::handleFailure() const { + // testClass.errln("%s failure - %s", testName, errorName()); + UnicodeString msg(testName, -1, US_INV); + msg.append(UNICODE_STRING_SIMPLE(" failure: ")).append(UnicodeString(errorName(), -1, US_INV)); + + if (get() == U_MISSING_RESOURCE_ERROR || get() == U_FILE_ACCESS_ERROR) { + testClass.dataerrln(msg); + } else { + testClass.errln(msg); + } +} + +TestDataModule *TestDataModule::getTestDataModule(const char* name, TestLog& log, UErrorCode &status) +{ + if(U_FAILURE(status)) { + return NULL; + } + TestDataModule *result = NULL; + + // TODO: probe for resource bundle and then for XML. + // According to that, construct an appropriate driver object + + result = new RBTestDataModule(name, log, status); + if(U_SUCCESS(status)) { + return result; + } else { + delete result; + return NULL; + } +} + +TestDataModule::TestDataModule(const char* name, TestLog& log, UErrorCode& /*status*/) +: testName(name), +fInfo(NULL), +fLog(log) +{ +} + +TestDataModule::~TestDataModule() { + if(fInfo != NULL) { + delete fInfo; + } +} + +const char * TestDataModule::getName() const +{ + return testName; +} + + + +RBTestDataModule::~RBTestDataModule() +{ + ures_close(fTestData); + ures_close(fModuleBundle); + ures_close(fInfoRB); + uprv_free(tdpath); +} + +RBTestDataModule::RBTestDataModule(const char* name, TestLog& log, UErrorCode& status) +: TestDataModule(name, log, status), + fModuleBundle(NULL), + fTestData(NULL), + fInfoRB(NULL), + tdpath(NULL) +{ + fNumberOfTests = 0; + fDataTestValid = TRUE; + fModuleBundle = getTestBundle(name, status); + if(fDataTestValid) { + fTestData = ures_getByKey(fModuleBundle, "TestData", NULL, &status); + fNumberOfTests = ures_getSize(fTestData); + fInfoRB = ures_getByKey(fModuleBundle, "Info", NULL, &status); + if(status != U_ZERO_ERROR) { + log.errln(UNICODE_STRING_SIMPLE("Unable to initalize test data - missing mandatory description resources!")); + fDataTestValid = FALSE; + } else { + fInfo = new RBDataMap(fInfoRB, status); + } + } +} + +UBool RBTestDataModule::getInfo(const DataMap *& info, UErrorCode &/*status*/) const +{ + info = fInfo; + if(fInfo) { + return TRUE; + } else { + return FALSE; + } +} + +TestData* RBTestDataModule::createTestData(int32_t index, UErrorCode &status) const +{ + TestData *result = NULL; + UErrorCode intStatus = U_ZERO_ERROR; + + if(fDataTestValid == TRUE) { + // Both of these resources get adopted by a TestData object. + UResourceBundle *DataFillIn = ures_getByIndex(fTestData, index, NULL, &status); + UResourceBundle *headers = ures_getByKey(fInfoRB, "Headers", NULL, &intStatus); + + if(U_SUCCESS(status)) { + result = new RBTestData(DataFillIn, headers, status); + + if(U_SUCCESS(status)) { + return result; + } else { + delete result; + } + } else { + ures_close(DataFillIn); + ures_close(headers); + } + } else { + status = U_MISSING_RESOURCE_ERROR; + } + return NULL; +} + +TestData* RBTestDataModule::createTestData(const char* name, UErrorCode &status) const +{ + TestData *result = NULL; + UErrorCode intStatus = U_ZERO_ERROR; + + if(fDataTestValid == TRUE) { + // Both of these resources get adopted by a TestData object. + UResourceBundle *DataFillIn = ures_getByKey(fTestData, name, NULL, &status); + UResourceBundle *headers = ures_getByKey(fInfoRB, "Headers", NULL, &intStatus); + + if(U_SUCCESS(status)) { + result = new RBTestData(DataFillIn, headers, status); + if(U_SUCCESS(status)) { + return result; + } else { + delete result; + } + } else { + ures_close(DataFillIn); + ures_close(headers); + } + } else { + status = U_MISSING_RESOURCE_ERROR; + } + return NULL; +} + + + +//Get test data from ResourceBundles +UResourceBundle* +RBTestDataModule::getTestBundle(const char* bundleName, UErrorCode &status) +{ + if(U_SUCCESS(status)) { + UResourceBundle *testBundle = NULL; + const char* icu_data = fLog.getTestDataPath(status); + if (testBundle == NULL) { + testBundle = ures_openDirect(icu_data, bundleName, &status); + if (status != U_ZERO_ERROR) { + fLog.dataerrln(UNICODE_STRING_SIMPLE("Could not load test data from resourcebundle: ") + UnicodeString(bundleName, -1, US_INV)); + fDataTestValid = FALSE; + } + } + return testBundle; + } else { + return NULL; + } +} + diff --git a/pool/shard007/C++/0093232_pb-orm-transaction.cc b/pool/shard007/C++/0093232_pb-orm-transaction.cc new file mode 100644 index 0000000000000000000000000000000000000000..1487d79822fc45559f6ac38eba153282843eb6d3 --- /dev/null +++ b/pool/shard007/C++/0093232_pb-orm-transaction.cc @@ -0,0 +1,95 @@ +/* + * Created by René Post on 10/25/11. + * Copyright (c) 2011 xpt Software & Consulting B.V. 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. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + */ + +// +// pb-orm-transaction.cc +// protobuf-orm +// + +#include "pb-orm-transaction.h" +#include "pb-orm-database.h" +#include "pb-orm-log.h" + +OrmTransactionBase::OrmTransactionBase(OrmConn conn_) : conn(conn_) +{ +} + +OrmTransactionBase::~OrmTransactionBase() +{ + rollback(); +} + +bool OrmTransactionBase::started() +{ + return conn != NULL; +} + +bool OrmTransactionBase::commit() +{ + if (!conn) + return false; + + // try to commit + if (CONN->commit_transaction()) { + // commit succeeded + conn = NULL; + return true; + } + + // commit failed, are we still inside a transaction ? + if (CONN->in_transaction()) + return false; // leave conn assigned so commit can be retried. + + // Oh oh, no longer inside a transaction, so no point in calling commit again. + OrmLogError("error caused premature termination of transaction"); + conn = NULL; + return false; +} + +void OrmTransactionBase::rollback() +{ + if (conn) { + CONN->rollback_transaction(); + conn = NULL; + } +} + +OrmTransaction::OrmTransaction(OrmConn conn_) : OrmTransactionBase(conn_) +{ + if (conn) { + if (!CONN->begin_transaction()) + conn = NULL; + } + +} + +OrmTransactionRW::OrmTransactionRW(OrmConn conn_) : OrmTransactionBase(conn_) +{ + if (conn) { + if (!CONN->begin_transaction_rw()) + conn = NULL; + } +} diff --git a/pool/shard007/C++/0093234_download-query-loader.cpp b/pool/shard007/C++/0093234_download-query-loader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ae22320153aaf21ab4bd24a7472e4cd25ace605c --- /dev/null +++ b/pool/shard007/C++/0093234_download-query-loader.cpp @@ -0,0 +1,98 @@ +#include "downloader/download-query-loader.h" +#include <QFile> +#include <QJsonArray> +#include <QJsonDocument> +#include <QJsonObject> +#include "downloader/download-query-group.h" +#include "downloader/download-query-image.h" +#include "logger.h" + + +bool DownloadQueryLoader::load(const QString &path, QList<DownloadQueryImage> &uniques, QList<DownloadQueryGroup> &groups, Profile *profile) +{ + QFile f(path); + if (!f.open(QFile::ReadOnly)) { + return false; + } + + // Get the file's header to get the version + QString header = f.readLine().trimmed(); + + // Version 1 and 2 are plain text + if (header.startsWith("[IGL ")) { + log(QStringLiteral("Text-based IGL files are not supported"), Logger::Warning); + return false; + } + + // Other versions are JSON-based + f.reset(); + + const QByteArray data = f.readAll(); + QJsonDocument loadDoc = QJsonDocument::fromJson(data); + QJsonObject object = loadDoc.object(); + + const int version = object["version"].toInt(); + switch (version) + { + case 3: + { + QJsonArray groupsJson = object["batchs"].toArray(); + for (auto groupJson : groupsJson) { + DownloadQueryGroup batch; + if (batch.read(groupJson.toObject(), profile)) { + groups.append(batch); + } + } + + QJsonArray uniquesJson = object["uniques"].toArray(); + for (auto uniqueJson : uniquesJson) { + DownloadQueryImage unique; + if (unique.read(uniqueJson.toObject(), profile)) { + uniques.append(unique); + } + } + return true; + } + + default: + log(QStringLiteral("Unknown IGL file version: %1").arg(version), Logger::Warning); + return false; + } +} + +bool DownloadQueryLoader::save(const QString &path, const QList<DownloadQueryImage> &uniques, const QList<DownloadQueryGroup> &groups, bool saveProgress) +{ + QFile saveFile(path); + if (!saveFile.open(QFile::WriteOnly)) { + return false; + } + + // Batch downloads + QJsonArray groupsJson; + for (const auto &b : groups) { + QJsonObject batch; + b.write(batch, saveProgress); + groupsJson.append(batch); + } + + // Unique images + QJsonArray uniquesJson; + for (const auto &u : uniques) { + QJsonObject unique; + u.write(unique); + uniquesJson.append(unique); + } + + // Generate result + QJsonObject full; + full["version"] = 3; + full["batchs"] = groupsJson; + full["uniques"] = uniquesJson; + + // Write result + QJsonDocument saveDoc(full); + saveFile.write(saveDoc.toJson()); + saveFile.close(); + + return true; +} diff --git a/pool/shard007/C++/0093239_font_mgr.cpp b/pool/shard007/C++/0093239_font_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..85bcd4186db45109d712c223065a89ba682ab0a1 --- /dev/null +++ b/pool/shard007/C++/0093239_font_mgr.cpp @@ -0,0 +1,100 @@ +#include "font_mgr.h" +#include "pathos/text/font_texture_cache.h" +#include "pathos/util/resource_finder.h" +#include "pathos/util/log.h" + +#define REMOVE_GLYPH_LOADING 1 + +namespace pathos { + + FontManager& FontManager::get() + { + static FontManager instance; + return instance; + } + + FontManager::FontManager() {} + FontManager::~FontManager() { + if (initialized) { + term(); + } + } + + bool FontManager::init() { + if (initialized) { + return true; + } + + if (FT_Init_FreeType(&library)) { + LOG(LogError, "Cannot init FreeType library"); + return false; + } + FT_Int major, minor, patch; + FT_Library_Version(library, &major, &minor, &patch); + LOG(LogInfo, "[ThirdParty] FreeType : %d.%d.%d", major, minor, patch); + + initialized = true; + return initialized; + } + + bool FontManager::term() { + if (!initialized) { + LOG(LogError, "[ThirdParty] FontManager is even not initialized yet"); + return false; + } + // Release FreeType library + if (FT_Done_FreeType(library)) { + LOG(LogError, "[ThirdParty] Error while destroying FreeType library"); + return false; + } + return true; + } + + bool FontManager::registerFont(const std::string& tag, const char* filepath, uint32 pixelSize) { + if (fontDescDict.find(tag) != fontDescDict.end()) { + LOG(LogError, "Tag is already registered: %s (filepath=%s, pixelSize=%u)", tag.c_str(), filepath, pixelSize); + return false; + } + std::string fullFilepath = ResourceFinder::get().find(filepath); + if (fullFilepath.size() == 0) { + LOG(LogError, "Cannot find a font file: %s", filepath); + return false; + } + + FontDesc desc; + desc.fullFilepath = fullFilepath; + desc.pixelSize = pixelSize; + desc.cacheTexture = new FontTextureCache; + desc.cacheTexture->init(fullFilepath.c_str(), pixelSize); + fontDescDict[tag] = std::move(desc); + + return true; + } + + bool FontManager::getFontDesc(const std::string& tag, FontDesc& outDesc) { + auto it = fontDescDict.find(tag); + if (it == fontDescDict.end()) { + return false; + } + outDesc = it->second; + return true; + } + + void FontManager::registerCache(FontTextureCache* cache) + { + cacheList.push_back(cache); + } + + void FontManager::unregisterCache(FontTextureCache* cache) + { + cacheList.remove_if([cache](FontTextureCache* x) { return x == cache; }); + } + + void FontManager::onFrameEnd() + { + for (FontTextureCache* cache : cacheList) { + cache->onFrameEnd(); + } + } + +} diff --git a/pool/shard007/C++/0093243_profiler.cpp b/pool/shard007/C++/0093243_profiler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ceefd9e300fafe9268ce0196fba141e324ff31bb --- /dev/null +++ b/pool/shard007/C++/0093243_profiler.cpp @@ -0,0 +1,123 @@ +#include "profiler.hpp" +#include "integers.hpp" +#include "text.hpp" +#include <algorithm> +#include <functional> +#include <iomanip> +#include <sstream> + +struct ProfilerRecord { + std::string base; + std::string name; + std::string full; + double time; + + ProfilerRecord(const std::string &full_name, double time) : full(full_name), time(time) { + auto separator = full_name.find_last_of('.'); + if (separator != std::string::npos) { + base = full_name.substr(0, separator); + name = full_name.substr(separator + 1); + } else { + name = full_name; + } + } + + bool operator<(const ProfilerRecord &other) const { + return base < other.base || (base == other.base && time > other.time); + } +}; + +static double seconds_between(const TimePoint now, const TimePoint then) { + const std::chrono::duration<double> delta = now - then; + return delta.count(); +} + +TimePoint Profiler::get_time_point() const { + return std::chrono::steady_clock::now(); +} + +std::string Profiler::get_component_name() const { + std::string name; + bool first = true; + for (const auto &bit : hierarchy) { + if (!first) { + name += '.'; + } + name += bit; + first = false; + } + return name; +} + +void Profiler::start(const std::string &component) { + if (!active) { + return; + } + hierarchy.push_back(component); + const std::string &component_name = get_component_name(); + events[component_name]++; + started[component_name] = get_time_point(); +} + +void Profiler::stop() { + if (!active) { + return; + } + const std::string &component_name = get_component_name(); + double duration = seconds_between(get_time_point(), started[component_name]); + maxima[component_name] = std::max(maxima[component_name], duration); + minima[component_name] = std::min(minima[component_name], duration); + timings[component_name] += duration; + hierarchy.pop_back(); +} + +static std::string seconds_to_milliseconds_string(double value) { + return double_to_string(1000.0 * value, 2) + " ms"; +} + +std::string Profiler::dump() { + if (!active) { + return ""; + } + std::vector<ProfilerRecord> records; + std::unordered_map<std::string, double> base_total; + for (auto timing : timings) { + const ProfilerRecord &record = ProfilerRecord(timing.first, timing.second); + base_total[record.base] += record.time; + records.push_back(record); + } + std::sort(records.begin(), records.end()); + std::stringstream stream; + const std::vector<std::string> labels = {"Event", "Min", "Max", "Mean", "Count", "Ratio"}; + for (size_t i = 0; i < labels.size(); i++) { + if (i > 0) { + stream << ','; + } + stream << labels[i]; + } + stream << '\n'; + auto dump_record = [this, &base_total, &stream](const ProfilerRecord &record) { + stream << record.full << ','; + stream << seconds_to_milliseconds_string(minima[record.full]) << ','; + stream << seconds_to_milliseconds_string(maxima[record.full]) << ','; + stream << seconds_to_milliseconds_string(record.time / events[record.full]) << ','; + stream << std::to_string(events[record.full]) << ','; + stream << double_to_string(record.time / base_total[record.base], 2); + }; + // After dumping a record, dump all of its children. + std::function<void(size_t)> dump_tree = [&records, &stream, &dump_record, &dump_tree](size_t i) { + dump_record(records[i]); + stream << '\n'; + for (size_t j = 0; j < records.size(); j++) { + if (records[j].base == records[i].full) { + dump_tree(j); + } + } + }; + for (size_t i = 0; i < records.size(); i++) { + if (records[i].base.empty()) { + dump_tree(i); + } + } + return stream.str(); +} diff --git a/pool/shard007/C++/0093244_api.cpp b/pool/shard007/C++/0093244_api.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1568a505a0c6823a855e667a07f8460132fbb497 --- /dev/null +++ b/pool/shard007/C++/0093244_api.cpp @@ -0,0 +1,63 @@ +#include "../interfaceslib.h" +#include "api.h" + +namespace Engine { +namespace Filesystem { + + bool createDirectories(const Path &p) + { + if (exists(p)) + return true; + + Path parent = p.parentPath(); + if (!parent.empty()) + if (!createDirectories(parent)) + return false; + return createDirectory(p); + } + + bool copyFile(const Path &p, const Path &target) + { + Path exactTarget = target; + if (isDir(exactTarget)) + exactTarget /= p.filename(); + Stream out = openFileWrite(exactTarget, true); + assert(out); + Stream in = openFileRead(p); + assert(in); + out.pipe(in); + return true; + } + + FileQuery listFilesRecursive(const Path &path) + { + return { path, true }; + } + + FileQuery listFilesAndDirsRecursive(const Path &path) + { + return { path, true, true }; + } + + FileQuery listFiles(const Path &path) + { + return { path, false }; + } + + FileQuery listDirs(const Path &path) + { + return { path, false, true, false }; + } + + FileQuery listFilesAndDirs(const Path &path) + { + return { path, false, true }; + } + + bool isSeparator(char c) + { + return c == '/' || c == '\\'; + } + +} +} diff --git a/pool/shard007/C++/0093245_throttle_impl.cc b/pool/shard007/C++/0093245_throttle_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..201d7ce86f48dbbbd646581d05c99fddea621715 --- /dev/null +++ b/pool/shard007/C++/0093245_throttle_impl.cc @@ -0,0 +1,136 @@ +/* -*- c++ -*- */ +/* + * Copyright 2005-2011 Free Software Foundation, Inc. + * + * This file is part of GNU Radio + * + * SPDX-License-Identifier: GPL-3.0-or-later + * + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "throttle_impl.h" +#include <gnuradio/io_signature.h> +#include <cstring> +#include <limits> +#include <thread> + +pmt::pmt_t throttle_rx_rate_pmt(pmt::intern("rx_rate")); + +namespace gr { +namespace blocks { + +throttle::sptr throttle::make(size_t itemsize, double samples_per_sec, bool ignore_tags) +{ + return gnuradio::make_block_sptr<throttle_impl>( + itemsize, samples_per_sec, ignore_tags); +} + +throttle_impl::throttle_impl(size_t itemsize, double samples_per_second, bool ignore_tags) + : sync_block("throttle", + io_signature::make(1, 1, itemsize), + io_signature::make(0, 1, itemsize)), + d_itemsize(itemsize), + d_ignore_tags(ignore_tags) +{ + set_sample_rate(samples_per_second); +} + +throttle_impl::~throttle_impl() {} + +bool throttle_impl::start() +{ + d_start = std::chrono::steady_clock::now(); + d_total_samples = 0; + return block::start(); +} + +void throttle_impl::set_sample_rate(double rate) +{ + // changing the sample rate performs a reset of state params + d_start = std::chrono::steady_clock::now(); + d_total_samples = 0; + d_sample_rate = rate; + d_sample_period = std::chrono::duration<double>(1 / rate); +} + +double throttle_impl::sample_rate() const { return d_sample_rate; } + +int throttle_impl::work(int noutput_items, + gr_vector_const_void_star& input_items, + gr_vector_void_star& output_items) +{ + // check for updated rx_rate tag + if (!d_ignore_tags) { + uint64_t abs_N = nitems_read(0); + std::vector<tag_t> all_tags; + get_tags_in_range(all_tags, 0, abs_N, abs_N + noutput_items); + for (const auto& tag : all_tags) { + if (pmt::eq(tag.key, throttle_rx_rate_pmt)) { + double new_rate = pmt::to_double(tag.value); + set_sample_rate(new_rate); + } + } + } + + // copy all samples output[i] <= input[i] + const char* in = (const char*)input_items[0]; + + // iff we have a connected output, then copy + if (!output_items.empty()) { + char* out = reinterpret_cast<char*>(output_items[0]); + std::memcpy(out, in, noutput_items * d_itemsize); + } + d_total_samples += noutput_items; + + auto now = std::chrono::steady_clock::now(); + auto expected_time = d_start + d_sample_period * d_total_samples; + + if (expected_time > now) { + auto limit_duration = + std::chrono::duration<double>(std::numeric_limits<long>::max()); + if (expected_time - now > limit_duration) { + GR_LOG_ALERT(d_logger, + "WARNING: Throttle sleep time overflow! You " + "are probably using a very low sample rate."); + } + std::this_thread::sleep_until(expected_time); + } + + return noutput_items; +} + +void throttle_impl::setup_rpc() +{ +#ifdef GR_CTRLPORT + d_rpc_vars.emplace_back( + new rpcbasic_register_get<throttle, double>(alias(), + "sample_rate", + &throttle::sample_rate, + pmt::mp(0.0), + pmt::mp(100.0e6), + pmt::mp(0.0), + "Hz", + "Sample Rate", + RPC_PRIVLVL_MIN, + DISPTIME | DISPOPTSTRIP)); + + d_rpc_vars.emplace_back( + new rpcbasic_register_set<throttle, double>(alias(), + "sample_rate", + &throttle::set_sample_rate, + pmt::mp(0.0), + pmt::mp(100.0e6), + pmt::mp(0.0), + "Hz", + "Sample Rate", + RPC_PRIVLVL_MIN, + DISPTIME | DISPOPTSTRIP)); +#endif /* GR_CTRLPORT */ +} + +} /* namespace blocks */ +} /* namespace gr */ diff --git a/pool/shard007/C++/0093258_forwarding.cc b/pool/shard007/C++/0093258_forwarding.cc new file mode 100644 index 0000000000000000000000000000000000000000..6f24ee8e7464f458955424513d100645428b019a --- /dev/null +++ b/pool/shard007/C++/0093258_forwarding.cc @@ -0,0 +1,56 @@ +// Copyright (C) 2014-2016 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// <http://www.gnu.org/licenses/>. + +// { dg-options "-std=gnu++11" } + +#include <functional> +#include <testsuite_hooks.h> + +struct Counted +{ + Counted() : count(0) { } + Counted(const Counted& c) : count(c.count + 1) { } + int count; +}; + +int func(Counted c) { return c.count; } + +std::function<int(Counted)> f = func; + +void +test01() +{ + Counted c; + int n = f(c); + // 1 copy invoking function::operator() and 1 copy invoking func + VERIFY( n == 2 ); +} + +void +test02() +{ + int n = f(Counted{}); + // copy elided when invoking function::operator(), 1 copy invoking func + VERIFY( n == 1 ); +} + +int +main() +{ + test01(); + test02(); +} diff --git a/pool/shard007/C++/0093259_instrumented_mutex.cc b/pool/shard007/C++/0093259_instrumented_mutex.cc new file mode 100644 index 0000000000000000000000000000000000000000..443dc48136c3c986c7020575b276aee0a1e1b93c --- /dev/null +++ b/pool/shard007/C++/0093259_instrumented_mutex.cc @@ -0,0 +1,93 @@ +// Copyright (c) 2011-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. +// This source code is also licensed under the GPLv2 license found in the +// COPYING file in the root directory of this source tree. + +#include "monitoring/instrumented_mutex.h" +#include "monitoring/perf_context_imp.h" +#include "monitoring/thread_status_util.h" +#include "util/sync_point.h" + +namespace rocksdb { +namespace { +bool ShouldReportToStats(Env* env, Statistics* stats) { + return env != nullptr && stats != nullptr && + stats->stats_level_ > kExceptTimeForMutex; +} +} // namespace + +void InstrumentedMutex::Lock() { + PERF_CONDITIONAL_TIMER_FOR_MUTEX_GUARD(db_mutex_lock_nanos, + stats_code_ == DB_MUTEX_WAIT_MICROS); + uint64_t wait_time_micros = 0; + if (ShouldReportToStats(env_, stats_)) { + { + StopWatch sw(env_, nullptr, 0, &wait_time_micros); + LockInternal(); + } + RecordTick(stats_, stats_code_, wait_time_micros); + } else { + LockInternal(); + } +} + +void InstrumentedMutex::LockInternal() { +#ifndef NDEBUG + ThreadStatusUtil::TEST_StateDelay(ThreadStatus::STATE_MUTEX_WAIT); +#endif + mutex_.Lock(); +} + +void InstrumentedCondVar::Wait() { + PERF_CONDITIONAL_TIMER_FOR_MUTEX_GUARD(db_condition_wait_nanos, + stats_code_ == DB_MUTEX_WAIT_MICROS); + uint64_t wait_time_micros = 0; + if (ShouldReportToStats(env_, stats_)) { + { + StopWatch sw(env_, nullptr, 0, &wait_time_micros); + WaitInternal(); + } + RecordTick(stats_, stats_code_, wait_time_micros); + } else { + WaitInternal(); + } +} + +void InstrumentedCondVar::WaitInternal() { +#ifndef NDEBUG + ThreadStatusUtil::TEST_StateDelay(ThreadStatus::STATE_MUTEX_WAIT); +#endif + cond_.Wait(); +} + +bool InstrumentedCondVar::TimedWait(uint64_t abs_time_us) { + PERF_CONDITIONAL_TIMER_FOR_MUTEX_GUARD(db_condition_wait_nanos, + stats_code_ == DB_MUTEX_WAIT_MICROS); + uint64_t wait_time_micros = 0; + bool result = false; + if (ShouldReportToStats(env_, stats_)) { + { + StopWatch sw(env_, nullptr, 0, &wait_time_micros); + result = TimedWaitInternal(abs_time_us); + } + RecordTick(stats_, stats_code_, wait_time_micros); + } else { + result = TimedWaitInternal(abs_time_us); + } + return result; +} + +bool InstrumentedCondVar::TimedWaitInternal(uint64_t abs_time_us) { +#ifndef NDEBUG + ThreadStatusUtil::TEST_StateDelay(ThreadStatus::STATE_MUTEX_WAIT); +#endif + + TEST_SYNC_POINT_CALLBACK("InstrumentedCondVar::TimedWaitInternal", + &abs_time_us); + + return cond_.TimedWait(abs_time_us); +} + +} // namespace rocksdb diff --git a/pool/shard007/C++/0093264_Animatable.cpp b/pool/shard007/C++/0093264_Animatable.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0c916ea1a47ae1eac7a9702896bab3cd6300f20e --- /dev/null +++ b/pool/shard007/C++/0093264_Animatable.cpp @@ -0,0 +1,24 @@ +#include "Animatable.h" + +Animatable::Animatable() : animatableImage(NULL), frameRate(24) +{ +} + +Animatable::~Animatable() +{ + delete animatableImage; +} + +void Animatable::animateOn(SDL_Renderer *toAnimateOn) +{ + SDL_Rect* clipping = animatableImage->getClipRect(); + SDL_Rect* position = animatableImage->getPositionRect(); + + SDL_RenderCopy(toAnimateOn, animatableImage->getTexture(), clipping, position); +} + +void Animatable::loadImage(SDL_Renderer* renderer, string imageFile) +{ + animatableImage = new Image(); + animatableImage->loadImage(renderer, imageFile); +} \ No newline at end of file diff --git a/pool/shard007/C++/0093265_exampleFBKneePassive.cpp b/pool/shard007/C++/0093265_exampleFBKneePassive.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a872e51050a4f0acc17c865bdbbd8fe01ef24273 --- /dev/null +++ b/pool/shard007/C++/0093265_exampleFBKneePassive.cpp @@ -0,0 +1,195 @@ +#include <OpenSim/OpenSim.h> +#include <vector> +#include "WISCO_ElasticFoundationForce.h" +#include "WISCO_Ligament.h" +#include "WISCO_IdealMuscle.h" +using namespace OpenSim; +using SimTK::Vec3; + +int main() +{ + try { + static const std::string WISCO_HOME{ "C:/github/wisco_opensim" }; + + + // Timer + std::clock_t start; + double duration; + start = std::clock(); + + //Load WISCO_Plugin + //static const std::string plugin_file{ "../../../install/plugin/WISCO_Plugin" }; + static const std::string plugin_file{ "C:/github/wisco_opensim/install/plugin/WISCO_Plugin" }; + + LoadOpenSimLibrary(plugin_file, true); + + //Load Model + static const std::string model_file = WISCO_HOME + "/source/models/fbknee/fbknee.osim"; + static const std::string settings_file{ "./inputs/ContactAnalysis_settings.xml" }; + + Model model(model_file); + + //===================================================================== + // Configure the model + //===================================================================== + model.setUseVisualizer(true); + + SimTK::State& state = model.initSystem(); + + for (Coordinate& coord : model.updComponentList<Coordinate>()) { + coord.set_locked(true); + } + + Joint& knee = model.updJointSet().get("knee_r"); + Joint& pf = model.updJointSet().get("pf_r"); + + //Prescribe knee flexion + std::string pres_knee_mot_file{ "C:/github/wisco_opensim/source/examples/exampleFBKneePassiveFlexion/inputs/kfec_halfhz_0050.mot" }; + STOFileAdapter* pres_mot = new STOFileAdapter(); + TimeSeriesTable pres_table = pres_mot->read(pres_knee_mot_file); + + std::vector<double> time = pres_table.getIndependentColumn(); + int flex_col_i = pres_table.getColumnIndex("knee_flex_r"); + const SimTK::Matrix& knee_flex_view = pres_table.getMatrix().getAsMatrix(); + + std::vector<double> knee_flex(pres_table.getNumRows()); + + for (int i = 0; i < pres_table.getNumRows(); ++i) { + knee_flex[i] = knee_flex_view(i, flex_col_i)*SimTK::Pi / 180; + } + + SimmSpline knee_flex_func = SimmSpline(time.size(), &time[0], &knee_flex[0], "prescribed_knee_flex"); + + + knee.upd_coordinates(0).set_prescribed(true); + knee.upd_coordinates(0).set_prescribed_function(knee_flex_func); + + for (int i = 0; i < 6; ++i) { + knee.upd_coordinates(i).set_locked(false); + knee.upd_coordinates(i).set_clamped(false); + pf.upd_coordinates(i).set_locked(false); + pf.upd_coordinates(i).set_clamped(false); + + } + + + /* + CustomJoint& pelvis_jnt = model.updComponent<CustomJoint>("gnd_pelvis"); + pelvis_jnt.upd_coordinates(0).set_default_value( 90 * SimTK::Pi / 180); + + CustomJoint& hip = model.updComponent<CustomJoint>("hip_r"); + hip.upd_coordinates(0).set_default_value(20 * SimTK::Pi / 180); + + CustomJoint& ankle = model.updComponent<CustomJoint>("ankle_r"); + ankle.upd_coordinates(0).set_default_value(-30 * SimTK::Pi / 180); + */ + model.set_gravity(Vec3(0, 0, 0)); + + + for (WrapObject& wrap : model.updComponentList<WrapObject>()) { + wrap.upd_Appearance().set_visible(false); + + } + + //Add 2% muscle activation + PrescribedController* msl_control = new PrescribedController(); + msl_control->setActuators(model.updActuators()); + + for (WISCO_IdealMuscle& msl : model.updComponentList<WISCO_IdealMuscle>()) { + msl_control->prescribeControlForActuator(msl.getName(), new Constant(0.02)); + } + + model.addComponent(msl_control); + + for (WISCO_Ligament& lig : model.updComponentList<WISCO_Ligament>()){ + lig.set_normalized_damping_coefficient(0.003); + } + /*ConsoleReporter* con = new ConsoleReporter(); + con->setName("acl_report"); + con->addToReport(model.getComponent<WISCO_Ligament>("ACLpl1").getOutput("dynamic_quantities").getChannel("force_total")); + con->set_report_time_interval(0.00001); + model.addComponent(con);*/ + + state = model.initSystem(); + model.equilibrateMuscles(state); + + // Add display geometry. + model.updMatterSubsystem().setShowDefaultGeometry(false); + + SimTK::Visualizer& viz = model.updVisualizer().updSimbodyVisualizer(); + viz.setBackgroundColor(SimTK::White); + viz.setShowSimTime(true); + + //===================================================================== + // Simulate + //===================================================================== + if (true) { + double initialTime = 0.0; + double finalTime = 0.000001; + + + SimTK::RungeKuttaMersonIntegrator integrator(model.getSystem()); + integrator.setAccuracy(0.00001); + + //SimTK::CPodesIntegrator integrator(model.getSystem(), SimTK::CPodes::BDF, SimTK::CPodes::Newton); + //integrator.setAccuracy(0.00001); + + Manager manager(model, integrator); + + manager.initialize(state); + manager.integrate(finalTime); + + manager.getStateStorage().resampleLinear(0.01); + + + // Report Timer Results + duration = (std::clock() - start) / (double)CLOCKS_PER_SEC; + std::cout << "printf: " << duration << '\n'; + + + //===================================================================== + //Write Outputs + //===================================================================== + model.print("./results/fbknee.osim"); + + //Motion file + static const std::string out_mot_file{ "./results/fbknee_passive_flex.mot" }; + manager.getStateStorage().print(out_mot_file); + + } + + //Perform ContactAnalysis + AnalyzeTool analyzeTool = AnalyzeTool(settings_file); + //analyzeTool.run(); + // ********** END CODE ********** + } + catch (OpenSim::Exception ex) + { + std::cout << ex.getMessage() << std::endl; + std::cin.get(); + return 1; + } + catch (SimTK::Exception::Base ex) + { + std::cout << ex.getMessage() << std::endl; + std::cin.get(); + return 1; + } + catch (std::exception ex) + { + std::cout << ex.what() << std::endl; + std::cin.get(); + return 1; + } + catch (...) + { + std::cout << "UNRECOGNIZED EXCEPTION" << std::endl; + std::cin.get(); + return 1; + } + std::cout << "OpenSim example completed successfully" << std::endl; + std::cout << "Press return to continue" << std::endl; + std::cin.get(); + return 0; +} + diff --git a/pool/shard007/C++/0093268_PluginShapeFactory.cpp b/pool/shard007/C++/0093268_PluginShapeFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a585f79209af432ce7c508d3a0413d41dd80ce9 --- /dev/null +++ b/pool/shard007/C++/0093268_PluginShapeFactory.cpp @@ -0,0 +1,59 @@ +/* This file is part of the KDE project + * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). + * + * Contact: Vidhyapria Arunkumar <vidhyapria.arunkumar@nokia.com> + * Contact: Amit Aggarwal <amit.5.aggarwal@nokia.com> + * Contact: Manikandaprasad N C <manikandaprasad.chandrasekar@nokia.com> + + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "PluginShapeFactory.h" + +#include "PluginShape.h" + +#include <KoXmlNS.h> +#include <KoShapeLoadingContext.h> +#include "KoShapeBasedDocumentBase.h" + +#include <klocale.h> +#include <kdebug.h> + +PluginShapeFactory::PluginShapeFactory() + : KoShapeFactoryBase(PLUGINSHAPEID, i18n("Plugin Placeholder")) +{ + setToolTip(i18n("Plugin Placeholder, embedded or fullscreen")); + //setIcon("video-x-generic"); + setXmlElementNames(KoXmlNS::draw, QStringList("plugin")); + setLoadingPriority(1); + setHidden(true); +} + +KoShape *PluginShapeFactory::createDefaultShape(KoDocumentResourceManager *documentResources) const +{ + Q_UNUSED(documentResources); + PluginShape *defaultShape = new PluginShape(); + defaultShape->setShapeId(PLUGINSHAPEID); + return defaultShape; +} + +bool PluginShapeFactory::supports(const KoXmlElement &e, KoShapeLoadingContext &context) const +{ + Q_UNUSED(context); + return e.localName() == "plugin" && e.namespaceURI() == KoXmlNS::draw; +} + + diff --git a/pool/shard007/C++/0093273_validate_misc.cpp b/pool/shard007/C++/0093273_validate_misc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f0deedfad66732f69a0cc35329f142fc7f489089 --- /dev/null +++ b/pool/shard007/C++/0093273_validate_misc.cpp @@ -0,0 +1,163 @@ +// Copyright (c) 2018 Google LLC. +// Copyright (c) 2019 NVIDIA Corporation +// +// 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 "source/val/validate.h" + +#include "source/opcode.h" +#include "source/spirv_target_env.h" +#include "source/val/instruction.h" +#include "source/val/validate_scopes.h" +#include "source/val/validation_state.h" + +namespace spvtools { +namespace val { +namespace { + +spv_result_t ValidateUndef(ValidationState_t& _, const Instruction* inst) { + if (_.HasCapability(SpvCapabilityShader) && + _.ContainsLimitedUseIntOrFloatType(inst->type_id()) && + !_.IsPointerType(inst->type_id())) { + return _.diag(SPV_ERROR_INVALID_ID, inst) + << "Cannot create undefined values with 8- or 16-bit types"; + } + + if (spvIsWebGPUEnv(_.context()->target_env)) { + return _.diag(SPV_ERROR_INVALID_BINARY, inst) << "OpUndef is disallowed"; + } + + return SPV_SUCCESS; +} + +spv_result_t ValidateShaderClock(ValidationState_t& _, + const Instruction* inst) { + const uint32_t scope = inst->GetOperandAs<uint32_t>(2); + if (auto error = ValidateScope(_, inst, scope)) { + return error; + } + + bool is_int32 = false, is_const_int32 = false; + uint32_t value = 0; + std::tie(is_int32, is_const_int32, value) = _.EvalInt32IfConst(scope); + if (is_const_int32 && value != SpvScopeSubgroup && value != SpvScopeDevice) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << "Scope must be Subgroup or Device"; + } + + // Result Type must be a 64 - bit unsigned integer type or + // a vector of two - components of 32 - + // bit unsigned integer type + const uint32_t result_type = inst->type_id(); + if (!(_.IsUnsignedIntScalarType(result_type) && + _.GetBitWidth(result_type) == 64) && + !(_.IsUnsignedIntVectorType(result_type) && + _.GetDimension(result_type) == 2 && _.GetBitWidth(result_type) == 32)) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) << "Expected Value to be a " + "vector of two components" + " of unsigned integer" + " or 64bit unsigned integer"; + } + + return SPV_SUCCESS; +} + +} // namespace + +spv_result_t MiscPass(ValidationState_t& _, const Instruction* inst) { + switch (inst->opcode()) { + case SpvOpUndef: + if (auto error = ValidateUndef(_, inst)) return error; + break; + default: + break; + } + switch (inst->opcode()) { + case SpvOpBeginInvocationInterlockEXT: + case SpvOpEndInvocationInterlockEXT: + _.function(inst->function()->id()) + ->RegisterExecutionModelLimitation( + SpvExecutionModelFragment, + "OpBeginInvocationInterlockEXT/OpEndInvocationInterlockEXT " + "require Fragment execution model"); + + _.function(inst->function()->id()) + ->RegisterLimitation([](const ValidationState_t& state, + const Function* entry_point, + std::string* message) { + const auto* execution_modes = + state.GetExecutionModes(entry_point->id()); + + auto find_interlock = [](const SpvExecutionMode& mode) { + switch (mode) { + case SpvExecutionModePixelInterlockOrderedEXT: + case SpvExecutionModePixelInterlockUnorderedEXT: + case SpvExecutionModeSampleInterlockOrderedEXT: + case SpvExecutionModeSampleInterlockUnorderedEXT: + case SpvExecutionModeShadingRateInterlockOrderedEXT: + case SpvExecutionModeShadingRateInterlockUnorderedEXT: + return true; + default: + return false; + } + }; + + bool found = false; + if (execution_modes) { + auto i = std::find_if(execution_modes->begin(), + execution_modes->end(), find_interlock); + found = (i != execution_modes->end()); + } + + if (!found) { + *message = + "OpBeginInvocationInterlockEXT/OpEndInvocationInterlockEXT " + "require a fragment shader interlock execution mode."; + return false; + } + return true; + }); + break; + case SpvOpDemoteToHelperInvocationEXT: + _.function(inst->function()->id()) + ->RegisterExecutionModelLimitation( + SpvExecutionModelFragment, + "OpDemoteToHelperInvocationEXT requires Fragment execution " + "model"); + break; + case SpvOpIsHelperInvocationEXT: { + const uint32_t result_type = inst->type_id(); + _.function(inst->function()->id()) + ->RegisterExecutionModelLimitation( + SpvExecutionModelFragment, + "OpIsHelperInvocationEXT requires Fragment execution model"); + if (!_.IsBoolScalarType(result_type)) + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << "Expected bool scalar type as Result Type: " + << spvOpcodeString(inst->opcode()); + break; + } + case SpvOpReadClockKHR: + if (auto error = ValidateShaderClock(_, inst)) { + return error; + } + break; + default: + break; + } + + return SPV_SUCCESS; +} + +} // namespace val +} // namespace spvtools diff --git a/pool/shard007/C++/0093275_toolbar.cpp b/pool/shard007/C++/0093275_toolbar.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d22aec7f3d409505900f6be0138ef281261887cf --- /dev/null +++ b/pool/shard007/C++/0093275_toolbar.cpp @@ -0,0 +1,56 @@ +/* Gobby - GTK-based collaborative text editor + * Copyright (C) 2008-2015 Armin Burgmeier <armin@arbur.net> + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include "core/toolbar.hpp" + +#include <gtkmm/toolbar.h> +#include <gtkmm/builder.h> + +Gobby::Toolbar::Toolbar(const Preferences& preferences): + m_preferences(preferences) +{ + set_orientation(Gtk::ORIENTATION_VERTICAL); + + Glib::RefPtr<Gtk::Builder> builder = + Gtk::Builder::create_from_resource( + "/de/0x539/gobby/ui/toolbar.ui"); + + builder->get_widget("toolbar", m_toolbar); + + // Initial settings + on_toolbar_style_changed(); + on_show_toolbar_changed(); + + preferences.appearance.toolbar_style.signal_changed().connect( + sigc::mem_fun(*this, &Toolbar::on_toolbar_style_changed)); + preferences.appearance.show_toolbar.signal_changed().connect( + sigc::mem_fun(*this, &Toolbar::on_show_toolbar_changed)); + + attach(*m_toolbar, 0, 0, 1, 1); +} + +void Gobby::Toolbar::on_toolbar_style_changed() +{ + m_toolbar->set_toolbar_style(m_preferences.appearance.toolbar_style); +} + +void Gobby::Toolbar::on_show_toolbar_changed() +{ + if(m_preferences.appearance.show_toolbar) + m_toolbar->show(); + else + m_toolbar->hide(); +} diff --git a/pool/shard007/C++/0093282_aeron_driver_conductor_clock_test.cpp b/pool/shard007/C++/0093282_aeron_driver_conductor_clock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bf5505f73dea5d4d2c2a4fc9a642254c058f8914 --- /dev/null +++ b/pool/shard007/C++/0093282_aeron_driver_conductor_clock_test.cpp @@ -0,0 +1,45 @@ +/* + * Copyright 2014-2020 Real Logic Limited. + * + * 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 + * + * https://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 "aeron_driver_conductor_test.h" + +class DriverConductorClockTest : public DriverConductorTest, public testing::Test +{ +}; + +TEST_F(DriverConductorClockTest, shouldUpdateCachedClockOnMsBoundary) +{ + doWork(); + int64_t initial_nano_time = aeron_clock_cached_nano_time(m_conductor.m_conductor.context->cached_clock); + int64_t initial_epoch_time = aeron_clock_cached_epoch_time(m_conductor.m_conductor.context->cached_clock); + ASSERT_NE(0, m_conductor.m_conductor.clock_update_deadline_ns); + int64_t half_increment_for_clock_update = + (m_conductor.m_conductor.clock_update_deadline_ns - initial_nano_time) / 2; + + test_increment_nano_time(half_increment_for_clock_update); + doWork(); + ASSERT_EQ(initial_nano_time, aeron_clock_cached_nano_time(m_conductor.m_conductor.context->cached_clock)); + ASSERT_EQ(initial_epoch_time, aeron_clock_cached_epoch_time(m_conductor.m_conductor.context->cached_clock)); + + test_increment_nano_time(half_increment_for_clock_update); + doWork(); + ASSERT_LE( + initial_nano_time + AERON_DRIVER_CONDUCTOR_CLOCK_UPDATE_DURATION_NS, + aeron_clock_cached_nano_time(m_conductor.m_conductor.context->cached_clock)); + ASSERT_LT( + initial_epoch_time, + aeron_clock_cached_epoch_time(m_conductor.m_conductor.context->cached_clock)); +} diff --git a/pool/shard007/C++/0093286_cert_store.cc b/pool/shard007/C++/0093286_cert_store.cc new file mode 100644 index 0000000000000000000000000000000000000000..be75b38b5909b13baf4aec12e77c2de9f9a11c8b --- /dev/null +++ b/pool/shard007/C++/0093286_cert_store.cc @@ -0,0 +1,146 @@ +// Copyright (c) 2011 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 "content/browser/cert_store.h" + +#include <algorithm> +#include <functional> + +#include "base/stl_util-inl.h" +#include "content/browser/renderer_host/render_process_host.h" +#include "content/browser/renderer_host/render_view_host.h" +#include "content/common/notification_service.h" + +template <typename T> +struct MatchSecond { + explicit MatchSecond(const T& t) : value(t) {} + + template<typename Pair> + bool operator()(const Pair& p) const { + return (value == p.second); + } + T value; +}; + +// static +CertStore* CertStore::GetInstance() { + return Singleton<CertStore>::get(); +} + +CertStore::CertStore() : next_cert_id_(1) { + // We watch for RenderProcess termination, as this is how we clear + // certificates for now. + // TODO(jcampan): we should be listening to events such as resource cached/ + // removed from cache, and remove the cert when we know it + // is not used anymore. + + registrar_.Add(this, NotificationType::RENDERER_PROCESS_TERMINATED, + NotificationService::AllSources()); + registrar_.Add(this, NotificationType::RENDERER_PROCESS_CLOSED, + NotificationService::AllSources()); +} + +CertStore::~CertStore() { +} + +int CertStore::StoreCert(net::X509Certificate* cert, int process_id) { + DCHECK(cert); + base::AutoLock autoLock(cert_lock_); + + int cert_id; + + // Do we already know this cert? + ReverseCertMap::iterator cert_iter = cert_to_id_.find(cert); + if (cert_iter == cert_to_id_.end()) { + cert_id = next_cert_id_++; + // We use 0 as an invalid cert_id value. In the unlikely event that + // next_cert_id_ wraps around, we reset it to 1. + if (next_cert_id_ == 0) + next_cert_id_ = 1; + cert->AddRef(); + id_to_cert_[cert_id] = cert; + cert_to_id_[cert] = cert_id; + } else { + cert_id = cert_iter->second; + } + + // Let's update process_id_to_cert_id_. + if (std::find_if(process_id_to_cert_id_.lower_bound(process_id), + process_id_to_cert_id_.upper_bound(process_id), + MatchSecond<int>(cert_id)) == + process_id_to_cert_id_.upper_bound(process_id)) { + process_id_to_cert_id_.insert(std::make_pair(process_id, cert_id)); + } + + // And cert_id_to_process_id_. + if (std::find_if(cert_id_to_process_id_.lower_bound(cert_id), + cert_id_to_process_id_.upper_bound(cert_id), + MatchSecond<int>(process_id)) == + cert_id_to_process_id_.upper_bound(cert_id)) { + cert_id_to_process_id_.insert(std::make_pair(cert_id, process_id)); + } + + return cert_id; +} + +bool CertStore::RetrieveCert(int cert_id, + scoped_refptr<net::X509Certificate>* cert) { + base::AutoLock autoLock(cert_lock_); + + CertMap::iterator iter = id_to_cert_.find(cert_id); + if (iter == id_to_cert_.end()) + return false; + if (cert) + *cert = iter->second; + return true; +} + +void CertStore::RemoveCertInternal(int cert_id) { + CertMap::iterator cert_iter = id_to_cert_.find(cert_id); + DCHECK(cert_iter != id_to_cert_.end()); + + ReverseCertMap::iterator id_iter = cert_to_id_.find(cert_iter->second); + DCHECK(id_iter != cert_to_id_.end()); + cert_to_id_.erase(id_iter); + + cert_iter->second->Release(); + id_to_cert_.erase(cert_iter); +} + +void CertStore::RemoveCertsForRenderProcesHost(int process_id) { + base::AutoLock autoLock(cert_lock_); + + // We iterate through all the cert ids for that process. + IDMap::iterator ids_iter; + for (ids_iter = process_id_to_cert_id_.lower_bound(process_id); + ids_iter != process_id_to_cert_id_.upper_bound(process_id);) { + int cert_id = ids_iter->second; + // Remove this process from cert_id_to_process_id_. + IDMap::iterator proc_iter = + std::find_if(cert_id_to_process_id_.lower_bound(cert_id), + cert_id_to_process_id_.upper_bound(cert_id), + MatchSecond<int>(process_id)); + DCHECK(proc_iter != cert_id_to_process_id_.upper_bound(cert_id)); + cert_id_to_process_id_.erase(proc_iter); + + if (cert_id_to_process_id_.count(cert_id) == 0) { + // This cert is not referenced by any process, remove it from id_to_cert_ + // and cert_to_id_. + RemoveCertInternal(cert_id); + } + + // Erase the current item but keep the iterator valid. + process_id_to_cert_id_.erase(ids_iter++); + } +} + +void CertStore::Observe(NotificationType type, + const NotificationSource& source, + const NotificationDetails& details) { + DCHECK(type == NotificationType::RENDERER_PROCESS_TERMINATED || + type == NotificationType::RENDERER_PROCESS_CLOSED); + RenderProcessHost* rph = Source<RenderProcessHost>(source).ptr(); + DCHECK(rph); + RemoveCertsForRenderProcesHost(rph->id()); +} diff --git a/pool/shard007/C++/0093290_task039.cpp b/pool/shard007/C++/0093290_task039.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ae83d8d83faf837599e485da14297c5c3b7a4fbc --- /dev/null +++ b/pool/shard007/C++/0093290_task039.cpp @@ -0,0 +1,37 @@ +#include <map> + +#include "base/pythagorean_triple.h" +#include "base/task.h" + +void DFS(const PrimitivePythagoreanTriple<uint> &triple, + int max_p, std::map<int, int> *result) { + int perimeter = triple.a() + triple.b() + triple.c(); + if (perimeter > max_p) { + return; + } + + for (int i = 1; i*perimeter <= max_p; ++i) { + (*result)[i*perimeter]++; + } + + DFS(triple.PriceTree().LeftChild(), max_p, result); + DFS(triple.PriceTree().MiddleChild(), max_p, result); + DFS(triple.PriceTree().RightChild(), max_p, result); +} + +TASK(39) { + int max_c = 1000; + std::map<int, int> result; + + DFS(PrimitivePythagoreanTriple<uint>(3, 4, 5), max_c, &result); + + int max = 0, ans = -1; + for (auto pair : result) { + if (max < pair.second) { + max = pair.second; + ans = pair.first; + } + } + + return ans; +} diff --git a/pool/shard007/C++/0093311_0146-LRU_Cache.cpp b/pool/shard007/C++/0093311_0146-LRU_Cache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..09305208e227eb77ce9e97b76e8568a9b67fabba --- /dev/null +++ b/pool/shard007/C++/0093311_0146-LRU_Cache.cpp @@ -0,0 +1,43 @@ +class LRUCache { +public: + LRUCache(int capacity) { + this->capacity = capacity; + } + + int get(int key) { + if (cacheMap.find(key) == cacheMap.end()) { + return -1; + } + + cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]); + cacheMap[key] = cacheList.begin(); + return cacheList.front().second; + } + + void put(int key, int value) { + if (get(key) == -1) { + if (cacheList.size() == capacity) { + cacheMap.erase(cacheList.back().first); + cacheList.pop_back(); + } + cacheList.push_front({key, value}); + cacheMap[key] = cacheList.begin(); + } + else { + cacheList.begin()->second = value; + } + } + +private: + int capacity; + list<pair<int, int>> cacheList; + unordered_map<int, list<pair<int, int>>::iterator> cacheMap; +}; + +/** + * Your LRUCache object will be instantiated and called as such: + * LRUCache obj = new LRUCache(capacity); + * int param_1 = obj.get(key); + * obj.put(key,value); + */ + \ No newline at end of file diff --git a/pool/shard007/C++/0093334_gtstadministrators.cpp b/pool/shard007/C++/0093334_gtstadministrators.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cce477f1ada4f0e6d0eabb599fbb6f6fa2f6a4b7 --- /dev/null +++ b/pool/shard007/C++/0093334_gtstadministrators.cpp @@ -0,0 +1,68 @@ +//--------------------------------------------------------------------------- +/* +GTST, Game Theory Server +Copyright (C) 2011-2015 Richel Bilderbeek + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. +You should have received a copy of the GNU General Public License +along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ +//--------------------------------------------------------------------------- +//From http://www.richelbilderbeek.nl/ProjectGtst.htm +//--------------------------------------------------------------------------- +#include "gtstadministrator.h" +#include "gtstadministrators.h" +#include "counter.h" + +ribi::gtst::Administrators::Administrators() + : m_administrators{}, + m_last_id_administrator(new Counter(1)) +{ +} + +boost::weak_ptr<ribi::gtst::Administrator> ribi::gtst::Administrators::CreateNewAdministrator() +{ + #ifndef NDEBUG + const int n_administrators_old = m_administrators.size(); + std::for_each(m_administrators.begin(),m_administrators.end(), + [](const boost::shared_ptr<Administrator>& p) + { + assert(p && "Assume all Administrators are valid"); + } ); + #endif + + const int new_id = m_last_id_administrator->Get(); + assert(new_id > 0); + + #ifndef NDEBUG + std::for_each(m_administrators.begin(),m_administrators.end(), + [new_id](const boost::shared_ptr<Administrator>& p) + { + assert(p->GetId() != new_id && "Assume new ID is really a unique ID"); + } ); + #endif + + boost::shared_ptr<Administrator> new_administrator( + new Administrator(new_id)); + assert(new_administrator); + + //Keep one copy of the administrator + m_administrators.insert(new_administrator); + + #ifndef NDEBUG + const int n_administrators_new = m_administrators.size(); + assert(n_administrators_new == n_administrators_old + 1 + && "Assume the new administrator has really been added to m_administrators"); + #endif + + return new_administrator; +} + diff --git a/pool/shard007/C++/0093342_QSCU.cpp b/pool/shard007/C++/0093342_QSCU.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56ce90fb9b4f16350952ba8526b538f7ea9d7358 --- /dev/null +++ b/pool/shard007/C++/0093342_QSCU.cpp @@ -0,0 +1,270 @@ +/****************************************************************************** + * Endpoint.cpp + * Implementation of the QuboBus Endpoint. + * + * Copyright (C) 2016 Robotics at Maryland + * Copyright (C) 2016 Greg Harris <gharris1727@gmail.com> + * All rights reserved. + ******************************************************************************/ + +// UNIX Serial includes +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/ioctl.h> +#include <fcntl.h> +#include <stdarg.h> + +// Header include +#include "QSCU.h" + +#if QUBOBUS_PROTOCOL_VERSION != 3 +#error Update me with new message defs! +#endif + +#include <stdio.h> + +QSCU::QSCU(std::string deviceFile, speed_t baud) + : _deviceFile(deviceFile), + _termBaud(baud), + _deviceFD(-1), + _timeout({1,500}) +{ + +} + +QSCU::~QSCU() { closeDevice(); } + +void QSCU::openDevice() { + struct termios termcfg; + int modemcfg = 0, fd = -1; + /* Open the serial port and store into a file descriptor. + * O_RDWR allows for bi-directional I/O, and + * O_NONBLOCK makes it so that read/write does not block. + */ + fd = open(_deviceFile.c_str(), O_RDWR, O_NONBLOCK); + // Check to see if the device exists. + if (fd == -1) { + throw QSCUException("Device '"+_deviceFile+"' unavaliable."); + } + // Read the config of the interface. + if (tcgetattr(fd, &termcfg)) { + throw QSCUException("Unable to read terminal configuration."); + } + + // Set the baudrate for the terminal + if (cfsetospeed(&termcfg, _termBaud)) { + throw QSCUException("Unable to set terminal output speed."); + } + if (cfsetispeed(&termcfg, _termBaud)) { + throw QSCUException("Unable to set terminal intput speed."); + } + + // Set raw I/O rules to read and write the data purely. + cfmakeraw(&termcfg); + + termcfg.c_cflag &= ~CSTOPB; + + // Configure the read timeout (deciseconds) + termcfg.c_cc[VTIME] = 0; + // Configure the minimum number of chars for read. + termcfg.c_cc[VMIN] = 1; + + // Push the configuration to the terminal NOW. + if (tcsetattr(fd, TCSANOW, &termcfg)) { + throw QSCUException("Unable to set terminal configuration."); + } + + // Pull in the modem configuration + if (ioctl(fd, TIOCMGET, &modemcfg)) { + throw QSCUException("Unable to read modem configuration."); + } + // Enable Request to Send + modemcfg |= TIOCM_RTS; + // Push the modem config back to the modem. + if (ioctl(fd, TIOCMSET, &modemcfg)) { + throw QSCUException("Unable to set modem configuration."); + } + + // Successful hardware connection! + // Needs to be set for the qscu protocol library to make the connection. + _deviceFD = fd; + + _state = initialize(this, QSCU::serialRead, QSCU::serialWrite, 10); + + connect(); +} + +bool QSCU::isOpen() {return _deviceFD >= 0;} + +void QSCU::assertOpen() { if (!isOpen()) throw QSCUException("Device needs to be open!"); } + +void QSCU::closeDevice() { + if (isOpen()) + close(_deviceFD); + _deviceFD = -1; +} + +/****************************************************************************** + * Internal Functionality + * All of the following functions are meant for internal-use only + ******************************************************************************/ + +void QSCU::connect() { + + uint8_t buffer[QUBOBUS_MAX_PAYLOAD_LENGTH]; + assertOpen(); + // Prepare to begin communication with the device. + if (init_connect(&_state, buffer)) { + closeDevice(); + throw QSCUException("Unable to sychronize the remote connection!"); + } +} + +ssize_t QSCU::serialRead(void *io_host, void *buffer, size_t size) { + QSCU *qscu = (QSCU*) io_host; + ssize_t ret = qscu->readRaw(buffer, size); + return ret; +} + +ssize_t QSCU::serialWrite(void *io_host, void *buffer, size_t size) { + QSCU *qscu = (QSCU*) io_host; + ssize_t ret = qscu->writeRaw(buffer, size); + return ret; +} + +ssize_t QSCU::readRaw(void* blob, size_t bytes_to_read) { + // Keep track of the number of bytes read, and the number of fds that are ready. + int bytes_read = 0, current_read = 0, fds_ready = 0; + // Sets of file descriptors for use with select(2). + fd_set read_fds, write_fds, except_fds; + // Timeout in the form of {sec, usec}, for use with select(2). + struct timeval timeout = _timeout; + // Ensure the device is avaliable and open. + assertOpen(); + // Check if we need to read data at all. + if (bytes_to_read > 0) { + do { + // Set up for the select call to handle timeouts. + FD_ZERO(&read_fds); + FD_ZERO(&write_fds); + FD_ZERO(&except_fds); + FD_SET(_deviceFD, &read_fds); + // Wait until the device is ready to read, return the number of FDs avalaible. + fds_ready = select(FD_SETSIZE, &read_fds, NULL, NULL, &timeout); + if (fds_ready == 1) { + // The filedescriptor is ready to read. + current_read = read(_deviceFD, (((char*)blob) + bytes_read), + (bytes_to_read - bytes_read)); + // If the read was successful, record the number of bytes read. + if (current_read >= 0) { + bytes_read += current_read; + } + } + // Keep reading until we've run out of data, or we couldnt read more data. + } while ((bytes_read < bytes_to_read) && (fds_ready == 1) && (current_read >= 0)); + } + // Return the number of bytes we actually managed to read. + return bytes_read; +} + +ssize_t QSCU::writeRaw(void* blob, size_t bytes_to_write) { + // Keep track of the number of bytes written, and the number of fds that are ready. + int bytes_written = 0, current_write = 0, fds_ready = 0; + // Sets of file descriptors for use with select(2). + fd_set read_fds, write_fds, except_fds; + // Timeout in the form of {sec, usec}, for use with select(2). + struct timeval timeout = _timeout; + // Ensure the device is avaliable and open. + assertOpen(); + // Check if we need to write data at all. + if (bytes_to_write > 0) { + do { + // Set up for the select call to handle timeouts. + FD_ZERO(&read_fds); + FD_ZERO(&write_fds); + FD_ZERO(&except_fds); + FD_SET(_deviceFD, &write_fds); + // Wait until the device is ready to write, return the number of FDs avalaible. + fds_ready = select(_deviceFD+1, &read_fds, &write_fds, &except_fds, &timeout); + if (fds_ready == 1) { + // The filedescriptor is ready to write. + current_write = write(_deviceFD, (((char*)blob) + bytes_written), + (bytes_to_write - bytes_written)); + // If the write was successful, record the number of bytes written. + if (current_write >= 0) { + bytes_written += current_write; + } + } + // Keep writing until we've run out of data, or we couldnt write more data. + } while ((bytes_written < bytes_to_write) && (fds_ready == 1) && (current_write >= 0)); + } + // Return the number of bytes we actually managed to write. + return bytes_written; +} + +void QSCU::sendMessage(Transaction *transaction, void *payload, void *response) { + char buffer[QUBOBUS_MAX_PAYLOAD_LENGTH]; + bool completed = false; + int retries = 0; + + Message recieved_message, sent = create_request(transaction, payload); + + while (!completed) { + bool recieved = false; + + write_message(&_state, &sent); + + while (!recieved) { + if (read_message(&_state, &recieved_message, buffer)){ + throw QSCUException("No message received"); + } + + if (checksum_message(&recieved_message) != recieved_message.footer.checksum) { + + if ( retries > _max_retries ){ + throw QSCUException("Maximum number of retries reached!"); + } + retries++; + Message response = create_error(&eChecksum, NULL); + write_message(&_state, &response); + + } else { + recieved = true; + } + } + + if (recieved_message.header.message_type == MT_RESPONSE) { + if (recieved_message.header.message_id != transaction->id || recieved_message.payload_size != transaction->response) + throw QSCUException("Malformed response payload!"); + /* Copy the read message back into the response buffer. */ + memcpy(response, buffer, transaction->response); + completed = true; + } else if (recieved_message.header.message_type == MT_ERROR) { + if (recieved_message.header.message_id == eChecksum.id) { + //The other side got a checksum error, retry sending. + } else { + // throw QSCUException(str(recieved_message.payload, recieved_message.payload_size)); + } + } else { + //throw QSCUException("Unexpected response: " + recieved_message.header.message_type + ":" + recieved.header.message_id); + } + } + +} + +int QSCU::keepAlive(){ + Message alive; + unsigned char buffer[QUBOBUS_MAX_PAYLOAD_LENGTH]; + alive = create_keep_alive(); + if ( write_message( &_state, &alive ) ){ + throw QSCUException("Unable to write message -> keepAlive"); + } + if ( read_message( &_state, &alive, buffer ) ) { + throw QSCUException("No message received -> keepAlive"); + } + if ( alive.header.message_type != MT_KEEPALIVE ) { + throw QSCUException("Incorrect response received -> keepAlive"); + } + // alive succeeded, return 0 + return 0; + } diff --git a/pool/shard007/C++/0093347_InitialInfoTreeIO.cc b/pool/shard007/C++/0093347_InitialInfoTreeIO.cc new file mode 100644 index 0000000000000000000000000000000000000000..d79ebd0e45505015237e1d3e8c18d5821f45f333 --- /dev/null +++ b/pool/shard007/C++/0093347_InitialInfoTreeIO.cc @@ -0,0 +1,139 @@ +/************************************************************************* + * * + * Copyright (c) 2011 Hirokazu Odaka * + * * + * This program is free software: you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation, either version 3 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program. If not, see <http://www.gnu.org/licenses/>. * + * * + *************************************************************************/ + +#include "InitialInfoTreeIO.hh" + +#include "TTree.h" +#include "AstroUnits.hh" + +namespace unit = anlgeant4::unit; + +namespace comptonsoft +{ + +InitialInfoTreeIO::InitialInfoTreeIO() + : tree_(nullptr), enabled_(true) +{ +} + +InitialInfoTreeIO::~InitialInfoTreeIO() = default; + +void InitialInfoTreeIO::defineBranches() +{ + if (enabled_) { + tree_->Branch("ini_energy", &ini_energy_, "ini_energy/F"); + tree_->Branch("ini_dirx", &ini_dirx_, "ini_dirx/F"); + tree_->Branch("ini_diry", &ini_diry_, "ini_diry/F"); + tree_->Branch("ini_dirz", &ini_dirz_, "ini_dirz/F"); + tree_->Branch("ini_time", &ini_time_, "ini_time/D"); + tree_->Branch("ini_posx", &ini_posx_, "ini_posx/F"); + tree_->Branch("ini_posy", &ini_posy_, "ini_posy/F"); + tree_->Branch("ini_posz", &ini_posz_, "ini_posz/F"); + tree_->Branch("ini_polarx", &ini_polarx_, "ini_polarx/F"); + tree_->Branch("ini_polary", &ini_polary_, "ini_polary/F"); + tree_->Branch("ini_polarz", &ini_polarz_, "ini_polarz/F"); + tree_->Branch("weight", &weight_, "weight/F"); + } +} + +void InitialInfoTreeIO::setBranchAddresses() +{ + if (enabled_) { + tree_->SetBranchAddress("ini_energy", &ini_energy_); + tree_->SetBranchAddress("ini_dirx", &ini_dirx_); + tree_->SetBranchAddress("ini_diry", &ini_diry_); + tree_->SetBranchAddress("ini_dirz", &ini_dirz_); + tree_->SetBranchAddress("ini_time", &ini_time_); + tree_->SetBranchAddress("ini_posx", &ini_posx_); + tree_->SetBranchAddress("ini_posy", &ini_posy_); + tree_->SetBranchAddress("ini_posz", &ini_posz_); + tree_->SetBranchAddress("ini_polarx", &ini_polarx_); + tree_->SetBranchAddress("ini_polary", &ini_polary_); + tree_->SetBranchAddress("ini_polarz", &ini_polarz_); + tree_->SetBranchAddress("weight", &weight_); + } +} + +double InitialInfoTreeIO::getInitialEnergy() const +{ + return ini_energy_ * unit::keV; +} + +vector3_t InitialInfoTreeIO::getInitialDirection() const +{ + return vector3_t(ini_dirx_, ini_diry_, ini_dirz_); +} + +double InitialInfoTreeIO::getInitialTime() const +{ + return ini_time_ * unit::second; +} + +vector3_t InitialInfoTreeIO::getInitialPosition() const +{ + return vector3_t(ini_posx_ * unit::cm, ini_posy_ * unit::cm, ini_posz_ * unit::cm); +} + +vector3_t InitialInfoTreeIO::getInitialPolarization() const +{ + return vector3_t(ini_polarx_, ini_polary_, ini_polarz_); +} + +double InitialInfoTreeIO::getWeight() const +{ + return weight_; +} + +void InitialInfoTreeIO::setInitialEnergy(double v) +{ + ini_energy_ = v / unit::keV; +} + +void InitialInfoTreeIO::setInitialDirection(double x, double y, double z) +{ + ini_dirx_ = x; + ini_diry_ = y; + ini_dirz_ = z; +} + +void InitialInfoTreeIO::setInitialTime(double v) +{ + ini_time_ = v / unit::second; +} + +void InitialInfoTreeIO::setInitialPosition(double x, double y, double z) +{ + ini_posx_ = x / unit::cm; + ini_posy_ = y / unit::cm; + ini_posz_ = z / unit::cm; +} + +void InitialInfoTreeIO::setInitialPolarization(double x, double y, double z) +{ + ini_polarx_ = x; + ini_polary_ = y; + ini_polarz_ = z; +} + +void InitialInfoTreeIO::setWeight(double v) +{ + weight_ = v; +} + +} /* namespace comptonsoft */ diff --git a/pool/shard007/C++/0093351_RejectVpcEndpointConnectionsRequest.cpp b/pool/shard007/C++/0093351_RejectVpcEndpointConnectionsRequest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..19e3a87eb35b9832665eeb94fba4696dc8916ed3 --- /dev/null +++ b/pool/shard007/C++/0093351_RejectVpcEndpointConnectionsRequest.cpp @@ -0,0 +1,64 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include <aws/ec2/model/RejectVpcEndpointConnectionsRequest.h> +#include <aws/core/utils/StringUtils.h> +#include <aws/core/utils/memory/stl/AWSStringStream.h> + +using namespace Aws::EC2::Model; +using namespace Aws::Utils; + +RejectVpcEndpointConnectionsRequest::RejectVpcEndpointConnectionsRequest() : + m_dryRun(false), + m_dryRunHasBeenSet(false), + m_serviceIdHasBeenSet(false), + m_vpcEndpointIdsHasBeenSet(false) +{ +} + +Aws::String RejectVpcEndpointConnectionsRequest::SerializePayload() const +{ + Aws::StringStream ss; + ss << "Action=RejectVpcEndpointConnections&"; + if(m_dryRunHasBeenSet) + { + ss << "DryRun=" << std::boolalpha << m_dryRun << "&"; + } + + if(m_serviceIdHasBeenSet) + { + ss << "ServiceId=" << StringUtils::URLEncode(m_serviceId.c_str()) << "&"; + } + + if(m_vpcEndpointIdsHasBeenSet) + { + unsigned vpcEndpointIdsCount = 1; + for(auto& item : m_vpcEndpointIds) + { + ss << "VpcEndpointId." << vpcEndpointIdsCount << "=" + << StringUtils::URLEncode(item.c_str()) << "&"; + vpcEndpointIdsCount++; + } + } + + ss << "Version=2016-11-15"; + return ss.str(); +} + + +void RejectVpcEndpointConnectionsRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const +{ + uri.SetQueryString(SerializePayload()); +} diff --git a/pool/shard007/C++/0093358_SortCriterion.cpp b/pool/shard007/C++/0093358_SortCriterion.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a9a1107a2d98ef51678f522a51f1cc4fad7b6cc --- /dev/null +++ b/pool/shard007/C++/0093358_SortCriterion.cpp @@ -0,0 +1,85 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include <aws/glue/model/SortCriterion.h> +#include <aws/core/utils/json/JsonSerializer.h> + +#include <utility> + +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +namespace Aws +{ +namespace Glue +{ +namespace Model +{ + +SortCriterion::SortCriterion() : + m_fieldNameHasBeenSet(false), + m_sort(Sort::NOT_SET), + m_sortHasBeenSet(false) +{ +} + +SortCriterion::SortCriterion(JsonView jsonValue) : + m_fieldNameHasBeenSet(false), + m_sort(Sort::NOT_SET), + m_sortHasBeenSet(false) +{ + *this = jsonValue; +} + +SortCriterion& SortCriterion::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("FieldName")) + { + m_fieldName = jsonValue.GetString("FieldName"); + + m_fieldNameHasBeenSet = true; + } + + if(jsonValue.ValueExists("Sort")) + { + m_sort = SortMapper::GetSortForName(jsonValue.GetString("Sort")); + + m_sortHasBeenSet = true; + } + + return *this; +} + +JsonValue SortCriterion::Jsonize() const +{ + JsonValue payload; + + if(m_fieldNameHasBeenSet) + { + payload.WithString("FieldName", m_fieldName); + + } + + if(m_sortHasBeenSet) + { + payload.WithString("Sort", SortMapper::GetNameForSort(m_sort)); + } + + return payload; +} + +} // namespace Model +} // namespace Glue +} // namespace Aws diff --git a/pool/shard007/C++/0093359_putcomplianceitemsresponse.cpp b/pool/shard007/C++/0093359_putcomplianceitemsresponse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eb10abc59b435878eedeb9b728efbb669868aa73 --- /dev/null +++ b/pool/shard007/C++/0093359_putcomplianceitemsresponse.cpp @@ -0,0 +1,143 @@ +/* + Copyright 2013-2021 Paul Colby + + This file is part of QtAws. + + QtAws is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + QtAws is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with the QtAws. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "putcomplianceitemsresponse.h" +#include "putcomplianceitemsresponse_p.h" + +#include <QDebug> +#include <QNetworkReply> +#include <QXmlStreamReader> + +namespace QtAws { +namespace SSM { + +/*! + * \class QtAws::SSM::PutComplianceItemsResponse + * \brief The PutComplianceItemsResponse class provides an interace for SSM PutComplianceItems responses. + * + * \inmodule QtAwsSSM + * + * <fullname>AWS Systems Manager</fullname> + * + * AWS Systems Manager is a collection of capabilities that helps you automate management tasks such as collecting system + * inventory, applying operating system (OS) patches, automating the creation of Amazon Machine Images (AMIs), and + * configuring operating systems (OSs) and applications at scale. Systems Manager lets you remotely and securely manage the + * configuration of your managed instances. A <i>managed instance</i> is any Amazon Elastic Compute Cloud instance (EC2 + * instance), or any on-premises server or virtual machine (VM) in your hybrid environment that has been configured for + * Systems + * + * Manager> + * + * This reference is intended to be used with the <a + * href="https://docs.aws.amazon.com/systems-manager/latest/userguide/">AWS Systems Manager User + * + * Guide</a>> + * + * To get started, verify prerequisites and configure managed instances. For more information, see <a + * href="https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-setting-up.html">Setting up AWS + * Systems Manager</a> in the <i>AWS Systems Manager User + * + * Guide</i>> <p class="title"> <b>Related resources</b> + * + * </p <ul> <li> + * + * For information about how to use a Query API, see <a + * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/making-api-requests.html">Making API requests</a>. + * + * </p </li> <li> + * + * For information about other API actions you can perform on EC2 instances, see the <a + * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/">Amazon EC2 API + * + * Reference</a>> </li> <li> + * + * For information about AWS AppConfig, a capability of Systems Manager, see the <a + * href="https://docs.aws.amazon.com/appconfig/latest/userguide/">AWS AppConfig User Guide</a> and the <a + * href="https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/">AWS AppConfig API + * + * Reference</a>> </li> <li> + * + * For information about AWS Incident Manager, a capability of Systems Manager, see the <a + * href="https://docs.aws.amazon.com/incident-manager/latest/userguide/">AWS Incident Manager User Guide</a> and the <a + * href="https://docs.aws.amazon.com/incident-manager/latest/APIReference/">AWS Incident Manager API + * + * \sa SsmClient::putComplianceItems + */ + +/*! + * Constructs a PutComplianceItemsResponse object for \a reply to \a request, with parent \a parent. + */ +PutComplianceItemsResponse::PutComplianceItemsResponse( + const PutComplianceItemsRequest &request, + QNetworkReply * const reply, + QObject * const parent) + : SsmResponse(new PutComplianceItemsResponsePrivate(this), parent) +{ + setRequest(new PutComplianceItemsRequest(request)); + setReply(reply); +} + +/*! + * \reimp + */ +const PutComplianceItemsRequest * PutComplianceItemsResponse::request() const +{ + Q_D(const PutComplianceItemsResponse); + return static_cast<const PutComplianceItemsRequest *>(d->request); +} + +/*! + * \reimp + * Parses a successful SSM PutComplianceItems \a response. + */ +void PutComplianceItemsResponse::parseSuccess(QIODevice &response) +{ + //Q_D(PutComplianceItemsResponse); + QXmlStreamReader xml(&response); + /// @todo +} + +/*! + * \class QtAws::SSM::PutComplianceItemsResponsePrivate + * \brief The PutComplianceItemsResponsePrivate class provides private implementation for PutComplianceItemsResponse. + * \internal + * + * \inmodule QtAwsSSM + */ + +/*! + * Constructs a PutComplianceItemsResponsePrivate object with public implementation \a q. + */ +PutComplianceItemsResponsePrivate::PutComplianceItemsResponsePrivate( + PutComplianceItemsResponse * const q) : SsmResponsePrivate(q) +{ + +} + +/*! + * Parses a SSM PutComplianceItems response element from \a xml. + */ +void PutComplianceItemsResponsePrivate::parsePutComplianceItemsResponse(QXmlStreamReader &xml) +{ + Q_ASSERT(xml.name() == QLatin1String("PutComplianceItemsResponse")); + Q_UNUSED(xml) ///< @todo +} + +} // namespace SSM +} // namespace QtAws diff --git a/pool/shard007/C++/0093361_Atomics.cpp b/pool/shard007/C++/0093361_Atomics.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f3dcf7c568ab9422132d7528ae7d04d9e1de03c --- /dev/null +++ b/pool/shard007/C++/0093361_Atomics.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2007, 2008, 2010, 2012, 2015 Apple Inc. All rights reserved. + * Copyright (C) 2007 Justin Haygood (jhaygood@reaktix.com) + * + * 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. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h" +#include "Atomics.h" + +// Some architectures, like MIPS32, don't have GCC implementation for builtin __sync_* functions +// with 64 bits variable size. Official GCC answer for the problem: If a target doesn't support +// atomic operations on certain variable sizes, you are out of luck with atomicity in that case +// (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=56296). GCC >= 4.8 will support __atomic_* builtin +// functions for this purpose for all the GCC targets, but for current compilers we have to include +// our own implementation. +#if COMPILER(GCC_OR_CLANG) && !defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8) && USE(PTHREADS) + +#include "ThreadingPrimitives.h" + +namespace WTF { + +static const size_t kSwapLockCount = 32; +static Mutex s_swapLocks[kSwapLockCount]; + +static inline Mutex& getSwapLock(const volatile int64_t* addr) +{ + return s_swapLocks[(reinterpret_cast<intptr_t>(addr) >> 3U) % kSwapLockCount]; +} + +static int64_t atomicStep(int64_t volatile* addend, int64_t step) +{ + Mutex& mutex = getSwapLock(addend); + + mutex.lock(); + int64_t value = *addend + step; + *addend = value; + mutex.unlock(); + + return value; +} + +extern "C" { + +int64_t __sync_add_and_fetch_8(int64_t volatile* addend, int64_t value) +{ + return atomicStep(addend, value); +} + +int64_t __sync_sub_and_fetch_8(int64_t volatile* addend, int64_t value) +{ + return atomicStep(addend, -value); +} + +} // extern "C" + +} // namespace WTF + +#endif diff --git a/pool/shard007/C++/0093362_test_softmax_with_loss_layer.cpp b/pool/shard007/C++/0093362_test_softmax_with_loss_layer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6f45c3889c200c554b71817663d1f02d5e6e7074 --- /dev/null +++ b/pool/shard007/C++/0093362_test_softmax_with_loss_layer.cpp @@ -0,0 +1,61 @@ +// Copyright 2014 BVLC and contributors. + +#include <cmath> +#include <cstdlib> +#include <cstring> +#include <vector> + +#include "gtest/gtest.h" +#include "caffe/blob.hpp" +#include "caffe/common.hpp" +#include "caffe/filler.hpp" +#include "caffe/vision_layers.hpp" +#include "caffe/test/test_gradient_check_util.hpp" + +#include "caffe/test/test_caffe_main.hpp" + +namespace caffe { + +template <typename TypeParam> +class SoftmaxWithLossLayerTest : public MultiDeviceTest<TypeParam> { + typedef typename TypeParam::Dtype Dtype; + + protected: + SoftmaxWithLossLayerTest() + : blob_bottom_data_(new Blob<Dtype>(10, 5, 1, 1)), + blob_bottom_label_(new Blob<Dtype>(10, 1, 1, 1)) { + // fill the values + FillerParameter filler_param; + filler_param.set_std(10); + GaussianFiller<Dtype> filler(filler_param); + filler.Fill(this->blob_bottom_data_); + blob_bottom_vec_.push_back(blob_bottom_data_); + for (int i = 0; i < blob_bottom_label_->count(); ++i) { + blob_bottom_label_->mutable_cpu_data()[i] = caffe_rng_rand() % 5; + } + blob_bottom_vec_.push_back(blob_bottom_label_); + } + virtual ~SoftmaxWithLossLayerTest() { + delete blob_bottom_data_; + delete blob_bottom_label_; + } + Blob<Dtype>* const blob_bottom_data_; + Blob<Dtype>* const blob_bottom_label_; + vector<Blob<Dtype>*> blob_bottom_vec_; + vector<Blob<Dtype>*> blob_top_vec_; +}; + +TYPED_TEST_CASE(SoftmaxWithLossLayerTest, TestDtypesAndDevices); + + +TYPED_TEST(SoftmaxWithLossLayerTest, TestGradient) { + typedef typename TypeParam::Dtype Dtype; + LayerParameter layer_param; + SoftmaxWithLossLayer<Dtype> layer(layer_param); + layer.SetUp(this->blob_bottom_vec_, &this->blob_top_vec_); + GradientChecker<Dtype> checker(1e-2, 1e-2, 1701); + checker.CheckGradientSingle(&layer, &(this->blob_bottom_vec_), + &(this->blob_top_vec_), 0, -1, -1); +} + +} // namespace caffe diff --git a/pool/shard007/C++/0093381_Criterion.cpp b/pool/shard007/C++/0093381_Criterion.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a59115f12a7bbe767180c68e5bf897e43985f1d3 --- /dev/null +++ b/pool/shard007/C++/0093381_Criterion.cpp @@ -0,0 +1,140 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include <aws/accessanalyzer/model/Criterion.h> +#include <aws/core/utils/json/JsonSerializer.h> + +#include <utility> + +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +namespace Aws +{ +namespace AccessAnalyzer +{ +namespace Model +{ + +Criterion::Criterion() : + m_containsHasBeenSet(false), + m_eqHasBeenSet(false), + m_exists(false), + m_existsHasBeenSet(false), + m_neqHasBeenSet(false) +{ +} + +Criterion::Criterion(JsonView jsonValue) : + m_containsHasBeenSet(false), + m_eqHasBeenSet(false), + m_exists(false), + m_existsHasBeenSet(false), + m_neqHasBeenSet(false) +{ + *this = jsonValue; +} + +Criterion& Criterion::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("contains")) + { + Array<JsonView> containsJsonList = jsonValue.GetArray("contains"); + for(unsigned containsIndex = 0; containsIndex < containsJsonList.GetLength(); ++containsIndex) + { + m_contains.push_back(containsJsonList[containsIndex].AsString()); + } + m_containsHasBeenSet = true; + } + + if(jsonValue.ValueExists("eq")) + { + Array<JsonView> eqJsonList = jsonValue.GetArray("eq"); + for(unsigned eqIndex = 0; eqIndex < eqJsonList.GetLength(); ++eqIndex) + { + m_eq.push_back(eqJsonList[eqIndex].AsString()); + } + m_eqHasBeenSet = true; + } + + if(jsonValue.ValueExists("exists")) + { + m_exists = jsonValue.GetBool("exists"); + + m_existsHasBeenSet = true; + } + + if(jsonValue.ValueExists("neq")) + { + Array<JsonView> neqJsonList = jsonValue.GetArray("neq"); + for(unsigned neqIndex = 0; neqIndex < neqJsonList.GetLength(); ++neqIndex) + { + m_neq.push_back(neqJsonList[neqIndex].AsString()); + } + m_neqHasBeenSet = true; + } + + return *this; +} + +JsonValue Criterion::Jsonize() const +{ + JsonValue payload; + + if(m_containsHasBeenSet) + { + Array<JsonValue> containsJsonList(m_contains.size()); + for(unsigned containsIndex = 0; containsIndex < containsJsonList.GetLength(); ++containsIndex) + { + containsJsonList[containsIndex].AsString(m_contains[containsIndex]); + } + payload.WithArray("contains", std::move(containsJsonList)); + + } + + if(m_eqHasBeenSet) + { + Array<JsonValue> eqJsonList(m_eq.size()); + for(unsigned eqIndex = 0; eqIndex < eqJsonList.GetLength(); ++eqIndex) + { + eqJsonList[eqIndex].AsString(m_eq[eqIndex]); + } + payload.WithArray("eq", std::move(eqJsonList)); + + } + + if(m_existsHasBeenSet) + { + payload.WithBool("exists", m_exists); + + } + + if(m_neqHasBeenSet) + { + Array<JsonValue> neqJsonList(m_neq.size()); + for(unsigned neqIndex = 0; neqIndex < neqJsonList.GetLength(); ++neqIndex) + { + neqJsonList[neqIndex].AsString(m_neq[neqIndex]); + } + payload.WithArray("neq", std::move(neqJsonList)); + + } + + return payload; +} + +} // namespace Model +} // namespace AccessAnalyzer +} // namespace Aws diff --git a/pool/shard007/C++/0093389_repeatable_thread_test.cc b/pool/shard007/C++/0093389_repeatable_thread_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..19f22d726ac307fb398c8217d32f976f0d25223a --- /dev/null +++ b/pool/shard007/C++/0093389_repeatable_thread_test.cc @@ -0,0 +1,110 @@ +// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. +// This source code is licensed under both the GPLv2 (found in the +// COPYING file in the root directory) and Apache 2.0 License +// (found in the LICENSE.Apache file in the root directory). + +#include "util/repeatable_thread.h" + +#include <atomic> +#include <memory> + +#include "db/db_test_util.h" +#include "test_util/mock_time_env.h" +#include "test_util/sync_point.h" +#include "test_util/testharness.h" + +class RepeatableThreadTest : public testing::Test { + public: + RepeatableThreadTest() + : mock_clock_(std::make_shared<ROCKSDB_NAMESPACE::MockSystemClock>( + ROCKSDB_NAMESPACE::SystemClock::Default())) {} + + protected: + std::shared_ptr<ROCKSDB_NAMESPACE::MockSystemClock> mock_clock_; +}; + +TEST_F(RepeatableThreadTest, TimedTest) { + constexpr uint64_t kSecond = 1000000; // 1s = 1000000us + constexpr int kIteration = 3; + const auto& clock = ROCKSDB_NAMESPACE::SystemClock::Default(); + ROCKSDB_NAMESPACE::port::Mutex mutex; + ROCKSDB_NAMESPACE::port::CondVar test_cv(&mutex); + int count = 0; + uint64_t prev_time = clock->NowMicros(); + ROCKSDB_NAMESPACE::RepeatableThread thread( + [&] { + ROCKSDB_NAMESPACE::MutexLock l(&mutex); + count++; + uint64_t now = clock->NowMicros(); + assert(count == 1 || prev_time + 1 * kSecond <= now); + prev_time = now; + if (count >= kIteration) { + test_cv.SignalAll(); + } + }, + "rt_test", clock.get(), 1 * kSecond); + // Wait for execution finish. + { + ROCKSDB_NAMESPACE::MutexLock l(&mutex); + while (count < kIteration) { + test_cv.Wait(); + } + } + + // Test cancel + thread.cancel(); +} + +TEST_F(RepeatableThreadTest, MockEnvTest) { + constexpr uint64_t kSecond = 1000000; // 1s = 1000000us + constexpr int kIteration = 3; + mock_clock_->SetCurrentTime(0); // in seconds + std::atomic<int> count{0}; + +#if defined(OS_MACOSX) && !defined(NDEBUG) + ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing(); + ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks(); + ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack( + "InstrumentedCondVar::TimedWaitInternal", [&](void* arg) { + // Obtain the current (real) time in seconds and add 1000 extra seconds + // to ensure that RepeatableThread::wait invokes TimedWait with a time + // greater than (real) current time. This is to prevent the TimedWait + // function from returning immediately without sleeping and releasing + // the mutex on certain platforms, e.g. OS X. If TimedWait returns + // immediately, the mutex will not be released, and + // RepeatableThread::TEST_WaitForRun never has a chance to execute the + // callback which, in this case, updates the result returned by + // mock_clock->NowMicros. Consequently, RepeatableThread::wait cannot + // break out of the loop, causing test to hang. The extra 1000 seconds + // is a best-effort approach because there seems no reliable and + // deterministic way to provide the aforementioned guarantee. By the + // time RepeatableThread::wait is called, it is no guarantee that the + // delay + mock_clock->NowMicros will be greater than the current real + // time. However, 1000 seconds should be sufficient in most cases. + uint64_t time_us = *reinterpret_cast<uint64_t*>(arg); + if (time_us < mock_clock_->RealNowMicros()) { + *reinterpret_cast<uint64_t*>(arg) = + mock_clock_->RealNowMicros() + 1000; + } + }); + ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing(); +#endif // OS_MACOSX && !NDEBUG + + ROCKSDB_NAMESPACE::RepeatableThread thread( + [&] { count++; }, "rt_test", mock_clock_.get(), 1 * kSecond, 1 * kSecond); + for (int i = 1; i <= kIteration; i++) { + // Bump current time + thread.TEST_WaitForRun([&] { mock_clock_->SetCurrentTime(i); }); + } + // Test function should be exectued exactly kIteraion times. + ASSERT_EQ(kIteration, count.load()); + + // Test cancel + thread.cancel(); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + + return RUN_ALL_TESTS(); +} diff --git a/pool/shard007/C++/0093394_http_server.cpp b/pool/shard007/C++/0093394_http_server.cpp new file mode 100644 index 0000000000000000000000000000000000000000..275a7171ad0a33fe671cdddee1bc016acf7db43c --- /dev/null +++ b/pool/shard007/C++/0093394_http_server.cpp @@ -0,0 +1,124 @@ +// Copyright (c) 2014 The EventServer Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "HttpServer.h" + +#include "HttpParser.h" +#include "HttpRequest.h" +#include "HttpResponse.h" +using namespace http; + +#define Port 8081 +#define PortNum 5 + +HttpServer server(Port, PortNum); + +string concat(string key, string value) +{ + return key + ": " + value + "\r\n"; +} + +void sign_handler(HttpRequest *req, HttpResponse *rep, void *arg) +{ + rep -> addHeader("Content-Type", "text/plain"); + + HttpParser *parser = req -> getParser(); + + string origin = parser -> getOrigin(); + + rep -> addBody(origin); + + rep -> addBody("\n"); + + map<string, string> params = parser -> getParams(); + map<string, string>::iterator iter = params.begin(); + + for(; iter != params.end(); iter++) + { + rep -> addBody(concat((*iter).first, (*iter).second)); + } + + rep -> send(); +} + +void pub_handler(HttpRequest *req, HttpResponse *rep, void *arg) +{ + +} + +void sub_handler(HttpRequest *req, HttpResponse *rep, void *arg) +{ + +} + +void error_handler(HttpRequest *req, HttpResponse *rep, void *arg) +{ + rep -> addHeader("Content-Type", "text/plain"); + + HttpParser *parser = req -> getParser(); + + rep -> addBody(concat("method", parser -> getMethod())); + rep -> addBody(concat("version", parser -> getVersion())); + rep -> addBody(concat("url", parser -> getUrl())); + + map<string, string> header = parser -> getHeader(); + + map<string, string>::iterator iter = header.begin(); + + for(; iter != header.end(); iter++) + { + rep -> addBody(concat((*iter).first, (*iter).second)); + } + + rep -> addBody("\n"); + + map<string, string> params = parser -> getParams(); + iter = params.begin(); + + for(; iter != params.end(); iter++) + { + rep -> addBody(concat((*iter).first, (*iter).second)); + } + + rep -> send(); +} + +/// Signal Stop the server +void signalStop(int) +{ + INFO << "Stop running...by manually"; + server.stop(); +} + +/// Change the configure +int setlimit(int num_pipes) +{ + struct rlimit rl; + rl.rlim_cur = rl.rlim_max = num_pipes * 2 + 50; + if (::setrlimit(RLIMIT_NOFILE, &rl) == -1) + { + fprintf(stderr, "setrlimit error: %s", strerror(errno)); + return 1; + } +} + +int main() +{ + Log::setLevel(Log::debug); + + ::signal(SIGINT, signalStop); + setlimit(100000); + errno = 0; + + server.add("/sign", sign_handler, NULL); + server.add("/pub", pub_handler, NULL); + server.add("/sub", sub_handler, NULL); + server.error(error_handler, NULL); + + INFO << "server starting" ; + server.start(); + + INFO << "server stopping" ; + return 0; +} \ No newline at end of file diff --git a/pool/shard007/C++/0093405_NtQuerySysInfo_SystemLockInformation.cpp b/pool/shard007/C++/0093405_NtQuerySysInfo_SystemLockInformation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..df6f067a7b606672cea3af1e9868949dbab2d67f --- /dev/null +++ b/pool/shard007/C++/0093405_NtQuerySysInfo_SystemLockInformation.cpp @@ -0,0 +1,72 @@ +// NtQuerySysInfo_SystemModuleInformation.cpp : Attempts to use the NtQuerySystemInformation to find the base addresses if loaded modules. +// + +#include "stdafx.h" +#include <windows.h> + +typedef struct _SYSTEM_LOCK { + PVOID Address; + USHORT Type; + USHORT Reserved1; + ULONG ExclusiveOwnerThreadId; + ULONG ActiveCount; + ULONG ContentionCount; + ULONG Reserved2[2]; +#ifdef _WIN64 + ULONG Reserved3; +#endif + ULONG NumberOfSharedWaiters; + ULONG NumberOfExclusiveWaiters; +} SYSTEM_LOCK, *PSYSTEM_LOCK; + +typedef struct SYSTEM_LOCK_INFORMATION { + ULONG LocksCount; + SYSTEM_LOCK Locks[1]; +} SYSTEM_LOCK_INFORMATION, *PSYSTEM_LOCK_INFORMATION; + +typedef enum _SYSTEM_INFORMATION_CLASS { + SystemLockInformation = 12 +} SYSTEM_INFORMATION_CLASS; + +typedef NTSTATUS(WINAPI *PNtQuerySystemInformation)( + __in SYSTEM_INFORMATION_CLASS SystemInformationClass, + __inout PVOID SystemInformation, + __in ULONG SystemInformationLength, + __out_opt PULONG ReturnLength + ); + +int main() +{ + HMODULE ntdll = GetModuleHandle(TEXT("ntdll")); + PNtQuerySystemInformation query = (PNtQuerySystemInformation)GetProcAddress(ntdll, "NtQuerySystemInformation"); + if (query == NULL) { + printf("GetProcAddress() failed.\n"); + return 1; + } + + PSYSTEM_LOCK_INFORMATION pLockInfo = NULL; + ULONG len = 20; + NTSTATUS status = (NTSTATUS)0xc0000004; + + do { + len *= 2; + pLockInfo = (PSYSTEM_LOCK_INFORMATION)GlobalAlloc(GMEM_ZEROINIT, len); + status = query(SystemLockInformation, pLockInfo, len, &len); + } while (status == (NTSTATUS)0xc0000004); + if (status != (NTSTATUS)0x0) { + printf("NtQuerySystemInformation failed with error code 0x%X\n", status); + return 1; + } + for (unsigned int i = 0; i < pLockInfo->LocksCount; i++) { + PVOID lockAddress = pLockInfo->Locks[i].Address; + USHORT lockType = (USHORT)pLockInfo->Locks[i].Type; +#ifdef _WIN64 + printf("Lock Address 0x%llx\t", lockAddress); +#else + printf("Lock Address 0x%X\t", lockAddress); +#endif + printf("Lock Type 0x%X\r\n", lockType); + } + return 0; +} + diff --git a/pool/shard007/C++/0093407_p4est_3d_refine_04.cc b/pool/shard007/C++/0093407_p4est_3d_refine_04.cc new file mode 100644 index 0000000000000000000000000000000000000000..5217d50d53a12c2a83531071e379d5a9d81247e9 --- /dev/null +++ b/pool/shard007/C++/0093407_p4est_3d_refine_04.cc @@ -0,0 +1,140 @@ +// --------------------------------------------------------------------- +// +// Copyright (C) 2009 - 2013 by the deal.II authors +// +// This file is part of the deal.II library. +// +// The deal.II library is free software; you can use it, redistribute +// it, and/or modify it under the terms of the GNU Lesser General +// Public License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// The full text of the license can be found in the file LICENSE at +// the top level of the deal.II distribution. +// +// --------------------------------------------------------------------- + + + +// create a relatively simple 3d mesh and refine a few cells. this +// should produce the same output regardless of the number of +// processors +// +// this test is extracted from step-32 while searching for some +// apparently rather subtle and indeed pretty frustrating bug... + +#include "../tests.h" +#include "coarse_grid_common.h" +#include <deal.II/base/logstream.h> +#include <deal.II/base/tensor.h> +#include <deal.II/grid/tria.h> +#include <deal.II/distributed/tria.h> +#include <deal.II/grid/tria_accessor.h> +#include <deal.II/grid/grid_generator.h> +#include <deal.II/grid/grid_out.h> +#include <deal.II/grid/grid_tools.h> +#include <deal.II/base/utilities.h> + +#include <fstream> +#include <ostream> + + +template<int dim> +void test() +{ + unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD); + + if (true) + { + parallel::distributed::Triangulation<dim> + triangulation(MPI_COMM_WORLD); + + // create a mesh for the + // hypershell and refine it + // twice globally + const double R0 = 6371000.-2890000.; + const double R1 = 6371000.- 35000.; + GridGenerator::hyper_shell (triangulation, + Point<dim>(), + R0, + R1, + (dim==3) ? 96 : 12, + true); + triangulation.refine_global (2); + + // then flag all cells for + // refinement that are close to + // the north pole + unsigned int x_flagged_cells = 0; + for (typename Triangulation<dim>::active_cell_iterator + cell = triangulation.begin_active(); + cell != triangulation.end(); ++cell) + if (!cell->is_ghost() && !cell->is_artificial()) + if (cell->center()[2] > R1*0.75) + { + ++x_flagged_cells; + cell->set_refine_flag(); + } + + // count how many cells + // actually have the refinement + // flag after preparing for + // refinement, and ensure that + // this number is still the + // same as before + triangulation.prepare_coarsening_and_refinement (); + { + unsigned int n_flagged_cells = 0; + for (typename Triangulation<dim>::active_cell_iterator + cell = triangulation.begin_active(); + cell != triangulation.end(); ++cell) + if (!cell->is_ghost() && !cell->is_artificial()) + if (cell->refine_flag_set()) + ++n_flagged_cells; + + Assert (n_flagged_cells == x_flagged_cells, + ExcInternalError()); + + unsigned int global_f_c = 0; + MPI_Allreduce (&n_flagged_cells, &global_f_c, 1, MPI_UNSIGNED, + MPI_SUM, MPI_COMM_WORLD); + + if (myid == 0) + deallog << "# flagged cells = " << global_f_c << std::endl; + } + + triangulation.execute_coarsening_and_refinement (); + + if (myid == 0) + deallog << "#cells = " << triangulation.n_global_active_cells() + << std::endl; + } + + if (Utilities::MPI::this_mpi_process (MPI_COMM_WORLD) == 0) + deallog << "OK" << std::endl; +} + + +int main(int argc, char *argv[]) +{ + Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); + + unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD); + + + deallog.push(Utilities::int_to_string(myid)); + + if (myid == 0) + { + std::ofstream logfile("output"); + deallog.attach(logfile); + deallog.depth_console(0); + deallog.threshold_double(1.e-10); + + deallog.push("3d"); + test<3>(); + deallog.pop(); + } + else + test<3>(); + +} diff --git a/pool/shard007/C++/0093411_vtv_malloc.cc b/pool/shard007/C++/0093411_vtv_malloc.cc new file mode 100644 index 0000000000000000000000000000000000000000..ea26b8245c37873ebaa6e7eabcd50e6a94da0d67 --- /dev/null +++ b/pool/shard007/C++/0093411_vtv_malloc.cc @@ -0,0 +1,290 @@ +/* Copyright (C) 2012-2015 Free Software Foundation, Inc. + + This file is part of GCC. + + GCC is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + GCC is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + Under Section 7 of GPL version 3, you are granted additional + permissions described in the GCC Runtime Library Exception, version + 3.1, as published by the Free Software Foundation. + + You should have received a copy of the GNU General Public License and + a copy of the GCC Runtime Library Exception along with this program; + see the files COPYING3 and COPYING.RUNTIME respectively. If not, see + <http://www.gnu.org/licenses/>. */ + +/* This file is part of the vtable verification runtime library. It + contains our memory allocation and deallocation routines, which we + use in order to keep track of the pages in memory in which our sets + of valid vtable pointes are stored. (We need to know the pages so + we can set the protections on them appropriately). For more + information about the vtable verification feature, see the comments + in vtv_rts.cc. We use the existing obstack implementation in our + memory allocation scheme. */ + +#include <stdlib.h> +#include <unistd.h> +#if defined (__CYGWIN__) || defined (__MINGW32__) +#include <windows.h> +#else +#include <sys/mman.h> +#endif +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> +#include <stdio.h> + +#include "vtv_utils.h" +#include "vtv_malloc.h" +#include "obstack.h" + +/* The following variables are used only for debugging and performance tuning + purposes. Therefore they do not need to be "protected". They cannot be used + to attack the vtable verification system and if they become corrupted it will + not affect the correctness or security of any of the rest of the vtable + verification feature. */ + +unsigned int num_calls_to_mprotect = 0; +unsigned int num_pages_protected = 0; +unsigned int long long mprotect_cycles = 0; + +/* Put the following variables in our ".vtable_map_vars" section so + that they are protected. They are explicitly unprotected and + protected again by calls to __vtv_unprotect and __vtv_protect */ + +static struct obstack vtv_obstack VTV_PROTECTED_VAR; +static void *current_chunk VTV_PROTECTED_VAR = 0; +static size_t current_chunk_size VTV_PROTECTED_VAR = 0; +static int malloc_initialized VTV_PROTECTED_VAR = 0; + +#if defined (__CYGWIN__) || defined (__MINGW32__) +//sysconf(_SC_PAGE_SIZE) port +long sysconf_SC_PAGE_SIZE() +{ + SYSTEM_INFO si; + GetSystemInfo(&si); + long pageSize = (long)si.dwPageSize; + return pageSize; + //return 4096; // standard usermode 32bit pagesize in bytes // FIXME +} +#endif + +/* The function goes through and counts all the pages we have allocated + so far. It returns the page count. */ + +int +__vtv_count_mmapped_pages (void) +{ + int count = 0; + struct _obstack_chunk * ci = (struct _obstack_chunk *) current_chunk; + while (ci) + { + count++; + ci = ci->prev; + } + + return count; +} + +/* This function goes through all of the pages we have allocated so + far and calls mprotect to change the protections on the pages, + according to the value of PROTECTION_FLAG. */ + +static void +change_protections_on_data_chunks (int protection_flag) +{ + struct _obstack_chunk *ci; + ci = (struct _obstack_chunk *) current_chunk; + + while (ci) + { + /* Initial set up for mprotect call.*/ + struct _obstack_chunk *protect_start = ci; + size_t chunk_size; + size_t total_size; + unsigned int num_pages_in_chunk; + char *next_page; + unsigned long long start, end; + int result; + + + /* As long as the next 'chunk' is adjacent to the current one, + keep going down the list. */ + do + { + chunk_size = (ci->limit - (char *) ci); + total_size = (ci->limit - (char *) protect_start); + num_pages_in_chunk = chunk_size / VTV_PAGE_SIZE; + if (chunk_size % VTV_PAGE_SIZE > 0) + num_pages_in_chunk++; + next_page = (char *) ci + (num_pages_in_chunk * VTV_PAGE_SIZE); + ci = ci->prev; + } while (ci && (char *) ci == next_page); + + VTV_DEBUG_ASSERT (((unsigned long) protect_start & (VTV_PAGE_SIZE - 1)) + == 0); + + /* Protect the contiguous chunks so far. */ + start = rdtsc (); + result = mprotect (protect_start, total_size, protection_flag); + end = rdtsc (); + mprotect_cycles += end - start; + if (result == -1) + VTV_error (); + num_calls_to_mprotect++; + num_pages_protected += (total_size + VTV_PAGE_SIZE - 1)/ VTV_PAGE_SIZE; + } + +#ifdef VTV_DEBUG + __vtv_malloc_dump_stats (); +#endif +} + +/* This function makes all of our allocated pages read-only. */ + +void +__vtv_malloc_protect (void) +{ + change_protections_on_data_chunks (PROT_READ); +} + +/* This function makes all of our allocated pages read-write. */ + +void +__vtv_malloc_unprotect (void) +{ + change_protections_on_data_chunks (PROT_READ | PROT_WRITE); +} + +/* Allocates a SIZE-sized chunk of memory that is aligned to a page + boundary. The amount of memory requested (SIZE) must be a multiple + of the page size. Note: We must use mmap to allocate the memory; + using malloc here will cause problems. */ + +static void * +obstack_chunk_alloc (size_t size) +{ + /* Increase size to the next multiple of VTV_PAGE_SIZE. */ + size = (size + (VTV_PAGE_SIZE - 1)) & (~(VTV_PAGE_SIZE - 1)); + VTV_DEBUG_ASSERT ((size & (VTV_PAGE_SIZE - 1)) == 0); + void *allocated; + +#if defined (__CYGWIN__) || defined (__MINGW32__) + if ((allocated = VirtualAlloc(NULL, size, MEM_RESERVE|MEM_COMMIT, + PAGE_READWRITE)) == 0) +#else + if ((allocated = mmap (NULL, size, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)) == 0) +#endif + VTV_error (); + + VTV_DEBUG_ASSERT (((unsigned long) allocated & (VTV_PAGE_SIZE - 1)) == 0); + + current_chunk = allocated; + current_chunk_size = size; + return allocated; +} + +static void +obstack_chunk_free (void *) +{ + /* Do nothing. For our purposes there should be very little + de-allocation. */ +} + +/* This function sets up and initializes the obstack pieces for our + memory allocation scheme. */ + +void +__vtv_malloc_init (void) +{ + /* Make sure we only execute the main body of this function ONCE. */ + if (malloc_initialized) + return; + +#if defined (__CYGWIN__) || defined (__MINGW32__) + if (VTV_PAGE_SIZE != sysconf_SC_PAGE_SIZE()) +#else + if (VTV_PAGE_SIZE != sysconf (_SC_PAGE_SIZE)) +#endif + VTV_error (); + + /* We guarantee that the obstack alloc failed handler will never be + called because in case the allocation of the chunk fails, it will + never return */ + obstack_alloc_failed_handler = NULL; + + obstack_specify_allocation (&vtv_obstack, VTV_PAGE_SIZE, sizeof (long), + obstack_chunk_alloc, obstack_chunk_free); + malloc_initialized = 1; +} + +/* This is our external interface for the memory allocation. SIZE is + the requested number of bytes to be allocated/ */ + +void * +__vtv_malloc (size_t size) +{ + return obstack_alloc (&vtv_obstack, size); +} + + +/* This is our external interface for memory deallocation. */ + +void +__vtv_free (void *) +{ + /* Do nothing. We dont care about recovering unneded memory at this + time. */ +} + + +/* This is a debugging function tat collects statistics about our + memory allocation. */ +void +__vtv_malloc_stats (void) +{ + int count = 0; + struct _obstack_chunk * ci = (struct _obstack_chunk *) current_chunk; + while (ci) + { + count++; + ci = ci->prev; + } + fprintf (stderr, + "__vtv_malloc_stats:\n Page Size = %lu bytes\n " + "Number of pages = %d\n", static_cast<unsigned long>(VTV_PAGE_SIZE), + count); +} + +/* This is a debugging function. It writes out our memory allocation + statistics to a log file. */ + +void +__vtv_malloc_dump_stats (void) +{ + static int fd = -1; + + if (fd == -1) + fd = __vtv_open_log ("vtv_mem_protection.log"); + if (fd == -1) + return; + + int count = 0; + struct _obstack_chunk * ci = (struct _obstack_chunk *) current_chunk; + while (ci) + { + count++; + ci = ci->prev; + } + + __vtv_add_to_log (fd, "__vtv_malloc_protect protected=%d pages\n", count); +} diff --git a/pool/shard007/C++/0093421_GenTemplate.cpp b/pool/shard007/C++/0093421_GenTemplate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..123fc286803254f2567ce6aa754a074a0264d075 --- /dev/null +++ b/pool/shard007/C++/0093421_GenTemplate.cpp @@ -0,0 +1,102 @@ +/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + Copyright (c) 2012-2021 The plumed team + (see the PEOPLE file at the root of the distribution for a list of names) + + See http://www.plumed.org for more information. + + This file is part of plumed, version 2. + + plumed is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + plumed is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with plumed. If not, see <http://www.gnu.org/licenses/>. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ +#include "CLTool.h" +#include "CLToolRegister.h" +#include "tools/Tools.h" +#include "core/ActionRegister.h" +#include <cstdio> +#include <string> +#include <iostream> + +namespace PLMD { +namespace cltools { + +//+PLUMEDOC TOOLS gentemplate +/* +gentemplate is a tool that you can use to construct template inputs for the various actions + +The templates generated by this tool are primarily for use with Toni Giorgino's VMD GUI. It may be +useful however to use this tool as a quick aid memoir. + +\par Examples + +The following generates template input for the action DISTANCE. +\verbatim +plumed gentemplate --action DISTANCE +\endverbatim + + +*/ +//+ENDPLUMEDOC + +class GenTemplate: + public CLTool +{ +public: + static void registerKeywords( Keywords& keys ); + explicit GenTemplate(const CLToolOptions& co ); + int main(FILE* in, FILE*out,Communicator& pc) override; + std::string description()const override { + return "print out a template input for a particular action"; + } +}; + +PLUMED_REGISTER_CLTOOL(GenTemplate,"gentemplate") + +void GenTemplate::registerKeywords( Keywords& keys ) { + CLTool::registerKeywords( keys ); + keys.add("optional","--action","print the template for this particular action"); + keys.addFlag("--list",false,"print a list of the available actions"); + keys.addFlag("--include-optional",false,"also print optional modifiers"); +} + +GenTemplate::GenTemplate(const CLToolOptions& co ): + CLTool(co) +{ + inputdata=commandline; +} + +int GenTemplate::main(FILE* in, FILE*out,Communicator& pc) { + + std::string action; + bool list_templates=false; + parseFlag("--list",list_templates); + + if(list_templates) { + std::cerr<<actionRegister()<<"\n"; + return 0; + } else if(parse("--action",action)) { + bool include_optional; + parseFlag("--include-optional",include_optional); + if( !actionRegister().printTemplate(action,include_optional) ) { + error("there is no registered action named " + action); + return 1; + } + } else return 1; + + + + return 0; +} +} + +} // End of namespace diff --git a/pool/shard007/C++/0093431_splashscreen.cpp b/pool/shard007/C++/0093431_splashscreen.cpp new file mode 100644 index 0000000000000000000000000000000000000000..894ada816c3d95c6b2460dbde3af6343a90bb756 --- /dev/null +++ b/pool/shard007/C++/0093431_splashscreen.cpp @@ -0,0 +1,52 @@ +#include "splashscreen.h" +#include "clientversion.h" +#include "util.h" + +#include <QPainter> +#undef loop /* ugh, remove this when the #define loop is gone from util.h */ +#include <QApplication> + +SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) : + QSplashScreen(pixmap, f) +{ + // set reference point, paddings + int paddingLeftCol2 = 230; + int paddingTopCol2 = 376; + int line1 = 0; + int line2 = 13; + int line3 = 26; + + float fontFactor = 1.0; + + // define text to place + QString titleText = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down + QString versionText = QString("Version %1 ").arg(QString::fromStdString(FormatFullVersion())); + QString copyrightText1 = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin developers")); + QString copyrightText2 = QChar(0xA9)+QString(" %1 ").arg(COPYRIGHT_YEAR) + QString(tr("Gecicoin")); + + QString font = "Arial"; + + // load the bitmap for writing some text over it + QPixmap newPixmap; + if(GetBoolArg("-testnet")) { + newPixmap = QPixmap(":/images/splash_testnet"); + } + else { + newPixmap = QPixmap(":/images/splash"); + } + + QPainter pixPaint(&newPixmap); + pixPaint.setPen(QColor(70,70,70)); + + pixPaint.setFont(QFont(font, 9*fontFactor)); + pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line3,versionText); + + // draw copyright stuff + pixPaint.setFont(QFont(font, 9*fontFactor)); + pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line1,copyrightText1); + pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line2,copyrightText2); + + pixPaint.end(); + + this->setPixmap(newPixmap); +} diff --git a/pool/shard007/C++/0093435_matrix.cpp b/pool/shard007/C++/0093435_matrix.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4e4df2b9d85b5b7d23b14be978eeb5d09a162db3 --- /dev/null +++ b/pool/shard007/C++/0093435_matrix.cpp @@ -0,0 +1,110 @@ +/** derived from */ + +#include <stdio.h> +#include <stdlib.h> +#include <math.h> +#include <algorithm> +#include <time.h> +#include <omp.h> + +void createData(int const num_rows, int const num_cols, float* const a, float* const b, + float* const c, float* const ref); +void checkSol(int const num_rows, int const num_cols, float const* const a, float const* const b); + +/** + * optimize this code + */ +void add(float* const a, float* const b, float* const c, int const num_rows, int const num_cols) +{ + #pragma omp parallel for collapse(2) + for(int col = 0; col < num_cols; col++) { + for(int row = 0; row < num_rows; row++) { + int i = col + row * num_cols; + c[i] = a[i] + b[i]; + } + } +} + +int main() +{ + float *a, *b, *c, *sol; + + int const NUM_ROWS = 2048; + int const NUM_COLS = 2048; + size_t const N_BYTES = NUM_ROWS * NUM_COLS * sizeof(float); + + a = (float*)malloc(N_BYTES); + b = (float*)malloc(N_BYTES); + c = (float*)malloc(N_BYTES); + sol = (float*)malloc(N_BYTES); + + createData(NUM_ROWS, NUM_COLS, a, b, c, sol); + + // c = a + b + add(a, b, c, NUM_ROWS, NUM_COLS); + + checkSol(NUM_ROWS, NUM_COLS, c, sol); + + free(a); + free(b); + free(c); + free(sol); + + return 0; +} + +void createData(int const num_rows, int const num_cols, float* const a, float* const b, float* const c, float* const ref) +{ + int row, col; + + srand((unsigned)time(NULL)); + + #pragma omp parallel for collapse(2) + for(int row = 0; row < num_rows; row++) { + for(int col = 0; col < num_cols; col++) { + int i = col + row * num_cols; + a[i] = static_cast <float> (rand()) / static_cast <float> (RAND_MAX); + b[i] = static_cast <float> (rand()) / static_cast <float> (RAND_MAX); + c[i] = 0.0f; + ref[i] = a[i] + b[i]; + } + } +} + +void checkSol(int const num_rows, int const num_cols, float const* const a, float const* const b) +{ + int const N = num_rows * num_cols; + + int different = 0; + + int beginpos = 0, n_per_loop = 2048 * 2048 / omp_get_max_threads(); + while(beginpos < N && !different) + { + int endpos = std::min(N, beginpos + n_per_loop); + #pragma omp parallel for reduction(|:different) + for(int i = beginpos; i < endpos; i++) + if(a[i] != b[i]) + { + different = 1; + } + beginpos = endpos; + } + + + // #pragma omp parallel + // { + // int this_thread = omp_get_thread_num(), num_threads = omp_get_num_threads(); + // size_t beginpos = (this_thread+0) * N / num_threads; + // size_t endpos = (this_thread+1) * N / num_threads; + // // watch out for overflow in that multiplication. + // #pragma omp for reduction(|:different) + // for(size_t i=beginpos; i < endpos; i++) { + // different = (a[i] != b[i]); + // } + // } + + if(different) + printf("Arrays do not match.\n"); + else + printf("Arrays match.\n"); +} diff --git a/pool/shard007/C++/0093447_scantest.cpp b/pool/shard007/C++/0093447_scantest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..917fe52e10e3117cb5ccecfa9db6ebd7d7fb943f --- /dev/null +++ b/pool/shard007/C++/0093447_scantest.cpp @@ -0,0 +1,56 @@ +/* This file is part of FSView. + Copyright (C) 2002, 2003 Josef Weidendorfer <Josef.Weidendorfer@gmx.de> + + KCachegrind is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation, version 2. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +/* Test Directory Scanning. Usually not build. */ + +#include <stdio.h> +#include <unistd.h> + +#include "scan.h" + +class MyListener: public ScanListener +{ +public: + void scanStarted(ScanDir* d) + { + printf("Started Scan on %s\n", qPrintable(d->name())); + }; + + void sizeChanged(ScanDir* d) + { + printf("Change in %s: Dirs %d, Files %d", + qPrintable(d->name()), + d->dirCount(), d->fileCount()); + printf("Size %llu\n", (unsigned long long int)d->size()); + } + + void scanFinished(ScanDir* d) + { + printf("Finished Scan on %s\n", qPrintable(d->name())); + } +}; + +int main(int argc, char* argv[]) +{ + ScanManager m("/opt"); + if (argc>1) m.setTop(argv[1]); + + m.setListener(new MyListener()); + m.startScan(); + while(m.scan(1)); +} diff --git a/pool/shard007/C++/0093448_projectnamevalidatinglineedit.cpp b/pool/shard007/C++/0093448_projectnamevalidatinglineedit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f4762a5ed99c4e6f1fb207ab9d155a16e5100e49 --- /dev/null +++ b/pool/shard007/C++/0093448_projectnamevalidatinglineedit.cpp @@ -0,0 +1,61 @@ +/************************************************************************** +** +** This file is part of Qt Creator +** +** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +** +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** Commercial Usage +** +** Licensees holding valid Qt Commercial licenses may use this file in +** accordance with the Qt Commercial License Agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Nokia. +** +** GNU Lesser General Public License Usage +** +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at http://qt.nokia.com/contact. +** +**************************************************************************/ + +#include "projectnamevalidatinglineedit.h" +#include "filenamevalidatinglineedit.h" + +namespace Utils { + +ProjectNameValidatingLineEdit::ProjectNameValidatingLineEdit(QWidget *parent) + : BaseValidatingLineEdit(parent) +{ +} + +bool ProjectNameValidatingLineEdit::validateProjectName(const QString &name, QString *errorMessage /* = 0*/) +{ + // Validation is file name + checking for dots + if (!FileNameValidatingLineEdit::validateFileName(name, false, errorMessage)) + return false; + + // We don't want dots in the directory name for some legacy Windows + // reason. Since we are cross-platform, we generally disallow it. + if (name.contains(QLatin1Char('.'))) { + if (errorMessage) + *errorMessage = tr("The name must not contain the '.'-character."); + return false; + } + return true; +} + +bool ProjectNameValidatingLineEdit::validate(const QString &value, QString *errorMessage) const +{ + return validateProjectName(value, errorMessage); +} + +} // namespace Utils diff --git a/pool/shard007/C++/0093454_EnvelopFinderTest.cpp b/pool/shard007/C++/0093454_EnvelopFinderTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b25cd9b7c770de4998abaa653de8755f66d62584 --- /dev/null +++ b/pool/shard007/C++/0093454_EnvelopFinderTest.cpp @@ -0,0 +1,95 @@ +/******************************************************************** + created: 2012/11/16 + created: 16:11:2012 16:59 + filename: E:\Sync\Dropbox\Codes\glycan_pipeline\GAG\test\EnvelopFinderTest.cpp + file path: E:\Sync\Dropbox\Codes\glycan_pipeline\GAG\test + file base: EnvelopFinderTest + file ext: cpp + author: Han Hu + + purpose: +*********************************************************************/ + +#include <GAGPL/SPECTRUM/EnvelopFinder.h> +#include <GAGPL/SPECTRUM/PeakList.h> +#include <iostream> +#include <sstream> +#include <fstream> +#include <utility> +#include <boost/algorithm/string.hpp> + +using namespace gag; +using namespace std; + +RichList readSpectrum() +{ + std::cout << "Load spectrum..." << std::endl; + + std::ifstream infile("../data/spectrum.txt"); + + std::string line; + + RichList spec; + if(infile.is_open()) + { + while(std::getline(infile, line)) + { + std::istringstream is; + is.str(line); + double k1, k2, k3, k4; + is >> k1 >> k2 >> k3 >> k4; + //gag::Peak pk(k1, k2); + RichPeakPtr pk = createRichPeak(k1, k2, k3, k4); + spec.addPeak(pk); + } + } + infile.close(); + infile.clear(); + return spec; + +} + +int main(int argc, char *argv[]) +{ + // Test 1 + cout << "Test 1: Manual interpretation" << endl; + RichList spec1; + RichPeakPtr pk0 = createRichPeak(376.49227,2125405,5184,3.7); + RichPeakPtr pk1 = createRichPeak(376.99506,51087228,311536,130); + RichPeakPtr pk2 = createRichPeak(377.32956,12896527,68383,31.5); + RichPeakPtr pk3 = createRichPeak(377.65959,3833504,4942,8.1); + RichPeakPtr pk4 = createRichPeak(377.66405,4087202,5864,8.7); + RichPeakPtr pk5 = createRichPeak(377.99828,1626549,5004,2.4); + spec1.addPeak(pk0); + spec1.addPeak(pk1); + spec1.addPeak(pk2); + spec1.addPeak(pk3); + spec1.addPeak(pk4); + spec1.addPeak(pk5); + + EnvelopFinder env_finder1(spec1); + + std::vector<EnvelopPtr> env_pool1 = env_finder1.getEnvelops(); + BOOST_FOREACH(EnvelopPtr env, env_pool1) + { + env_finder1.printEnvelop(env); + } + // Test 2 + //cout << endl; + //cout << "Test 2: Real spectrum" << endl; + //// 1. TBD: Read the data and examine the format of the data. + // + //RichList spectrum = readSpectrum(); + //spectrum.printPeakList<peak_mz>(); + + //EnvelopFinder env_finder2(spectrum); + + //// 2. print the identified envelops. + //std::vector<EnvelopPtr> env_pool = env_finder2.getEnvelops(); + + //BOOST_FOREACH(EnvelopPtr env, env_pool) + //{ + // env_finder2.printEnvelop(env); + //} + +} \ No newline at end of file diff --git a/pool/shard007/C++/0093467_capflooredinflationcoupon.cpp b/pool/shard007/C++/0093467_capflooredinflationcoupon.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6cfd2f03fd8821753dbb5e230ac5d65358c129ff --- /dev/null +++ b/pool/shard007/C++/0093467_capflooredinflationcoupon.cpp @@ -0,0 +1,164 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ + +/* + Copyright (C) 2009 Chris Kenyon + + This file is part of QuantLib, a free-software/open-source library + for financial quantitative analysts and developers - http://quantlib.org/ + + QuantLib is free software: you can redistribute it and/or modify it + under the terms of the QuantLib license. You should have received a + copy of the license along with this program; if not, please email + <quantlib-dev@lists.sf.net>. The license is also available online at + <http://quantlib.org/license.shtml>. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the license for more details. + */ + +#include <ql/cashflows/capflooredinflationcoupon.hpp> +#include <ql/cashflows/inflationcouponpricer.hpp> + +namespace QuantLib { + + void CappedFlooredYoYInflationCoupon::setCommon( + Rate cap, Rate floor) { + + isCapped_ = false; + isFloored_ = false; + + if (gearing_ > 0) { + if (cap != Null<Rate>()) { + isCapped_ = true; + cap_ = cap; + } + if (floor != Null<Rate>()) { + floor_ = floor; + isFloored_ = true; + } + } else { + if (cap != Null<Rate>()){ + floor_ = cap; + isFloored_ = true; + } + if (floor != Null<Rate>()){ + isCapped_ = true; + cap_ = floor; + } + } + if (isCapped_ && isFloored_) { + QL_REQUIRE(cap >= floor, "cap level (" << cap << + ") less than floor level (" << floor << ")"); + } + } + + + CappedFlooredYoYInflationCoupon::CappedFlooredYoYInflationCoupon( + const boost::shared_ptr<YoYInflationCoupon>& underlying, + Rate cap, Rate floor) + : YoYInflationCoupon(underlying->date(), + underlying->nominal(), + underlying->accrualStartDate(), + underlying->accrualEndDate(), + underlying->fixingDays(), + underlying->yoyIndex(), + underlying->observationLag(), + underlying->dayCounter(), + underlying->gearing(), + underlying->spread(), + underlying->referencePeriodStart(), + underlying->referencePeriodEnd()), + underlying_(underlying), isFloored_(false), isCapped_(false) { + + setCommon(cap, floor); + registerWith(underlying); + } + + + void CappedFlooredYoYInflationCoupon::setPricer( + const boost::shared_ptr<YoYInflationCouponPricer>& pricer) { + + YoYInflationCoupon::setPricer(pricer); + if (underlying_) underlying_->setPricer(pricer); + } + + + Rate CappedFlooredYoYInflationCoupon::rate() const { + Rate swapletRate = underlying_ ? underlying_->rate() : YoYInflationCoupon::rate(); + + if(isFloored_ || isCapped_) { + if (underlying_) { + QL_REQUIRE(underlying_->pricer(), "pricer not set"); + } else { + QL_REQUIRE(pricer_, "pricer not set"); + } + } + + Rate floorletRate = 0.; + if(isFloored_) { + floorletRate = + underlying_ ? + underlying_->pricer()->floorletRate(effectiveFloor()) : + pricer()->floorletRate(effectiveFloor()) + ; + } + Rate capletRate = 0.; + if(isCapped_) { + capletRate = + underlying_ ? + underlying_->pricer()->capletRate(effectiveCap()) : + pricer()->capletRate(effectiveCap()) + ; + } + + return swapletRate + floorletRate - capletRate; + } + + + Rate CappedFlooredYoYInflationCoupon::cap() const { + if ( (gearing_ > 0) && isCapped_) + return cap_; + if ( (gearing_ < 0) && isFloored_) + return floor_; + return Null<Rate>(); + } + + + Rate CappedFlooredYoYInflationCoupon::floor() const { + if ( (gearing_ > 0) && isFloored_) + return floor_; + if ( (gearing_ < 0) && isCapped_) + return cap_; + return Null<Rate>(); + } + + + Rate CappedFlooredYoYInflationCoupon::effectiveCap() const { + return (cap_ - spread())/gearing(); + } + + + Rate CappedFlooredYoYInflationCoupon::effectiveFloor() const { + return (floor_ - spread())/gearing(); + } + + + void CappedFlooredYoYInflationCoupon::update() { + notifyObservers(); + } + + + void CappedFlooredYoYInflationCoupon::accept(AcyclicVisitor& v) { + typedef YoYInflationCoupon super; + Visitor<CappedFlooredYoYInflationCoupon>* v1 = + dynamic_cast<Visitor<CappedFlooredYoYInflationCoupon>*>(&v); + + if (v1 != 0) + v1->visit(*this); + else + super::accept(v); + } + +} + diff --git a/pool/shard007/C++/0093469_uarm_status.cpp b/pool/shard007/C++/0093469_uarm_status.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f31ff7d294c0e482c7a85dee73e81437d9953244 --- /dev/null +++ b/pool/shard007/C++/0093469_uarm_status.cpp @@ -0,0 +1,70 @@ + +/****************************************************************************************** +# File Name : uarm_core.py +# Author : Joey Song +# Version : V1.0 +# Date : 6 Jan, 2016 +# Modified Date : 6 Jan, 2016 +# Description : This documents is for uarm ROS Library and ROS package +# Copyright(C) 2016 uArm Team. All right reserved. +*******************************************************************************************/ + +#include "ros/ros.h" +#include "std_msgs/String.h" +#include <sstream> +#include <time.h> + +// Main function +int main(int argc, char **argv) +{ + // initial node + ros::init(argc, argv, "uarm_status"); + ros::NodeHandle n; + ros::Publisher execute = n.advertise<std_msgs::String>("uarm_status", 10); + + ros::Rate loop_rate(10); + + std_msgs::String msg; + int executeTrigger =0; + + // create a loop which will allow publisher publishs after set-up + while(ros::ok()){ + // check connection - if there is a subscriber + if (execute.getNumSubscribers()!=0) + { + if(executeTrigger == 0) + if (argc == 2) + { + std::string string_1 = argv[1]; + + // attach uarm + if ((string_1== "attach") || (string_1== "1") || (string_1== "ATTACH")) + { + msg.data = "attach"; + execute.publish(msg); + std::cout << "uArm: Attached uarm" << std::endl; + executeTrigger= 1; + } + // detach uarm + else if ((string_1 == "detach")|| (string_1== "0") || (string_1== "DETACH")) + { + msg.data = "detach"; + execute.publish(msg); + std::cout << "uArm: Detached uarm" << std::endl; + executeTrigger= 1; + } + // print errors + else + { + std::cout << "ERROR: Input Incorrect" << std::endl; + } + } + else + { + std::cout << "ERROR: Input detach/0 or attach/1" << std::endl; + } + sleep(0.1); + } + } + return 0; +} diff --git a/pool/shard007/C++/0093474_SneakyButton.cpp b/pool/shard007/C++/0093474_SneakyButton.cpp new file mode 100644 index 0000000000000000000000000000000000000000..27813b7378842f33401c6bb3293dc4c20b0c6e3d --- /dev/null +++ b/pool/shard007/C++/0093474_SneakyButton.cpp @@ -0,0 +1,273 @@ +/* -------------------------------------------------------------------------- + * + * File SneakyButton.cpp + * Description + * Ported By Young-Hwan Mun + * Created By Nick Pannuto on 2010/02/10 + * Contact xmsoft77@gmail.com + * + * -------------------------------------------------------------------------- + * + * Copyright (c) 2010-2013 XMSoft. + * Copyright (c) 2010-2013 cocos2d-x.org + * Copyright (c) 2010 Sneakyness, llc. All rights reserved. + * + * -------------------------------------------------------------------------- + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- */ + +#include "Precompiled.h" +#include "SneakyButton.h" + +NS_CC_BEGIN + +SneakyButton* SneakyButton::create ( const CCRect& tRect ) +{ + SneakyButton* pRet = new SneakyButton ( ); + + if ( pRet && pRet->initWithRect ( tRect ) ) + { + pRet->autorelease ( ); + } + else + { + CC_SAFE_DELETE ( pRet ); + } + + return pRet; +} + +SneakyButton* SneakyButton::create ( KDvoid ) +{ + SneakyButton* pRet = new SneakyButton ( ); + + if ( pRet && pRet->initWithRect ( CCRectZero ) ) + { + pRet->autorelease ( ); + } + else + { + CC_SAFE_DELETE ( pRet ); + } + + return pRet; +} + +KDbool SneakyButton::initWithRect ( const CCRect& tRect ) +{ + if ( !CCNode::init ( ) ) + { + return KD_FALSE; + } + + m_tBounds = CCRect ( 0, 0, tRect.size.cx, tRect.size.cy ); + m_tCenter = CCPoint ( tRect.size.cx / 2, tRect.size.cy / 2 ); + m_bStatus = KD_TRUE; + m_bActive = KD_FALSE; + m_bValue = KD_FALSE; + m_bIsHoldable = KD_FALSE; + m_bIsToggleable = KD_FALSE; + m_fRadius = 32.f; + m_fRateLimit = 1 / 120.f; + + this->setPosition ( tRect.origin ); + + return KD_TRUE; +} + +KDvoid SneakyButton::onEnterTransitionDidFinish ( KDvoid ) +{ + CCNode::onEnterTransitionDidFinish ( ); + + CCDirector::sharedDirector ( )->getTouchDispatcher ( )->addTargetedDelegate ( this, kCCMenuHandlerPriority, KD_TRUE ); +} + +KDvoid SneakyButton::onExit ( KDvoid ) +{ + CCDirector::sharedDirector ( )->getTouchDispatcher ( )->removeDelegate ( this ); + + CCNode::onExit ( ); +} + +KDvoid SneakyButton::limiter ( KDfloat fDelta ) +{ + m_bValue = 0; + this->unschedule ( schedule_selector ( SneakyButton::limiter ) ); + m_bActive = KD_FALSE; +} + +KDfloat SneakyButton::getRadius ( KDvoid ) +{ + return m_fRadius; +} + +KDvoid SneakyButton::setRadius ( KDfloat fRadius ) +{ + m_fRadius = fRadius; + m_fRadiusSq = fRadius * fRadius; +} + +KDbool SneakyButton::getStatus ( KDvoid ) +{ + return m_bStatus; +} + +KDvoid SneakyButton::setStatus ( KDbool bStatus ) +{ + m_bStatus = bStatus; +} + +KDbool SneakyButton::getValue ( KDvoid ) +{ + return m_bValue; +} + +KDbool SneakyButton::isActive ( KDvoid ) +{ + return m_bActive; +} + +KDbool SneakyButton::isHoldable ( KDvoid ) +{ + return m_bIsHoldable; +} + +KDvoid SneakyButton::setHoldable ( KDbool bIsHoldable ) +{ + m_bIsHoldable = bIsHoldable; +} + +KDbool SneakyButton::isToggleable ( KDvoid ) +{ + return m_bIsToggleable; +} + +KDvoid SneakyButton::setToggleable ( KDbool bIsToggleable ) +{ + m_bIsToggleable = bIsToggleable; +} + +KDfloat SneakyButton::getRateLimit ( KDvoid ) +{ + return m_fRateLimit; +} + +KDvoid SneakyButton::setRateLimit ( KDfloat fRateLimit ) +{ + m_fRateLimit = fRateLimit; +} + +KDbool SneakyButton::ccTouchBegan ( CCTouch* pTouch, CCEvent* pEvent ) +{ + if ( m_bActive ) + { + return KD_FALSE; + } + + CCPoint tLocation = this->convertTouchToNodeSpace ( pTouch ); + + // Do a fast rect check before doing a circle hit check: + if ( tLocation.x < -m_fRadius || tLocation.x > m_fRadius || tLocation.y < -m_fRadius || tLocation.y > m_fRadius ) + { + return KD_FALSE; + } + else + { + KDfloat fSq = tLocation.x * tLocation.x + tLocation.y * tLocation.y; + + if ( m_fRadiusSq > fSq ) + { + m_bActive = KD_TRUE; + + if ( !m_bIsHoldable && !m_bIsToggleable ) + { + m_bValue = KD_TRUE; + this->schedule ( schedule_selector ( SneakyButton::limiter ), m_fRateLimit ); + } + + if ( m_bIsHoldable ) + { + m_bValue = KD_TRUE; + } + + if ( m_bIsToggleable ) + { + m_bValue = !m_bValue; + } + + return KD_TRUE; + } + } + + return KD_FALSE; +} + +KDvoid SneakyButton::ccTouchMoved ( CCTouch* pTouch, CCEvent* pEvent ) +{ + if ( !m_bActive ) + { + return; + } + + CCPoint tLocation = this->convertTouchToNodeSpace ( pTouch ); + + // Do a fast rect check before doing a circle hit check: + if ( tLocation.x < -m_fRadius || tLocation.x > m_fRadius || tLocation.y < -m_fRadius || tLocation.y > m_fRadius ) + { + return; + } + else + { + KDfloat fSq = tLocation.x * tLocation.x + tLocation.y * tLocation.y; + if ( m_fRadiusSq > fSq ) + { + if ( m_bIsHoldable ) + { + m_bValue = KD_TRUE; + } + } + else + { + if ( m_bIsHoldable ) + { + m_bValue = KD_FALSE; + m_bActive = KD_FALSE; + } + } + } +} + +KDvoid SneakyButton::ccTouchEnded ( CCTouch* pTouch, CCEvent* pEvent ) +{ + if ( !m_bActive ) + { + return; + } + + if ( m_bIsHoldable ) + { + m_bValue = KD_FALSE; + } + + if ( m_bIsHoldable || m_bIsToggleable ) + { + m_bActive = KD_FALSE; + } +} + +NS_CC_END \ No newline at end of file diff --git a/pool/shard007/C++/0093490_Init.cpp b/pool/shard007/C++/0093490_Init.cpp new file mode 100644 index 0000000000000000000000000000000000000000..959afe8154d9ca48a45c72cc4c28c09f1bdd3fed --- /dev/null +++ b/pool/shard007/C++/0093490_Init.cpp @@ -0,0 +1,272 @@ +//***********************************************************************// +// // +// - "Talk to me like I'm a 3 year old!" Programming Lessons - // +// // +// $Author: DigiBen digiben@gametutorials.com // +// // +// $Program: Octree2 // +// // +// $Description: Intergrates frustum culling with an octree // +// // +//***********************************************************************// + + +#include "main.h" + + +///////////////////////////////// CHANGE TO FULL SCREEN \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* +///// +///// This changes the screen to FULL SCREEN +///// +///////////////////////////////// CHANGE TO FULL SCREEN \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* + +void ChangeToFullScreen() +{ + DEVMODE dmSettings; // Device Mode variable + + memset(&dmSettings,0,sizeof(dmSettings)); // Makes Sure Memory's Cleared + + // Get current settings -- This function fills in our settings. + // This makes sure NT and Win98 machines change correctly. + if(!EnumDisplaySettings(NULL,ENUM_CURRENT_SETTINGS,&dmSettings)) + { + // Display error message if we couldn't get display settings + MessageBox(NULL, "Could Not Enum Display Settings", "Error", MB_OK); + return; + } + + dmSettings.dmPelsWidth = SCREEN_WIDTH; // Selected Screen Width + dmSettings.dmPelsHeight = SCREEN_HEIGHT; // Selected Screen Height + dmSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; + + // This function actually changes the screen to full screen. + // CDS_FULLSCREEN gets rid of the start Bar. + // We always want to get a result from this function to check if we failed. + int result = ChangeDisplaySettings(&dmSettings,CDS_FULLSCREEN); + + // Check if we didn't receive a good return message From the function + if(result != DISP_CHANGE_SUCCESSFUL) + { + // Display the error message and quit the program + MessageBox(NULL, "Display Mode Not Compatible", "Error", MB_OK); + PostQuitMessage(0); + } +} + +///////////////////////////////// CREATE MY WINDOW \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* +///// +///// This function creates a window, but doesn't have a message loop +///// +///////////////////////////////// CREATE MY WINDOW \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* + +HWND CreateMyWindow(LPSTR strWindowName, int width, int height, DWORD dwStyle, bool bFullScreen, HINSTANCE hInstance) +{ + HWND hWnd; + WNDCLASS wndclass; + + memset(&wndclass, 0, sizeof(WNDCLASS)); // Init the size of the class + wndclass.style = CS_HREDRAW | CS_VREDRAW; // Regular drawing capabilities + wndclass.lpfnWndProc = WinProc; // Pass our function pointer as the window procedure + wndclass.hInstance = hInstance; // Assign our hInstance + wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); // General icon + wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); // An arrow for the cursor + wndclass.hbrBackground = (HBRUSH) (COLOR_WINDOW+1); // A white window + wndclass.lpszClassName = "GameTutorials"; // Assign the class name + + RegisterClass(&wndclass); // Register the class + + if(bFullScreen && !dwStyle) // Check if we wanted full screen mode + { // Set the window properties for full screen mode + dwStyle = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; + ChangeToFullScreen(); // Go to full screen + ShowCursor(FALSE); // Hide the cursor + } + else if(!dwStyle) // Assign styles to the window depending on the choice + dwStyle = WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; + + g_hInstance = hInstance; // Assign our global hInstance to the window's hInstance + + RECT rWindow; + rWindow.left = 0; // Set Left Value To 0 + rWindow.right = width; // Set Right Value To Requested Width + rWindow.top = 0; // Set Top Value To 0 + rWindow.bottom = height; // Set Bottom Value To Requested Height + + AdjustWindowRect( &rWindow, dwStyle, false); // Adjust Window To True Requested Size + + // Create the window + hWnd = CreateWindow("GameTutorials", strWindowName, dwStyle, 0, 0, + rWindow.right - rWindow.left, rWindow.bottom - rWindow.top, + NULL, NULL, hInstance, NULL); + + if(!hWnd) return NULL; // If we could get a handle, return NULL + + ShowWindow(hWnd, SW_SHOWNORMAL); // Show the window + UpdateWindow(hWnd); // Draw the window + + SetFocus(hWnd); // Sets Keyboard Focus To The Window + + return hWnd; +} + +///////////////////////////////// SET UP PIXEL FORMAT \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* +///// +///// This function sets the pixel format for OpenGL. +///// +///////////////////////////////// SET UP PIXEL FORMAT \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* + +bool bSetupPixelFormat(HDC hdc) +{ + PIXELFORMATDESCRIPTOR pfd; + int pixelformat; + + pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); // Set the size of the structure + pfd.nVersion = 1; // Always set this to 1 + // Pass in the appropriate OpenGL flags + pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; + pfd.dwLayerMask = PFD_MAIN_PLANE; // We want the standard mask (this is ignored anyway) + pfd.iPixelType = PFD_TYPE_RGBA; // We want RGB and Alpha pixel type + pfd.cColorBits = SCREEN_DEPTH; // Here we use our #define for the color bits + pfd.cDepthBits = SCREEN_DEPTH; // Depthbits is ignored for RGBA, but we do it anyway + pfd.cAccumBits = 0; // No special bitplanes needed + pfd.cStencilBits = 0; // We desire no stencil bits + + // This gets us a pixel format that best matches the one passed in from the device + if ( (pixelformat = ChoosePixelFormat(hdc, &pfd)) == FALSE ) + { + MessageBox(NULL, "ChoosePixelFormat failed", "Error", MB_OK); + return FALSE; + } + + // This sets the pixel format that we extracted from above + if (SetPixelFormat(hdc, pixelformat, &pfd) == FALSE) + { + MessageBox(NULL, "SetPixelFormat failed", "Error", MB_OK); + return FALSE; + } + + return TRUE; // Return a success! +} + +//////////////////////////// RESIZE OPENGL SCREEN \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* +///// +///// This function resizes the viewport for OpenGL. +///// +//////////////////////////// RESIZE OPENGL SCREEN \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* +void SizeOpenGLScreen(int width, int height) // Initialize The GL Window +{ + if (height==0) // Prevent A Divide By Zero error + { + height=1; // Make the Height Equal One + } + + glViewport(0,0,width,height); // Make our viewport the whole window + // We could make the view smaller inside + // Our window if we wanted too. + // The glViewport takes (x, y, width, height) + // This basically means, what are our drawing boundaries + + glMatrixMode(GL_PROJECTION); // Select The Projection Matrix + glLoadIdentity(); // Reset The Projection Matrix + + // Calculate The Aspect Ratio Of The Window + // The parameters are: + // (view angle, aspect ration of the width to the height, + // the closest distance to the camera before it clips, + // FOV // Ratio // the farthest distance before it stops drawing). + gluPerspective(45.0f,(GLfloat)width/(GLfloat)height, 1.0f, 1000.0f); + + glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix + glLoadIdentity(); // Reset The Modelview Matrix +} + +///////////////////////////////// INITIALIZE GL \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* +///// +///// This function handles all the initialization for OpenGL. +///// +///////////////////////////////// INITIALIZE GL \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* + +void InitializeOpenGL(int width, int height) +{ + g_hDC = GetDC(g_hWnd); // This sets our global HDC + // We don't free this hdc until the end of our program + if (!bSetupPixelFormat(g_hDC)) // This sets our pixel format/information + PostQuitMessage (0); // If there's an error, quit + + g_hRC = wglCreateContext(g_hDC); // This creates a rendering context from our hdc + wglMakeCurrent(g_hDC, g_hRC); // This makes the rendering context we just created the one we want to use + + glEnable(GL_DEPTH_TEST); // Enables Depth Testing + + SizeOpenGLScreen(width, height); // Setup the screen translations and viewport +} + +///////////////////////////////// DE INIT \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* +///// +///// This function cleans up and then posts a quit message to the window +///// +///////////////////////////////// DE INIT \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* + +void DeInit() +{ + if (g_hRC) + { + wglMakeCurrent(NULL, NULL); // This frees our rendering memory and sets everything back to normal + wglDeleteContext(g_hRC); // Delete our OpenGL Rendering Context + } + + if (g_hDC) + ReleaseDC(g_hWnd, g_hDC); // Release our HDC from memory + + if(g_bFullScreen) // If we were in full screen + { + ChangeDisplaySettings(NULL,0); // If So Switch Back To The Desktop + ShowCursor(TRUE); // Show Mouse Pointer + } + + UnregisterClass("GameTutorials", g_hInstance); // Free the window class + + PostQuitMessage (0); // Post a QUIT message to the window +} + + +///////////////////////////////// WIN MAIN \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* +///// +///// This function handles registering and creating the window. +///// +///////////////////////////////// WIN MAIN \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* + +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hprev, PSTR cmdline, int ishow) +{ + HWND hWnd; + + // Check if we want full screen or not + if(MessageBox(NULL, "Click Yes to go to full screen (Recommended)", "Options", MB_YESNO | MB_ICONQUESTION) == IDNO) + g_bFullScreen = false; + + // Create our window with our function we create that passes in the: + // name, width, height, any flags for the window, if we want fullscreen of not, and the hInstance. + hWnd = CreateMyWindow("www.GameTutorials.com - Octree With Frustum Culling", SCREEN_WIDTH, SCREEN_HEIGHT, 0, g_bFullScreen, hInstance); + + // If we never got a valid window handle, quit the program + if(hWnd == NULL) return true; + + // INIT OpenGL + Init(hWnd); + + // Run our message loop and after it's done, return the result + return MainLoop(); +} + + +///////////////////////////////////////////////////////////////////////////////// +// +// * QUICK NOTES * +// +// Nothing was added to our initialization to deal with creating an octree. +// +// +// Ben Humphrey (DigiBen) +// Game Programmer +// DigiBen@GameTutorials.com +// ©2000-2005 GameTutorials diff --git a/pool/shard007/C++/0093499_RecConfigParse.cc b/pool/shard007/C++/0093499_RecConfigParse.cc new file mode 100644 index 0000000000000000000000000000000000000000..1d84416a81ba5b001476008c71b4b017b4a2bae2 --- /dev/null +++ b/pool/shard007/C++/0093499_RecConfigParse.cc @@ -0,0 +1,285 @@ +/** @file + + Parse the records.config configuration file. + + @section license License + + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#include "tscore/ink_platform.h" +#include "tscore/ink_memory.h" + +#include "tscore/TextBuffer.h" +#include "tscore/Tokenizer.h" +#include "tscore/ink_defs.h" +#include "tscore/ink_string.h" +#include "tscore/runroot.h" + +#include "P_RecFile.h" +#include "P_RecUtils.h" +#include "P_RecMessage.h" +#include "P_RecCore.h" +#include "tscore/I_Layout.h" + +const char *g_rec_config_fpath = nullptr; +LLQ *g_rec_config_contents_llq = nullptr; +std::unordered_set<std::string> g_rec_config_contents_ht; +ink_mutex g_rec_config_lock; + +//------------------------------------------------------------------------- +// RecConfigFileInit +//------------------------------------------------------------------------- +void +RecConfigFileInit() +{ + ink_mutex_init(&g_rec_config_lock); + g_rec_config_contents_llq = create_queue(); +} + +//------------------------------------------------------------------------- +// RecFileImport_Xmalloc +//------------------------------------------------------------------------- +static int +RecFileImport_Xmalloc(const char *file, char **file_buf, int *file_size) +{ + int err = REC_ERR_FAIL; + RecHandle h_file; + int bytes_read; + + if (file && file_buf && file_size) { + *file_buf = nullptr; + *file_size = 0; + if ((h_file = RecFileOpenR(file)) != REC_HANDLE_INVALID) { + *file_size = RecFileGetSize(h_file); + *file_buf = (char *)ats_malloc(*file_size + 1); + if (RecFileRead(h_file, *file_buf, *file_size, &bytes_read) != REC_ERR_FAIL && bytes_read == *file_size) { + (*file_buf)[*file_size] = '\0'; + err = REC_ERR_OKAY; + } else { + ats_free(*file_buf); + *file_buf = nullptr; + *file_size = 0; + } + RecFileClose(h_file); + } + } + + return err; +} + +//------------------------------------------------------------------------- +// RecConfigOverrideFromRunroot +//------------------------------------------------------------------------- +bool +RecConfigOverrideFromRunroot(const char *name) +{ + if (!get_runroot().empty()) { + if (!strcmp(name, "proxy.config.bin_path") || !strcmp(name, "proxy.config.local_state_dir") || + !strcmp(name, "proxy.config.log.logfile_dir") || !strcmp(name, "proxy.config.plugin.plugin_dir") || + !strcmp(name, "proxy.config.hostdb.storage_path")) { + return true; + } + } + return false; +} + +//------------------------------------------------------------------------- +// RecConfigOverrideFromEnvironment +//------------------------------------------------------------------------- +const char * +RecConfigOverrideFromEnvironment(const char *name, const char *value) +{ + ats_scoped_str envname(ats_strdup(name)); + const char *envval = nullptr; + + // Munge foo.bar.config into FOO_BAR_CONFIG. + for (char *c = envname; *c != '\0'; ++c) { + switch (*c) { + case '.': + *c = '_'; + break; + default: + *c = ParseRules::ink_toupper(*c); + break; + } + } + + envval = getenv((const char *)envname); + if (envval) { + return envval; + } else if (RecConfigOverrideFromRunroot(name)) { + return nullptr; + } + + return value; +} + +//------------------------------------------------------------------------- +// RecParseConfigFile +//------------------------------------------------------------------------- +int +RecConfigFileParse(const char *path, RecConfigEntryCallback handler) +{ + char *fbuf; + int fsize; + + const char *line; + int line_num; + + char *rec_type_str, *name_str, *data_type_str, *data_str; + const char *value_str; + RecT rec_type; + RecDataT data_type; + + Tokenizer line_tok("\r\n"); + tok_iter_state line_tok_state; + + RecConfigFileEntry *cfe; + + RecDebug(DL_Note, "Reading '%s'", path); + + // watch out, we're altering our g_rec_config_xxx structures + ink_mutex_acquire(&g_rec_config_lock); + + if (RecFileImport_Xmalloc(path, &fbuf, &fsize) == REC_ERR_FAIL) { + RecLog(DL_Warning, "Could not import '%s'", path); + ink_mutex_release(&g_rec_config_lock); + return REC_ERR_FAIL; + } + // clear our g_rec_config_contents_xxx structures + while (!queue_is_empty(g_rec_config_contents_llq)) { + cfe = (RecConfigFileEntry *)dequeue(g_rec_config_contents_llq); + ats_free(cfe->entry); + ats_free(cfe); + } + + line_tok.Initialize(fbuf, SHARE_TOKS | ALLOW_EMPTY_TOKS); + line = line_tok.iterFirst(&line_tok_state); + line_num = 1; + while (line) { + char *lc = ats_strdup(line); + char *lt = lc; + char *ln; + + while (isspace(*lt)) { + lt++; + } + rec_type_str = strtok_r(lt, " \t", &ln); + + // check for blank lines and comments + if ((!rec_type_str) || (rec_type_str && (*rec_type_str == '#'))) { + goto L_next_line; + } + + name_str = strtok_r(nullptr, " \t", &ln); + data_type_str = strtok_r(nullptr, " \t", &ln); + + // extract the string data (a little bit tricker since it can have spaces) + if (ln) { + // 'ln' will point to either the next token or a bunch of spaces + // if the user didn't supply a value (e.g. 'STRING '). First + // scan past all of the spaces. If we hit a '\0', then we we + // know we didn't have a valid value. If not, set 'data_str' to + // the start of the token and scan until we find the end. Once + // the end is found, back-peddle to remove any trailing spaces. + while (isspace(*ln)) { + ln++; + } + if (*ln == '\0') { + data_str = nullptr; + } else { + data_str = ln; + while (*ln != '\0') { + ln++; + } + ln--; + while (isspace(*ln) && (ln > data_str)) { + ln--; + } + ln++; + *ln = '\0'; + } + } else { + data_str = nullptr; + } + + // check for errors + if (!(rec_type_str && name_str && data_type_str && data_str)) { + RecLog(DL_Warning, "Could not parse line at '%s:%d' -- skipping line: '%s'", path, line_num, line); + goto L_next_line; + } + + // record type + if (strcmp(rec_type_str, "CONFIG") == 0) { + rec_type = RECT_CONFIG; + } else if (strcmp(rec_type_str, "PROCESS") == 0) { + rec_type = RECT_PROCESS; + } else if (strcmp(rec_type_str, "NODE") == 0) { + rec_type = RECT_NODE; + } else if (strcmp(rec_type_str, "LOCAL") == 0) { + rec_type = RECT_LOCAL; + } else { + RecLog(DL_Warning, "Unknown record type '%s' at '%s:%d' -- skipping line", rec_type_str, path, line_num); + goto L_next_line; + } + + // data_type + if (strcmp(data_type_str, "INT") == 0) { + data_type = RECD_INT; + } else if (strcmp(data_type_str, "FLOAT") == 0) { + data_type = RECD_FLOAT; + } else if (strcmp(data_type_str, "STRING") == 0) { + data_type = RECD_STRING; + } else if (strcmp(data_type_str, "COUNTER") == 0) { + data_type = RECD_COUNTER; + } else { + RecLog(DL_Warning, "Unknown data type '%s' at '%s:%d' -- skipping line", data_type_str, path, line_num); + goto L_next_line; + } + + // OK, we parsed the record, send it to the handler ... + value_str = RecConfigOverrideFromEnvironment(name_str, data_str); + handler(rec_type, data_type, name_str, value_str, value_str == data_str ? REC_SOURCE_EXPLICIT : REC_SOURCE_ENV); + + // update our g_rec_config_contents_xxx + cfe = (RecConfigFileEntry *)ats_malloc(sizeof(RecConfigFileEntry)); + cfe->entry_type = RECE_RECORD; + cfe->entry = ats_strdup(name_str); + enqueue(g_rec_config_contents_llq, (void *)cfe); + g_rec_config_contents_ht.emplace(name_str); + goto L_done; + + L_next_line: + // store this line into g_rec_config_contents_llq so that we can + // write it out later + cfe = (RecConfigFileEntry *)ats_malloc(sizeof(RecConfigFileEntry)); + cfe->entry_type = RECE_COMMENT; + cfe->entry = ats_strdup(line); + enqueue(g_rec_config_contents_llq, (void *)cfe); + + L_done: + line = line_tok.iterNext(&line_tok_state); + line_num++; + ats_free(lc); + } + + ink_mutex_release(&g_rec_config_lock); + ats_free(fbuf); + + return REC_ERR_OKAY; +} diff --git a/pool/shard007/C++/0093500_UniquePathsII.cpp b/pool/shard007/C++/0093500_UniquePathsII.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aa1b598c312dd3daf6fe571a7ccc20e90bebcd37 --- /dev/null +++ b/pool/shard007/C++/0093500_UniquePathsII.cpp @@ -0,0 +1,74 @@ +/* +Follow up for "Unique Paths": + +Now consider if some obstacles are added to the grids. How many unique paths would there be? + +An obstacle and empty space is marked as 1 and 0 respectively in the grid. + +For example, +There is one obstacle in the middle of a 3x3 grid as illustrated below. + +[ + [0,0,0], + [0,1,0], + [0,0,0] +] +The total number of unique paths is 2. + +Note: m and n will be at most 100. +*/ + +#include <vector> +#include <stdio.h> + +using namespace std; + +class Solution +{ +public: + // DP solution, matrix[i][j] = matrix[i - 1][j] + matrix[i][j - 1] + int uniquePathsWithObstacles(vector<vector<int> >& obstacle_grid) + { + if (obstacle_grid.empty()) + { + return 0; + } + int row = obstacle_grid.size(); + int column = obstacle_grid[0].size(); + vector<int> line(column, 0); + vector<vector<int> > matrix(row, line); + for (int i = 0; i < column && obstacle_grid[0][i] != 1; ++i) + { + matrix[0][i] = 1; + } + for (int i = 0; i < row && obstacle_grid[i][0] != 1; ++i) + { + matrix[i][0] = 1; + } + for (int i = 1; i < row; ++i) + { + for (int j = 1; j < column; ++j) + { + if (obstacle_grid[i][j] == 1) + { + continue; + } + matrix[i][j] = matrix[i - 1][j] + matrix[i][j - 1]; + } + } + return matrix[row - 1][column - 1]; + } +}; + +int main(int argc, char* argv[]) +{ + Solution s; + vector<vector<int> > grid = + { + {0,0,0}, + {0,1,0}, + {0,0,0}, + }; + printf("%d\n", s.uniquePathsWithObstacles(grid)); + return 0; +} diff --git a/pool/shard007/C++/0093504_mclTest.cpp b/pool/shard007/C++/0093504_mclTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4e3e795bf3e87e03b74b18f1ddac961b8c8455a2 --- /dev/null +++ b/pool/shard007/C++/0093504_mclTest.cpp @@ -0,0 +1,34 @@ +#include <vector> +#include <iostream> +using namespace std; + +#include "Observation.h" +#include "MCL.h" + +int main() +{ + // Testing the observation class stuff + vector<Observation> obs; + VisualLine* vl1 = new VisualLine(); + VisualLine* vl2 = new VisualLine(); + VisualCorner vc(100, 200, 200.0f, + 50.0f, *vl1, *vl2, 200.1f, 300.0f); + FieldObjects* fo = new FieldObjects(YELLOW_GOAL_RIGHT_POST); + (*fo).setX(1000); + (*fo).setY(200); + obs.push_back(*(new Observation(vc))); + obs.push_back(*(new Observation(*vl1))); + obs.push_back(*(new Observation(*vl2))); + obs.push_back(*(new Observation(*fo))); + + + MCL* myLoc = new MCL(); + + for(unsigned short i = 0; i < obs.size(); ++i) { + cout << "(" << obs[i].getVisDist() << ", " << obs[i].getVisBearing() << ")" + << endl; + } + + // // Clean everything up + delete vl1, vl2, fo; +} diff --git a/pool/shard007/C++/0093505_CRegisteredCommands.cpp b/pool/shard007/C++/0093505_CRegisteredCommands.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2bfc2f18eb8ff2a8d06a3c97c7d624a99bd3ed3a --- /dev/null +++ b/pool/shard007/C++/0093505_CRegisteredCommands.cpp @@ -0,0 +1,223 @@ +/***************************************************************************** +* +* PROJECT: Multi Theft Auto v1.0 +* LICENSE: See LICENSE in the top level directory +* FILE: mods/deathmatch/logic/CRegisteredCommands.cpp +* PURPOSE: Registered commands manager +* DEVELOPERS: Kevin Whiteside <kevuwk@gmail.com> +* Derek Abdine <...> +* +* Multi Theft Auto is available from http://www.multitheftauto.com/ +* +*****************************************************************************/ + +#include "stdinc.h" +#include "CRegisteredCommands.h" +//#include "CPlayer.h" +//#include "CAdmin.h" +//#include "CConsoleClient.h" +#include "lua/CLuaMain.h" +#include <assert.h> + +bool CRegisteredCommands::AddCommand ( CLuaMain* pLuaMain, const char* szKey, const char* szHandler ) +{ + assert ( pLuaMain ); + assert ( szKey ); + assert ( szHandler ); + + // Check if we already have this key and handler + SCommand* pCommand = GetCommand ( szKey, pLuaMain ); + if ( pCommand && !strcmp ( pCommand->szHandler, szHandler ) + return false; + + // Create the entry + pCommand = new SCommand; + pCommand->pLuaMain = pLuaMain; + strncpy ( pCommand->szKey, szKey, MAX_REGISTERED_COMMAND_LENGTH ); + pCommand->szKey [MAX_REGISTERED_COMMAND_LENGTH] = 0; + strncpy ( pCommand->szHandler, szHandler, MAX_REGISTERED_COMMANDHANDLER_LENGTH ); + pCommand->szHandler [MAX_REGISTERED_COMMANDHANDLER_LENGTH] = 0; + + // Add it to our list + m_Commands.push_back ( pCommand ); + return true; +} + + +bool CRegisteredCommands::RemoveCommand ( CLuaMain* pLuaMain, const char* szKey ) +{ + assert ( pLuaMain ); + assert ( szKey ); + + // Call the handler for every virtual machine that matches the given key + bool bFound = false; + list < SCommand* > ::iterator iter = m_Commands.begin (); + while ( iter != m_Commands.end () ) + { + // Matching vm's and names? + if ( (*iter)->pLuaMain == pLuaMain && strcmp ( (*iter)->szKey, szKey ) == 0 ) + { + // Delete it and remove it from our list + delete *iter; + m_Commands.erase ( iter ); + iter = m_Commands.begin (); + bFound = true; + continue; + } + iter++; + } + + return bFound; +} + + +void CRegisteredCommands::ClearCommands ( void ) +{ + // Delete all the commands + list < SCommand* > ::const_iterator iter = m_Commands.begin (); + for ( ; iter != m_Commands.end (); iter++ ) + { + delete *iter; + } + + // Clear the list + m_Commands.clear (); +} + + +void CRegisteredCommands::CleanUpForVM ( CLuaMain* pLuaMain ) +{ + assert ( pLuaMain ); + + // Delete every command that matches + list < SCommand* > ::iterator iter = m_Commands.begin (); + for ( ; iter != m_Commands.end (); ) + { + // Matching VM's? + if ( (*iter)->pLuaMain == pLuaMain ) + { + // Delete the entry and remove it from the list + delete *iter; + iter = m_Commands.erase ( iter ); + } + else + { + ++iter; + } + } +} + + +bool CRegisteredCommands::CommandExists ( const char* szKey, CLuaMain* pLuaMain ) +{ + assert ( szKey ); + + return GetCommand ( szKey, pLuaMain ) != NULL; +} + + +bool CRegisteredCommands::ProcessCommand ( const char* szKey, const char* szArguments, CClient* pClient ) +{ + assert ( szKey ); + + // Call the handler for every virtual machine that matches the given key + list < SCommand* > ::const_iterator iter = m_Commands.begin (); + for ( ; iter != m_Commands.end (); iter++ ) + { + // Matching names? + if ( strcmp ( (*iter)->szKey, szKey ) == 0 ) + { + // Call it + CallCommandHandler ( (*iter)->pLuaMain, (*iter)->szHandler, szKey, szArguments, pClient ); + return true; + } + } + + // Return whether some handler was called or not + return false; +} + + +CRegisteredCommands::SCommand* CRegisteredCommands::GetCommand ( const char* szKey, class CLuaMain* pLuaMain ) +{ + assert ( szKey ); + + // Try to find an entry with a matching name in our list + list < SCommand* > ::const_iterator iter = m_Commands.begin (); + for ( ; iter != m_Commands.end (); iter++ ) + { + // Matching name and no given VM or matching VM + if ( strcmp ( (*iter)->szKey, szKey ) == 0 && ( !pLuaMain || pLuaMain == (*iter)->pLuaMain ) ) + { + return *iter; + } + } + + // Doesn't exist + return NULL; +} + + +void CRegisteredCommands::CallCommandHandler ( CLuaMain* pLuaMain, const char* szHandler, const char* szKey, const char* szArguments, CClient* pClient ) +{ + assert ( pLuaMain ); + assert ( szHandler ); + assert ( szKey ); + + CLuaArguments Arguments; + // First, try to call a handler with the same number of arguments + if ( pClient ) + { + /*switch ( pClient->GetClientType () ) + { + case CClient::CLIENT_PLAYER: + { + Arguments.PushUserData ( static_cast < CPlayer* > ( pClient ) ); + break; + } + case CClient::CLIENT_REMOTECLIENT: + { + Arguments.PushUserData ( static_cast < CAdmin* > ( pClient ) ); + break; + } + case CClient::CLIENT_CONSOLE: + { + Arguments.PushUserData ( static_cast < CConsoleClient* > ( pClient ) ); + break; + } + default: + { + Arguments.PushBoolean ( false ); + break; + } + }*/ + } + else + { + Arguments.PushBoolean ( false ); + } + + Arguments.PushString ( szKey ); + + if ( szArguments ) + { + // Create a copy and strtok modifies the string + char * szTempArguments = new char[strlen(szArguments) + 1]; + strcpy ( szTempArguments, szArguments ); + char * arg; + arg = strtok ( szTempArguments, " " ); + while ( arg ) + { + Arguments.PushString ( arg ); + arg = strtok ( NULL, " " ); + } + delete [] szTempArguments; + } + else + { + Arguments.PushBoolean ( false ); + } + + // Call the handler with the arguments we pushed + Arguments.Call ( pLuaMain, szHandler ); +} diff --git a/pool/shard007/C++/0093516_SynthNote.cpp b/pool/shard007/C++/0093516_SynthNote.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ecced6b7350ee7e3d96d347acf6b04467e3d77f --- /dev/null +++ b/pool/shard007/C++/0093516_SynthNote.cpp @@ -0,0 +1,140 @@ +/* + File: SynthNote.cpp + Abstract: SynthNote.h + Version: 1.1 + + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple + Inc. ("Apple") in consideration of your agreement to the following + terms, and your use, installation, modification or redistribution of + this Apple software constitutes acceptance of these terms. If you do + not agree with these terms, please do not use, install, modify or + redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and + subject to these terms, Apple grants you a personal, non-exclusive + license, under Apple's copyrights in this original Apple software (the + "Apple Software"), to use, reproduce, modify and redistribute the Apple + Software, with or without modifications, in source and/or binary forms; + provided that if you redistribute the Apple Software in its entirety and + without modifications, you must retain this notice and the following + text and disclaimers in all such redistributions of the Apple Software. + Neither the name, trademarks, service marks or logos of Apple Inc. may + be used to endorse or promote products derived from the Apple Software + without specific prior written permission from Apple. Except as + expressly stated in this notice, no other rights or licenses, express or + implied, are granted by Apple herein, including but not limited to any + patent rights that may be infringed by your derivative works or by other + works in which the Apple Software may be incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE + MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND + OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, + MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED + AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), + STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + + Copyright (C) 2014 Apple Inc. All Rights Reserved. + +*/ +#include "SynthNote.h" +#include "SynthElement.h" +#include "AUInstrumentBase.h" + +bool SynthNote::AttackNote( + SynthPartElement * inPart, + SynthGroupElement * inGroup, + NoteInstanceID inNoteID, + UInt64 inAbsoluteSampleFrame, + UInt32 inOffsetSampleFrame, + const MusicDeviceNoteParams &inParams) +{ +#if DEBUG_PRINT + printf("SynthNote::AttackNote %lu %lu abs frame %llu rel frame %lu\n", (UInt32)inGroup->GroupID(), (UInt32)inNoteID, inAbsoluteSampleFrame, inOffsetSampleFrame); +#endif + mPart = inPart; + mGroup = inGroup; + mNoteID = inNoteID; + + mAbsoluteStartFrame = inAbsoluteSampleFrame; + mRelativeStartFrame = inOffsetSampleFrame; + mRelativeReleaseFrame = -1; + mRelativeKillFrame = -1; + + mPitch = inParams.mPitch; + mVelocity = inParams.mVelocity; + + + return Attack(inParams); +} + + +void SynthNote::Reset() +{ + mPart = 0; + mGroup = 0; + mAbsoluteStartFrame = 0; + mRelativeStartFrame = 0; + mRelativeReleaseFrame = 0; + mRelativeKillFrame = 0; +} + +void SynthNote::Kill(UInt32 inFrame) +{ + mRelativeKillFrame = inFrame; +} + +void SynthNote::Release(UInt32 inFrame) +{ + mRelativeReleaseFrame = inFrame; +} + +void SynthNote::FastRelease(UInt32 inFrame) +{ + mRelativeReleaseFrame = inFrame; +} + +double SynthNote::TuningA() const +{ + return 440.0; +} + +double SynthNote::Frequency() +{ + return TuningA() * pow(2., (mPitch - 69. + GetPitchBend()) / 12.); +} + +double SynthNote::SampleRate() +{ + return GetAudioUnit()->GetOutput(0)->GetStreamFormat().mSampleRate; +} + +AUInstrumentBase* SynthNote::GetAudioUnit() const +{ + return (AUInstrumentBase*)mGroup->GetAudioUnit(); +} + +Float32 SynthNote::GetGlobalParameter(AudioUnitParameterID inParamID) const +{ + return mGroup->GetAudioUnit()->Globals()->GetParameter(inParamID); +} + +void SynthNote::NoteEnded(UInt32 inFrame) +{ + mGroup->NoteEnded(this, inFrame); + mNoteID = 0xFFFFFFFF; +} + +float SynthNote::GetPitchBend() const +{ + return mGroup->GetPitchBend(); +} + + diff --git a/pool/shard007/C++/0093517_LanguageTab.cpp b/pool/shard007/C++/0093517_LanguageTab.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a50d611c8588a96cc965b217b755fe8e171458c2 --- /dev/null +++ b/pool/shard007/C++/0093517_LanguageTab.cpp @@ -0,0 +1,93 @@ +/* This file is part of the KDE project + Copyright (C) 2001, 2002 Montel Laurent <lmontel@mandrakesoft.com> + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. +*/ + +#include "LanguageTab.h" +#include "KoGlobal.h" + +#include <KoCharacterStyle.h> + +#include <kcombobox.h> +#include <kiconloader.h> + +#include <QSet> +#include <QStringList> + +#include <LanguageTab.moc> + +LanguageTab::LanguageTab(/*KSpell2::Loader::Ptr loader,*/bool uniqueFormat, QWidget* parent, Qt::WFlags fl) + : QWidget(parent), + m_uniqueFormat(uniqueFormat) +{ + widget.setupUi(this); + + Q_UNUSED(fl); + + widget.languageListSearchLine->setListWidget(widget.languageList); + + //TODO use fl + const QStringList langNames = KoGlobal::listOfLanguages(); + const QStringList langTags = KoGlobal::listOfLanguageTags(); + QSet<QString> spellCheckLanguages; + + widget.languageList->addItem(QString("None")); +#if 0 //Port it + if (loader) + spellCheckLanguages = QSet<QString>::fromList(loader->languages()); +#endif + QStringList::ConstIterator itName = langNames.begin(); + QStringList::ConstIterator itTag = langTags.begin(); + for (; itName != langNames.end() && itTag != langTags.end(); ++itName, ++itTag) { + if (spellCheckLanguages.contains(*itTag)) { + QListWidgetItem* item = new QListWidgetItem(); + item->setText(*itName); + item->setIcon(SmallIcon("tools-check-spelling")); + + widget.languageList->addItem(item); + } else + widget.languageList->addItem(*itName); + } + connect(widget.languageList, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), + this, SIGNAL(languageChanged())); +} + +LanguageTab::~LanguageTab() +{ +} + +void LanguageTab::save(KoCharacterStyle* style) const +{ + if (!widget.languageList->currentItem() || widget.languageList->currentItem()->text() == "None") //TODO i18n + style->setLanguage(QString()); + else + style->setLanguage(KoGlobal::tagOfLanguage(widget.languageList->currentItem()->text())); +} + +void LanguageTab::setDisplay(KoCharacterStyle *style) +{ + if (m_uniqueFormat) { + const QString& name = KoGlobal::languageFromTag(style->language()); + + QList<QListWidgetItem*> items = widget.languageList->findItems(name, + Qt::MatchFixedString); + if (!items.isEmpty()) { + widget.languageList->setCurrentItem(items.first()); + widget.languageList->scrollToItem(items.first()); + } + } +} diff --git a/pool/shard007/C++/0093521_39._Combination_Sum.cpp b/pool/shard007/C++/0093521_39._Combination_Sum.cpp new file mode 100644 index 0000000000000000000000000000000000000000..998f51f42d8c0eefbb2e2f029bd296b9a43c36ce --- /dev/null +++ b/pool/shard007/C++/0093521_39._Combination_Sum.cpp @@ -0,0 +1,80 @@ +// +// 39. Combination Sum.cpp +// leetcode +// +// Created by Yuebin Yang on 2017/2/3. +// Copyright © 2017年 yuebin. All rights reserved. +// +// Question: + //Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. + // + //The same repeated number may be chosen from C unlimited number of times. + // + //Note: + //All numbers (including target) will be positive integers. + //The solution set must not contain duplicate combinations. + //For example, given candidate set [2, 3, 6, 7] and target 7, + //A solution set is: + //[7], + //[2, 2, 3] + +// idea: because every element maybe used for more than one time. I use recursion to find out all the possible solutions. + +#include <iostream> +#include <stdio.h> +#include <vector> +#include <algorithm> +using namespace std; + + +class Solution { +public: + vector<vector<int>> combinationSum(vector<int>& candidates, int target) { + vector<int> path; + vector<vector<int>>result; + int len=candidates.size(); + sort(candidates.begin(),candidates.end()); + DFS(candidates,path,0,target,result); + + return result; + }// combinationSum + +private: + void DFS(vector<int>& candidates,vector<int>& path,int start,int target,vector<vector<int>>& result) + { + if(target==0) + { + result.push_back(path); + return; + } + for(int i=start;i<candidates.size();i++) + { + if(candidates[i]>target) + return; + path.push_back(candidates[i]); + DFS(candidates, path, i, target-candidates[i], result); + path.pop_back(); + } + }// DFS +}; + + +int main(){ + Solution solution; + int target = 12; + vector<int> vec; + vec.push_back(2); + vec.push_back(4); + //vec.push_back(); + vec.push_back(8); + + vector<vector<int> > result = solution.combinationSum(vec,target); + // 输出 + for(int i = 0;i < result.size();++i){ + for(int j = 0;j < result[i].size();++j){ + cout<<result[i][j]<<" "; + } + cout<<endl; + } + return 0; +} diff --git a/pool/shard007/C++/0093523_RoZlib.cpp b/pool/shard007/C++/0093523_RoZlib.cpp new file mode 100644 index 0000000000000000000000000000000000000000..195711d4522d07809c11c63c3cf72d406dc62595 --- /dev/null +++ b/pool/shard007/C++/0093523_RoZlib.cpp @@ -0,0 +1,96 @@ +#include "RoZlib.h" + +#include <zlib.h> + +#include <core/RoException.h> +#include <core/RoErrorInfo.h> + +RoErrorInfoDetail GetZlibErrorDetail(int errorCode) +{ + switch (errorCode) { + case Z_STREAM_END: + return RoErrorInfoDetail("Reached end of stream."); + break; + case Z_NEED_DICT: + return RoErrorInfoDetail("Need dict(?)"); + break; + case Z_ERRNO: + return RoErrorInfoDetail("ERRNO."); + break; + case Z_STREAM_ERROR: + return RoErrorInfoDetail("Stream error."); + break; + case Z_DATA_ERROR: + return RoErrorInfoDetail("Source data error."); + break; + case Z_MEM_ERROR: + return RoErrorInfoDetail("Memory Error."); + break; + case Z_BUF_ERROR: + return RoErrorInfoDetail("Unclear buffer error."); + break; + case Z_VERSION_ERROR: + return RoErrorInfoDetail("Incompatible zlib version."); + break; + default: + break; + } + return RoErrorInfoDetail("Unknown zlib error."); +} + +void RoZlib::Uncompress(RoCharArray& destination, const size_t uncompressedSize, const RoCharArray& source) +{ + RoCharArray uncompressed(uncompressedSize, 0); + uLong resultingUncompressedSize = static_cast<uLong>(uncompressedSize); + + int result = uncompress( + (Bytef*) &uncompressed[0], + &resultingUncompressedSize, + (const Bytef*) &source[0], + static_cast<uLong>(source.size())); + + if (Z_OK != result) { + roTHROW(RoException("ZlibException") + << GetZlibErrorDetail(result)); + } else if (uncompressedSize != resultingUncompressedSize) { + roTHROW(RoException("ZlibException") + << RoErrorInfoDetail("The resulting uncompressed size doesn't match the expected uncompressed size.")); + } + + destination.swap(uncompressed); +} + +void RoZlib::UncompressInline(RoCharArray& buffer, const size_t compressedSize) +{ + const size_t uncompressedSize = buffer.size(); + RoCharArray uncompressed(uncompressedSize, 0); + uLong resultingUncompressedSize = static_cast<uLong>(uncompressedSize); + int result = uncompress( + (Bytef*)&uncompressed[0], + &resultingUncompressedSize, + (const Bytef*)&buffer[0], + static_cast<uLong>(compressedSize)); + + if (Z_OK != result) { + roTHROW(RoException("ZlibException") + << GetZlibErrorDetail(result)); + } else if (uncompressedSize != resultingUncompressedSize) { + roTHROW(RoException("ZlibException") + << RoErrorInfoDetail("The resulting uncompressed size doesn't match the expected uncompressed size.")); + } +#if roPLATFORM_IS_WIN32 + memcpy_s(&buffer[0], buffer.size(), &uncompressed[0], uncompressedSize); +#else + memcpy(&buffer[0], &uncompressed[0], uncompressedSize); +#endif // roPLATFORM_IS_WIN32 +} + + +RoZlib::RoZlib(void) +{ +} + + +RoZlib::~RoZlib(void) +{ +} diff --git a/pool/shard007/C++/0093526_quic_spdy_session.cc b/pool/shard007/C++/0093526_quic_spdy_session.cc new file mode 100644 index 0000000000000000000000000000000000000000..0a8dda6929e139c0c6542f580b91c6d254095d39 --- /dev/null +++ b/pool/shard007/C++/0093526_quic_spdy_session.cc @@ -0,0 +1,80 @@ +// Copyright (c) 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. + +#include "net/quic/quic_spdy_session.h" + +#include "net/quic/quic_headers_stream.h" + +namespace net { + +QuicSpdySession::QuicSpdySession(QuicConnection* connection, + const QuicConfig& config) + : QuicSession(connection, config) { +} + +QuicSpdySession::~QuicSpdySession() { +} + +void QuicSpdySession::Initialize() { + QuicSession::Initialize(); + + if (perspective() == Perspective::IS_SERVER) { + set_largest_peer_created_stream_id(kHeadersStreamId); + } else { + QuicStreamId headers_stream_id = GetNextStreamId(); + DCHECK_EQ(headers_stream_id, kHeadersStreamId); + } + + headers_stream_.reset(new QuicHeadersStream(this)); + DCHECK_EQ(kHeadersStreamId, headers_stream_->id()); + static_streams()[kHeadersStreamId] = headers_stream_.get(); +} + +void QuicSpdySession::OnStreamHeaders(QuicStreamId stream_id, + StringPiece headers_data) { + QuicDataStream* stream = GetSpdyDataStream(stream_id); + if (!stream) { + // It's quite possible to receive headers after a stream has been reset. + return; + } + stream->OnStreamHeaders(headers_data); +} + +void QuicSpdySession::OnStreamHeadersPriority(QuicStreamId stream_id, + QuicPriority priority) { + QuicDataStream* stream = GetSpdyDataStream(stream_id); + if (!stream) { + // It's quite possible to receive headers after a stream has been reset. + return; + } + stream->OnStreamHeadersPriority(priority); +} + +void QuicSpdySession::OnStreamHeadersComplete(QuicStreamId stream_id, + bool fin, + size_t frame_len) { + QuicDataStream* stream = GetSpdyDataStream(stream_id); + if (!stream) { + // It's quite possible to receive headers after a stream has been reset. + return; + } + stream->OnStreamHeadersComplete(fin, frame_len); +} + +size_t QuicSpdySession::WriteHeaders( + QuicStreamId id, + const SpdyHeaderBlock& headers, + bool fin, + QuicPriority priority, + QuicAckNotifier::DelegateInterface* ack_notifier_delegate) { + return headers_stream_->WriteHeaders(id, headers, fin, priority, + ack_notifier_delegate); +} + +QuicDataStream* QuicSpdySession::GetSpdyDataStream( + const QuicStreamId stream_id) { + return static_cast<QuicDataStream*>(GetDynamicStream(stream_id)); +} + +} // namespace net diff --git a/pool/shard007/C++/0093527_zip_analyzer.cc b/pool/shard007/C++/0093527_zip_analyzer.cc new file mode 100644 index 0000000000000000000000000000000000000000..d10aebf84364fcfd28e615878b909e6f68df520d --- /dev/null +++ b/pool/shard007/C++/0093527_zip_analyzer.cc @@ -0,0 +1,93 @@ +// Copyright (c) 2012 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 "chrome/common/safe_browsing/zip_analyzer.h" + +#include <stddef.h> +#include <stdint.h> + +#include <memory> +#include <set> + +#include "base/logging.h" +#include "base/macros.h" +#include "base/metrics/histogram_functions.h" +#include "base/metrics/histogram_macros.h" +#include "base/numerics/checked_math.h" +#include "base/rand_util.h" +#include "base/time/time.h" +#include "build/build_config.h" +#include "chrome/common/safe_browsing/archive_analyzer_results.h" +#include "components/safe_browsing/content/common/file_type_policies.h" +#include "components/safe_browsing/core/common/proto/csd.pb.h" +#include "third_party/zlib/google/zip_reader.h" + +namespace safe_browsing { +namespace zip_analyzer { + +namespace { + +// The maximum duration of ZIP analysis, in milliseconds. +const int kZipAnalysisTimeoutMs = 10000; + +} // namespace + +void AnalyzeZipFile(base::File zip_file, + base::File temp_file, + ArchiveAnalyzerResults* results) { + base::Time start_time = base::Time::Now(); + zip::ZipReader reader; + if (!reader.OpenFromPlatformFile(zip_file.GetPlatformFile())) { + DVLOG(1) << "Failed to open zip file"; + return; + } + + bool too_big_to_unpack = + base::checked_cast<uint64_t>(zip_file.GetLength()) > + FileTypePolicies::GetInstance()->GetMaxFileSizeToAnalyze("zip"); + if (too_big_to_unpack) { + results->success = false; + return; + } + + bool timeout = false; + bool advanced = true; + results->file_count = 0; + results->directory_count = 0; + for (; reader.HasMore(); advanced = reader.AdvanceToNextEntry()) { + if (!advanced) { + DVLOG(1) << "Could not advance to next entry, aborting zip scan."; + return; + } + if (!reader.OpenCurrentEntryInZip()) { + DVLOG(1) << "Failed to open current entry in zip file"; + continue; + } + if (base::Time::Now() - start_time > + base::Milliseconds(kZipAnalysisTimeoutMs)) { + timeout = true; + break; + } + + // Clear the |temp_file| between extractions. + temp_file.Seek(base::File::Whence::FROM_BEGIN, 0); + temp_file.SetLength(0); + zip::FileWriterDelegate writer(&temp_file); + reader.ExtractCurrentEntry(&writer, std::numeric_limits<uint64_t>::max()); + UpdateArchiveAnalyzerResultsWithFile( + reader.current_entry_info()->file_path(), &temp_file, + writer.file_length(), reader.current_entry_info()->is_encrypted(), + results); + + if (reader.current_entry_info()->is_directory()) + results->directory_count++; + else + results->file_count++; + } + + results->success = !timeout; +} + +} // namespace zip_analyzer +} // namespace safe_browsing diff --git a/pool/shard007/C++/0093529_thd_sensor_kbl_amdgpu_thermal.cpp b/pool/shard007/C++/0093529_thd_sensor_kbl_amdgpu_thermal.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9a732bcee790e75e6c9ea2182dea69d9d9d0d66a --- /dev/null +++ b/pool/shard007/C++/0093529_thd_sensor_kbl_amdgpu_thermal.cpp @@ -0,0 +1,54 @@ +/* + * thd_sensor_kbl_amdgpu_thermal.cpp: Thermal Sensor for KBL-G amdgpu + * + * Copyright (C) 2018 Intel Corporation. All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License version + * 2 or later as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + * + * + * Author Name <Srinivas.Pandruvada@linux.intel.com> + * + */ + +#include <dirent.h> + +#include "thd_sensor_kbl_amdgpu_thermal.h" + +cthd_sensor_kbl_amdgpu_thermal::cthd_sensor_kbl_amdgpu_thermal(int index) : + cthd_sensor(index, "", "amdgpu-temperature", SENSOR_TYPE_RAW) { + + DIR *dir; + struct dirent *entry; + const std::string base_path = "/sys/class/hwmon/"; + + if ((dir = opendir(base_path.c_str())) != NULL) { + while ((entry = readdir(dir)) != NULL) { + // Check name + std::string name_path = base_path + entry->d_name + "/name"; + + std::ifstream ifs(name_path.c_str(), std::ifstream::in); + if (ifs.good()) { + std::string line; + while (std::getline(ifs, line)) { + if (line == "amdgpu") { + update_path(base_path + entry->d_name + "/temp1_input"); + } + } + ifs.close(); + } + } + closedir(dir); + } +} diff --git a/pool/shard007/C++/0093531_IterateObjectsFromObject0103.cpp b/pool/shard007/C++/0093531_IterateObjectsFromObject0103.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cf6a2c7422a61668760dcafde5f65398f1de2c34 --- /dev/null +++ b/pool/shard007/C++/0093531_IterateObjectsFromObject0103.cpp @@ -0,0 +1,136 @@ +/* + Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + See the License for the specific language governing permissions and + limitations under the License. +*/ +/** + * @author Valentin Al. Sitnick + * @version $Revision: 1.1 $ + * + */ + +/* *********************************************************************** */ + +#include "events.h" +#include "utils.h" +#include "fake.h" + +static bool test = false; +static bool util = false; +static bool flag = false; + +static jvmtiIterationControl JNICALL func(jvmtiObjectReferenceKind, jlong, + jlong, jlong*, jlong, jint, void*); + +/* *********************************************************************** */ + +/** + * test of function IterateOverObjectsReachableFromObject0101 + */ +void IterateObjectsFromObject0102() +{ + //Fake method for docletting only +} + +/* *********************************************************************** */ + +JNIEXPORT jint JNICALL Agent_OnLoad(prms_AGENT_ONLOAD) +{ + check_AGENT_ONLOAD; + + Callbacks CB; + + cb_exc; + cb_death; + + AGENT_FOR_EVENTS_TESTS_PART_I; /* events.h */ + + jvmtiEvent events[] = { JVMTI_EVENT_EXCEPTION, JVMTI_EVENT_VM_DEATH }; + + AGENT_FOR_EVENTS_TESTS_PART_II; + + fprintf(stderr, "\n-------------------------------------------------\n"); + fprintf(stderr, "\ntest IterateObjectsFromObject0103 is started\n{\n"); + fflush(stderr); + + return JNI_OK; +} + +/* *********************************************************************** */ + +void JNICALL callbackException(prms_EXCPT) +{ + check_EXCPT; + + if (flag) return; + + char* name; + char* signature; + char* generic; + jvmtiPhase phase; + jvmtiError result; + + result = jvmti_env->GetPhase(&phase); + fprintf(stderr, "\tnative: GetPhase result = %d (must be zero) \n", result); + fprintf(stderr, "\tnative: current phase is %d (must be 4 (LIVE-phase)) \n", phase); + if ((result != JVMTI_ERROR_NONE) || (phase != JVMTI_PHASE_LIVE)) return; + result = jvmti_env->GetMethodName(method, &name, &signature, &generic); + fprintf(stderr, "\tnative: GetMethodName result = %d (must be zero) \n", result); + fprintf(stderr, "\tnative: method name is %s \n", name); + fprintf(stderr, "\tnative: signature name is %s \n", signature); + fprintf(stderr, "\tnative: generic name is %s \n", generic); + fflush(stderr); + + if (result != JVMTI_ERROR_NONE) return; + if (strcmp(name, "special_method")) return; + + flag = true; + util = true; + + jobject object = exception; + jvmtiObjectReferenceCallback object_reference_callback = func; + void* user_data = NULL; + + result = jvmti_env->IterateOverObjectsReachableFromObject( NULL, + object_reference_callback, user_data); + + fprintf(stderr, "\tnative: IterateOverObjectsReachableFromObject result = %d (must be JVMTI_ERROR_INVALID_OBJECT (20)) \n", + result); + + if (result == JVMTI_ERROR_INVALID_OBJECT) test = true; +} + +void JNICALL callbackVMDeath(prms_VMDEATH) +{ + check_VMDEATH; + + fprintf(stderr, "\n\tTest of function IterateOverObjectsReachableFromObject0103 : "); + + if (test && util) + fprintf(stderr, " passed \n"); + else + fprintf(stderr, " failed \n"); + + fprintf(stderr, "\n} /* test IterateObjectsFromObject0103 is finished */ \n"); + fflush(stderr); +} + +/* *********************************************************************** */ + +jvmtiIterationControl JNICALL func(jvmtiObjectReferenceKind, jlong, + jlong, jlong*, jlong, jint, void*) +{ + return (jvmtiIterationControl)NULL; +} + diff --git a/pool/shard007/C++/0093533_GameSwitch.cpp b/pool/shard007/C++/0093533_GameSwitch.cpp new file mode 100644 index 0000000000000000000000000000000000000000..955314cfa8fcab968c9f7dbf94cfd3e00da25fb1 --- /dev/null +++ b/pool/shard007/C++/0093533_GameSwitch.cpp @@ -0,0 +1,79 @@ +#include "GameSwitch.h" + +#include "GVC.h" + +Game* GameSwitch::game = NULL; +GameMenu* GameSwitch::menu = NULL; +GameOver* GameSwitch::over = NULL; +GameOptions* GameSwitch::options = NULL; +GameHighScores* GameSwitch::highscores = NULL; +GameSubmitName* GameSwitch::submitName = NULL; + +GameSwitch::GameSwitch() +{ +} + +GameSwitch::~GameSwitch() +{ + delete(game); + delete(menu); + delete(over); + delete(options); + delete(highscores); + delete(submitName); +} + +void GameSwitch::load(Game& _game, GameMenu& _menu, GameOver& _over, GameOptions& _options, + GameHighScores& _highscores, GameSubmitName& _submitName) +{ + GameSwitch::game = &_game; + GameSwitch::menu = &_menu; + GameSwitch::over = &_over; + GameSwitch::options = &_options; + GameSwitch::highscores = &_highscores; + GameSwitch::submitName = &_submitName; +} + +void GameSwitch::alternateWorld(int world) +{ + if(world == 0) + { + menu->loop(); + } + else + { + if(world==1) + { + game->loop(); + } + else + { + if(world==2) + { + over->loop(); + } + else + { + if(world==3) + { + highscores->loop(); + } + else + { + if(world==4) + { + submitName->loop(); + } + else + { + if(world==5) + { + options->loop(); + } + } + } + } + } + } + return; +} diff --git a/pool/shard007/C++/0093534_1.cc b/pool/shard007/C++/0093534_1.cc new file mode 100644 index 0000000000000000000000000000000000000000..76f69fa6c283a33aa2937e8e0773282aff1871a7 --- /dev/null +++ b/pool/shard007/C++/0093534_1.cc @@ -0,0 +1,51 @@ +// 1999-09-20 bkoz + +// Copyright (C) 1999-2017 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// <http://www.gnu.org/licenses/>. + + +// 27.4.4.2 basic_ios member functions + +// NB: Don't include any other headers in this file. +#include <ios> +#include <testsuite_hooks.h> + +void test01() +{ + const std::locale c_loc = std::locale::classic(); + + std::ios ios_01(0); + std::ios::char_type ct01; + std::ios::char_type ct02('x');; + + // 27.4.2.3 locales + ios_01.imbue(c_loc); + + // char narrow(char_type c, char dfault) const; + char c1 = ios_01.narrow(ct02, 0); + VERIFY( c1 == 'x' ); + + // char_type widen(char c) const; + ct01 = ios_01.widen('c'); + VERIFY( ct01 == 'c' ); +} + +int main() +{ + test01(); + return 0; +} diff --git a/pool/shard007/C++/0093535_Socket.cpp b/pool/shard007/C++/0093535_Socket.cpp new file mode 100644 index 0000000000000000000000000000000000000000..225784d8dd25e0b657db10986a602a1824aea317 --- /dev/null +++ b/pool/shard007/C++/0093535_Socket.cpp @@ -0,0 +1,94 @@ +/* + * File: Socket.cpp + * Author: kleber + * + * Created on 14 de Maio de 2015, 22:28 + */ + +#include "Socket.h" + +namespace jk { + + Socket::Socket(string serverIP, int portnu) { + assert(!serverIP.empty()); + assert(portnu); + + this->serverIP = serverIP; + this->portnu = portnu; + + create(); + + bindServer(); + } + + Socket::Socket(const Socket& orig) { + } + + Socket::~Socket() { + // has connection + if (socketfd > 0) + closeConnection(socketfd); + } + + void Socket::create() { + // create a socket + socketfd = socket(AF_INET, SOCK_STREAM, 0); + + if (socketfd < 0) + throw new SocketException("ERROR - create socket failed."); + } + + void Socket::bindServer() { + + // clear data struct + bzero((char *) &server_addr, sizeof (server_addr)); + + server_addr.sin_family = AF_INET; + server_addr.sin_addr.s_addr = inet_addr(serverIP.c_str()); + // convert between host and network byte order + server_addr.sin_port = htons(portnu); + + if (bind(socketfd, (struct sockaddr *) &server_addr, sizeof (server_addr)) < 0) + throw new SocketException("ERROR - bind failed."); + + } + + void Socket::closeConnection(int socketID) { + close(socketID); + } + + void Socket::run() { + + // In kernels before 2.4.25 SOMAXCONN is 128 + listen(socketfd, SOMAXCONN); + + clientlen = sizeof (client_addr); + + // TODO - put a stop point + while (true) { + + printf("wait connection...\n"); + + // listen for connections + socketcli = accept(socketfd, (struct sockaddr*) &client_addr, &clientlen); + + if (socketcli < 0) + throw new SocketException("ERROR - acept connection failed."); + + int pid = fork(); + switch (pid) { + case 0: + this->onRead(); + closeConnection(socketcli); + break; + case -1: + throw new SocketException("ERRO - fork for read socket failed."); + default: + printf("got connection from IP %s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); + } + + } + + closeConnection(socketfd); + } +} \ No newline at end of file diff --git a/pool/shard007/C++/0093538_dllmain.cc b/pool/shard007/C++/0093538_dllmain.cc new file mode 100644 index 0000000000000000000000000000000000000000..9ef78e6215f25389b240b97d96f9225bccaeb18f --- /dev/null +++ b/pool/shard007/C++/0093538_dllmain.cc @@ -0,0 +1,274 @@ +// Copyright 2018 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 "chrome/credential_provider/gaiacp/dllmain.h" + +// It is important to include gaia_credential_base.h, reauth_credential.h and +// gaia_credential.h here, even though the classes are not used in this source +// file, in order to ensure that the COM objects will be properly linked into +// the dll. This became important after moving all the COM object code into a +// static library for testing purposes. +// +// This article clearly describes the issue and the fix: +// +// https://blogs.msdn.microsoft.com/larryosterman/2004/09/27/when-i-moved-my-code-into-a-library-what-happened-to-my-atl-com-objects/ + +#include "base/command_line.h" +#include "base/files/file_path.h" +#include "base/json/json_reader.h" +#include "base/macros.h" +#include "base/strings/utf_string_conversions.h" +#include "base/values.h" +#include "base/win/current_module.h" +#include "base/win/registry.h" +#include "base/win/scoped_com_initializer.h" +#include "build/branding_buildflags.h" +#include "chrome/common/chrome_version.h" +#include "chrome/credential_provider/common/gcp_strings.h" +#include "chrome/credential_provider/gaiacp/gaia_credential.h" +#include "chrome/credential_provider/gaiacp/gaia_credential_base.h" +#include "chrome/credential_provider/gaiacp/gaia_credential_provider.h" +#include "chrome/credential_provider/gaiacp/gaia_credential_provider_module.h" +#include "chrome/credential_provider/gaiacp/gcp_utils.h" +#include "chrome/credential_provider/gaiacp/logging.h" +#include "chrome/credential_provider/gaiacp/os_process_manager.h" +#include "chrome/credential_provider/gaiacp/os_user_manager.h" +#include "chrome/credential_provider/gaiacp/reauth_credential.h" +#include "chrome/credential_provider/gaiacp/reg_utils.h" +#include "components/crash/core/app/crash_switches.h" +#include "components/crash/core/app/run_as_crashpad_handler_win.h" +#include "content/public/common/content_switches.h" + +using credential_provider::putHR; + +credential_provider::CGaiaCredentialProviderModule _AtlModule; + +#define __TYPELIB_ID_SUFFIX_STRING(id) L"\\" _T(#id) +#define _TYPELIB_ID_SUFFIX_STRING(id) __TYPELIB_ID_SUFFIX_STRING(id) +#define TYPELIB_SUFFIX_STRING \ + _TYPELIB_ID_SUFFIX_STRING(TLB_GAIACREDENTIALPROVIDER) + +// DLL Entry Point +extern "C" BOOL WINAPI DllMain(HINSTANCE hinstance, + DWORD reason, + LPVOID reserved) { + return _AtlModule.DllMain(hinstance, reason, reserved); +} + +// Used to determine whether the DLL can be unloaded by OLE. +STDAPI DllCanUnloadNow(void) { + HRESULT hr = _AtlModule.DllCanUnloadNow(); + LOGFN(VERBOSE) << "hr=" << putHR(hr); + return hr; +} + +// Returns a class factory to create an object of the requested type. +STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) { + // This is performed in here to avoid from doing substantial work in DLLMain. + _AtlModule.LogProcessDetails(); + + // Check to see if the credential provider has crashed too much recently. + // If it has then do not allow it to create any credential providers. + if (!credential_provider::WriteToStartupSentinel()) { + LOGFN(ERROR) << "Disabled due to previous unsuccessful starts"; + return E_NOTIMPL; + } + + _AtlModule.InitializeCrashReporting(); + + HRESULT hr = _AtlModule.DllGetClassObject(rclsid, riid, ppv); + + if (SUCCEEDED(hr)) { + // Start refreshing token handle validity as soon as possible so that when + // their validity is requested later on by the credential providers they may + // already be available and no wait is needed. + _AtlModule.RefreshTokenHandleValidity(); + + _AtlModule.CheckGCPWExtension(); + } + + return hr; +} + +// DllRegisterServer - Adds entries to the system registry. +STDAPI DllRegisterServer(void) { + HRESULT hr = credential_provider::CGaiaCredentialBase::OnDllRegisterServer(); + LOGFN(VERBOSE) << "CGaiaCredential::OnDllRegisterServer hr=" << putHR(hr); + + if (SUCCEEDED(hr)) { + // Registers object. FALSE means don't register typelib. The default + // behaviour is assume the typelib has ID 1. But in this case grit can't + // be forced to use an ID of 1 when writing the rc file. + hr = _AtlModule.DllRegisterServer(FALSE); + LOGFN(VERBOSE) << "_AtlModule.DllRegisterServer hr=" << putHR(hr); + } + +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) + // Register with Google Update. + if (SUCCEEDED(hr)) { + base::win::RegKey key(HKEY_LOCAL_MACHINE, + credential_provider::kRegUpdaterClientsAppPath, + KEY_SET_VALUE | KEY_WOW64_32KEY); + LONG sts = key.WriteValue(L"pv", TEXT(CHROME_VERSION_STRING)); + if (sts != ERROR_SUCCESS) { + hr = HRESULT_FROM_WIN32(sts); + LOGFN(ERROR) << "key.WriteValue(pv) hr=" << putHR(hr); + } else { + sts = key.WriteValue( + L"name", + credential_provider::GetStringResource(IDS_PROJNAME_BASE).c_str()); + if (sts != ERROR_SUCCESS) { + hr = HRESULT_FROM_WIN32(sts); + LOGFN(ERROR) << "key.WriteValue(name) hr=" << putHR(hr); + } + } + } +#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) + + return hr; +} + +// DllUnregisterServer - Removes entries from the system registry. +STDAPI DllUnregisterServer(void) { +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) + // Unregister with Google Update. + base::win::RegKey key(HKEY_LOCAL_MACHINE, L"", DELETE | KEY_WOW64_32KEY); + LONG sts = key.DeleteKey(credential_provider::kRegUpdaterClientsAppPath); + + bool all_succeeded = sts == ERROR_SUCCESS; +#else + bool all_succeeded = true; +#endif + + HRESULT hr = + credential_provider::CGaiaCredentialBase::OnDllUnregisterServer(); + LOGFN(VERBOSE) << "CGaiaCredential::OnDllUnregisterServer hr=" << putHR(hr); + all_succeeded &= SUCCEEDED(hr); + + hr = _AtlModule.DllUnregisterServer(FALSE); + LOGFN(VERBOSE) << "_AtlModule.DllUnregisterServer hr=" << putHR(hr); + all_succeeded &= SUCCEEDED(hr); + + return all_succeeded ? S_OK : E_FAIL; +} + +// This entry point is called via rundll32. See +// CGaiaCredential::ForkPerformPostSigninActionsStub() for details. +void CALLBACK PerformPostSigninActionsW(HWND /*hwnd*/, + HINSTANCE /*hinst*/, + wchar_t* /*pszCmdLine*/, + int /*show*/) { + LOGFN(VERBOSE); + + _AtlModule.InitializeCrashReporting(); + + HANDLE hStdin = ::GetStdHandle(STD_INPUT_HANDLE); // No need to close. + if (hStdin == INVALID_HANDLE_VALUE) { + LOGFN(VERBOSE) << "No stdin"; + return; + } + + // First, read the buffer size. + DWORD buffer_size = 0; + DWORD bytes_read = 0; + if (!::ReadFile(hStdin, &buffer_size, sizeof(buffer_size), &bytes_read, + nullptr)) { + HRESULT hr = HRESULT_FROM_WIN32(::GetLastError()); + LOGFN(ERROR) << "ReadFile for buffer size failed. hr=" << putHR(hr); + return; + } + + // For security, we check for a max of 1 MB buffer size. + const DWORD kMaxBufferSizeAllowed = 1024 * 1024; // 1MB + if (!buffer_size || buffer_size > kMaxBufferSizeAllowed) { + LOGFN(ERROR) << "Invalid buffer size."; + return; + } + + // Second, read the buffer. + std::vector<char> buffer(buffer_size, 0); + if (!::ReadFile(hStdin, buffer.data(), buffer.size(), &bytes_read, nullptr)) { + HRESULT hr = HRESULT_FROM_WIN32(::GetLastError()); + LOGFN(ERROR) << "ReadFile hr=" << putHR(hr); + return; + } + // Don't log |buffer| since it contains sensitive info like password. + + HRESULT hr = S_OK; + absl::optional<base::Value> properties = + base::JSONReader::Read(buffer.data(), base::JSON_ALLOW_TRAILING_COMMAS); + + credential_provider::SecurelyClearBuffer(buffer.data(), buffer.size()); + + if (!properties || !properties->is_dict()) { + LOGFN(ERROR) << "base::JSONReader::Read failed length=" << buffer.size(); + return; + } + + // Make sure COM is initialized in this thread. This thread must be + // initialized as an MTA or the call to enroll with MDM causes a crash in COM. + base::win::ScopedCOMInitializer com_initializer( + base::win::ScopedCOMInitializer::kMTA); + if (!com_initializer.Succeeded()) { + hr = HRESULT_FROM_WIN32(::GetLastError()); + LOGFN(ERROR) << "ScopedCOMInitializer failed hr=" << putHR(hr); + } + + hr = credential_provider::CGaiaCredentialBase::PerformPostSigninActions( + *properties, com_initializer.Succeeded()); + if (FAILED(hr)) + LOGFN(ERROR) << "PerformPostSigninActions hr=" << putHR(hr); + + credential_provider::SecurelyClearDictionaryValue(&properties); + + LOGFN(VERBOSE) << "Done"; +} + +void CALLBACK RunAsCrashpadHandlerW(HWND /*hwnd*/, + HINSTANCE /*hinst*/, + wchar_t* /*pszCmdLine*/, + int /*show*/) { + base::CommandLine::Init(0, nullptr); + + const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess(); + + DCHECK_EQ(cmd_line->GetSwitchValueASCII(switches::kProcessType), + crash_reporter::switches::kCrashpadHandler); + + std::wstring entrypoint_arg; + credential_provider::GetEntryPointArgumentForRunDll( + CURRENT_MODULE(), credential_provider::kRunAsCrashpadHandlerEntryPoint, + &entrypoint_arg); + + // Get all the arguments from the original command line except for the + // entrypoint argument otherwise the crashpad handler will fail to start + // thinking that it is an invalid argument. + base::CommandLine::StringVector argv_without_entry_point; + argv_without_entry_point.reserve(cmd_line->argv().size()); + for (const auto& argv : cmd_line->argv()) { + if (argv == entrypoint_arg) + continue; + + argv_without_entry_point.push_back(argv); + } + + base::CommandLine cmd_line_without_entry_point(argv_without_entry_point); + + crash_reporter::RunAsCrashpadHandler(cmd_line_without_entry_point, + base::FilePath(), switches::kProcessType, + "user-data-dir"); +} + +void CALLBACK +SetFakesForTesting(const credential_provider::FakesForTesting* fakes) { + DCHECK(fakes); + credential_provider::ScopedLsaPolicy::SetCreatorForTesting( + fakes->scoped_lsa_policy_creator); + credential_provider::OSUserManager::SetInstanceForTesting( + fakes->os_user_manager_for_testing); + credential_provider::OSProcessManager::SetInstanceForTesting( + fakes->os_process_manager_for_testing); + + _AtlModule.set_is_testing(true); +} diff --git a/pool/shard007/C++/0093549_task.cpp b/pool/shard007/C++/0093549_task.cpp new file mode 100644 index 0000000000000000000000000000000000000000..29527e31062b0b88ef434d91dc1fc4575022a287 --- /dev/null +++ b/pool/shard007/C++/0093549_task.cpp @@ -0,0 +1,174 @@ +#include "engine/lumix.h" +#include "engine/core/iallocator.h" +#include "engine/core/mt/task.h" +#include "engine/core/mt/thread.h" +#include "engine/core/pc/simple_win.h" +#include "engine/core/profiler.h" + + + +namespace Lumix +{ + namespace MT + { + const uint32 STACK_SIZE = 0x8000; + + struct TaskImpl + { + explicit TaskImpl(IAllocator& allocator) + : m_allocator(allocator) + { } + + IAllocator& m_allocator; + HANDLE m_handle; + DWORD m_thread_id; + uint32 m_affinity_mask; + uint32 m_priority; + volatile bool m_is_running; + volatile bool m_force_exit; + volatile bool m_exited; + const char* m_thread_name; + Task* m_owner; + }; + + static DWORD WINAPI threadFunction(LPVOID ptr) + { + uint32 ret = 0xffffFFFF; + struct TaskImpl* impl = reinterpret_cast<TaskImpl*>(ptr); + setThreadName(impl->m_thread_id, impl->m_thread_name); + Profiler::setThreadName(impl->m_thread_name); + if (!impl->m_force_exit) + { + ret = impl->m_owner->task(); + } + impl->m_exited = true; + impl->m_is_running = false; + + return ret; + } + + Task::Task(IAllocator& allocator) + { + TaskImpl* impl = LUMIX_NEW(allocator, TaskImpl)(allocator); + impl->m_handle = nullptr; + impl->m_affinity_mask = getProccessAffinityMask(); + impl->m_priority = ::GetThreadPriority(GetCurrentThread()); + impl->m_is_running = false; + impl->m_force_exit = false; + impl->m_exited = false; + impl->m_thread_name = ""; + impl->m_owner = this; + + m_implementation = impl; + } + + Task::~Task() + { + ASSERT(!m_implementation->m_handle); + LUMIX_DELETE(m_implementation->m_allocator, m_implementation); + } + + bool Task::create(const char* name) + { + HANDLE handle = CreateThread(nullptr, STACK_SIZE, threadFunction, m_implementation, CREATE_SUSPENDED, &m_implementation->m_thread_id); + if (handle) + { + m_implementation->m_exited = false; + m_implementation->m_thread_name = name; + m_implementation->m_handle = handle; + } + return handle != nullptr; + } + + bool Task::run() + { + m_implementation->m_is_running = true; + return ::ResumeThread(m_implementation->m_handle) != -1; + } + + bool Task::destroy() + { + while (m_implementation->m_is_running) + { + yield(); + } + + ::CloseHandle(m_implementation->m_handle); + m_implementation->m_handle = nullptr; + return true; + } + + void Task::setAffinityMask(uint32 affinity_mask) + { + m_implementation->m_affinity_mask = affinity_mask; + if (m_implementation->m_handle) + { + ::SetThreadIdealProcessor(m_implementation->m_handle, affinity_mask); + } + } + + void Task::setPriority(uint32 priority) + { + m_implementation->m_priority = priority; + if (m_implementation->m_handle) + { + ::SetThreadPriority(m_implementation->m_handle, priority); + } + } + + uint32 Task::getAffinityMask() const + { + return m_implementation->m_affinity_mask; + } + + uint32 Task::getPriority() const + { + return m_implementation->m_priority; + } + + uint32 Task::getExitCode() const + { + uint32 exit_code = 0xffffFFFF; + ::GetExitCodeThread(m_implementation->m_handle, (LPDWORD)&exit_code); + return exit_code; + } + + bool Task::isRunning() const + { + return m_implementation->m_is_running; + } + + bool Task::isFinished() const + { + return m_implementation->m_exited; + } + + bool Task::isForceExit() const + { + return m_implementation->m_force_exit; + } + + IAllocator& Task::getAllocator() + { + return m_implementation->m_allocator; + } + + void Task::forceExit(bool wait) + { + m_implementation->m_force_exit = true; + + while (!isFinished() && wait) + { + yield(); + } + } + + void Task::exit(int32 exit_code) + { + m_implementation->m_exited = true; + m_implementation->m_is_running = false; + ::ExitThread(exit_code); + } + + } // namespace MT +} // namespace Lumix diff --git a/pool/shard007/C++/0093554_gen_arraybuilder.cpp b/pool/shard007/C++/0093554_gen_arraybuilder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..51b9b4432aad3c028a08b0e7ba1c4efaf2b96ba3 --- /dev/null +++ b/pool/shard007/C++/0093554_gen_arraybuilder.cpp @@ -0,0 +1,186 @@ +/* +* Calvin Neo +* Copyright (C) 2016 Calvin Neo <calvinneo@calvinneo.com> +* +* This program is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation; either version 2 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License along +* with this program; if not, write to the Free Software Foundation, Inc., +* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "gen_common.h" + +ParseNode gen_arraybuilder_from_paramtable(const ParseNode & argtable) { + /***************** + * give initial value + * `B(1:2:3)` can be either a single-element argtable or a exp, depending on what `B` is + * in light of this, reduction conflicts can be raised, + * promote argtable/dimen_slice to paramtable, in order to defer analysis + *****************/ + return gen_token(Term{ TokenMeta::NT_ARRAYBUILDER_LIST, argtable.to_string() }, argtable); +} + +bool maybe_return_array(FunctionInfo * finfo, const ParseNode & elem) { + /***************** + * return true: have a possiblity to return array section + * return false: won't return array section + *================= + * IMPORTANT: + * a function is not an array section, + * BUT it maybe return array section + * if you want to distinguish between function and array semanticly, + * use `is_fortran_function` + *****************/ + if (elem.token_equals(TokenMeta::NT_HIDDENDO)) { + return true; + } + else if (elem.token_equals(TokenMeta::UnknownVariant)) { + VariableInfo * vinfo = get_variable(get_context().current_module, finfo->local_name, elem.to_string()); + if (vinfo != nullptr) + { + if (vinfo->is_array()) { + return true; + } + else { + return false; + } + } + else { + fatal_error("Variable not defined"); + return true; + } + } + else if (elem.token_equals(TokenMeta::NT_FUCNTIONARRAY)){ + // 1. function may return either array or non-array + // 2. a NT_FUCNTIONARRAY can be either a array slice(which returns either an array or a scalar) or a function + // hard to determine, though it's possible to do that, however, this project is not a compiler + // so return true + string varname = elem.get(0).get_what(); + VariableInfo * vinfo = get_variable(get_context().current_module, finfo->local_name, varname); + FunctionInfo * f = get_function(get_context().current_module, varname); + // TODO search function context + if (f != nullptr) + { + // function + std::string & result_name = f->funcdesc.paramtable_info.back(); + VariableInfo * result_vinfo = get_variable(get_context().current_module, finfo->local_name, result_name); + ParseNode & result_type = result_vinfo->type; + if (result_type.token_equals(TokenMeta::Void_Decl, TokenMeta::Void)) + { + // subroutine + return false; + } + else { + if (result_vinfo->is_array()) + { + return true; + } + else { + return false; + } + } + } + else if (vinfo == nullptr) + { + // implicit + return true; + } + else { + return true; + } + } + else if (elem.token_equals(TokenMeta::NT_ARGTABLE_PURE)){ + // hard to determine, so return true + return true; + } + else if (is_literal(elem)) + { + // including literals + return false; + } + else{ + print_error("Strange element", elem); + return true; + } +} + +void regen_arraybuilder(FunctionInfo * finfo, ParseNode & array_builder) { + // wrap arraybuilder.fs.CurrentTerm.what with make_farray function + string arr_decl; + if (array_builder.token_equals(TokenMeta::NT_ARRAYBUILDER_LIST)) + { + // if array is assigned by an `(/` `/)` constructor + bool concat_array = false; + ParseNode & argtable = array_builder.get(0); + // if any of NT_ARRAYBUILDER_LIST's child is an array, then concat_array = true + concat_array = std::accumulate(argtable.begin(), argtable.end(), false, [&](bool x, ParseNode * p) { + return x || maybe_return_array(finfo, *p); + }); + if (!concat_array) + { + // all elements in the array builder is scalar + // can init array from initializer_list of initial value + sprintf(codegen_buf, "make_init_list(%s)", argtable.get_what().c_str()); + arr_decl = string(codegen_buf); + } + else { + // must init array from another farray/for1array + string subarrays = make_str_list(argtable.begin(), argtable.end(), [&](ParseNode * p) { + ParseNode & elem = *p; + if (elem.token_equals(TokenMeta::NT_HIDDENDO)) { + + vector<ParseNode *> hiddendo_layer = get_nested_hiddendo_layers(elem); + SliceBoundInfo lb_size = get_lbound_size_from_hiddendo(finfo, elem, hiddendo_layer); + std::string lb_size_str = gen_sliceinfo_str(get<0>(lb_size).begin(), get<0>(lb_size).end(), get<1>(lb_size).begin(), get<1>(lb_size).end()); + regen_exp(finfo, elem); + std::string lambda = elem.get_what(); + sprintf(codegen_buf, "make_init_list(%s, %s)", lb_size_str.c_str(), lambda.c_str()); + } + else if (elem.token_equals(TokenMeta::UnknownVariant, TokenMeta::NT_FUCNTIONARRAY)) { + regen_exp(finfo, elem); + VariableInfo * vinfo = get_variable(get_context().current_module, finfo->local_name, elem.get_what()); + if (maybe_return_array(finfo, elem)) + { + sprintf(codegen_buf, "make_init_list(%s)", elem.get_what().c_str()); + } + else { + // because forconcat only concat between arrays, so use `make_init_list` to promote a scalar to array + // IMPORTANT, TODO an specification `farray<T> make_init_list(const farray<T> & narr)` make sure no action should be performed to an array + sprintf(codegen_buf, "make_init_list(%s)", elem.get_what().c_str()); + } + } + else if (elem.token_equals(TokenMeta::NT_ARGTABLE_PURE)) + { + // a list of elements + regen_paramtable(finfo, elem); + sprintf(codegen_buf, "make_init_list(%s)", elem.get_what().c_str()); + } + else { + // literal + sprintf(codegen_buf, "make_init_list(%s)", elem.get_what().c_str()); + } + return string(codegen_buf); + }); + arr_decl = "forconcat({" + subarrays + "})"; + } + } + else + { + // if array is assigned by a scalar + // e.g. A = B(:) + regen_exp(finfo, array_builder); + arr_decl = array_builder.get_what(); + } + + array_builder.get_what() = arr_decl; + return; +} \ No newline at end of file diff --git a/pool/shard007/C++/0093555_t50fs.cpp b/pool/shard007/C++/0093555_t50fs.cpp new file mode 100644 index 0000000000000000000000000000000000000000..29012f71857eea01c45823f1c109c52e53e02497 --- /dev/null +++ b/pool/shard007/C++/0093555_t50fs.cpp @@ -0,0 +1,168 @@ +//------------------------------------------------------------------ +// +// @@@ START COPYRIGHT @@@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// +// @@@ END COPYRIGHT @@@ + +#include <assert.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "seabed/fs.h" + +#include "tchkfe.h" +#include "tmsfsutil.h" +#include "tutil.h" +#include "tutilp.h" +#include "ufsri.h" + + +int main(int argc, char *argv[]) { + void *buf; + _xcc_status cc; + bool client = false; + unsigned short count_read; + unsigned short count_written; + unsigned short count_xferred; + int ferr; + short filenum; + short filenum1; + short filenum2; + int filenumt; + int inx; + short lasterr; + int loop = 10; + char my_name[BUFSIZ]; + bool nowait = false; + char *p; + char recv_buffer[BUFSIZ]; + RI_Type ri; + char send_buffer1[BUFSIZ]; + char send_buffer2[BUFSIZ]; + SB_Tag_Type tag; + short tfilenum; + int timeout = -1; + TAD zargs[] = { + { "-client", TA_Bool, TA_NOMAX, &client }, + { "-loop", TA_Int, TA_NOMAX, &loop }, + { "-nowait", TA_Bool, TA_NOMAX, &nowait }, + { "-server", TA_Ign, TA_NOMAX, NULL }, + { "", TA_End, TA_NOMAX, NULL } + }; + + ferr = file_init(&argc, &argv); + TEST_CHK_FEOK(ferr); + msfs_util_init_fs(&argc, &argv, file_debug_hook); + arg_proc_args(zargs, false, argc, argv); + util_test_start(client); + ferr = file_mon_process_startup(!client); // system messages + TEST_CHK_FEOK(ferr); + util_gethostname(my_name, sizeof(my_name)); + + if (client) { + ferr = XFILE_OPEN_((char *) "$srv", 4, &filenum1, + 0, 0, 0, 0, 0, 0, 0, NULL); + TEST_CHK_FEOK(ferr); + ferr = XFILE_OPEN_((char *) "$srv", 4, &filenum2, + 0, 0, 0, 0, 0, 0, 0, NULL); + TEST_CHK_FEOK(ferr); + for (inx = 0; inx < loop; inx++) { + sprintf(send_buffer1, "hello, greetings from %s, inx=%d, fn=%d", + my_name, inx, filenum1); + sprintf(send_buffer2, "hello, greetings from %s, inx=%d, fn=%d", + my_name, inx, filenum2); + cc = XWRITEREADX(filenum1, + send_buffer1, + (short) (strlen(send_buffer1) + 1), + BUFSIZ, + &count_read, + 0); + TEST_CHK_CCEQ(cc); + cc = XWRITEREADX(filenum2, + send_buffer2, + (short) (strlen(send_buffer2) + 1), + BUFSIZ, + &count_read, + 0); + TEST_CHK_CCEQ(cc); + printf("%s\n", send_buffer1); + printf("%s\n", send_buffer2); + } + ferr = XFILE_CLOSE_(filenum1, 0); + TEST_CHK_FEOK(ferr); + ferr = XFILE_CLOSE_(filenum2, 0); + TEST_CHK_FEOK(ferr); + } else { + ferr = XFILE_OPEN_((char *) "$RECEIVE", 8, &filenum, + 0, 0, nowait ? (short) 1 : (short) 0, + 1, 0, // sys msg + 0, 0, NULL); + TEST_CHK_FEOK(ferr); + for (inx = 0; inx < loop * 2 + 4; inx++) { // get opens and closes + cc = XREADUPDATEX(filenum, + recv_buffer, + BUFSIZ, + &count_read, + 0); + TEST_CHK_CCIGNORE(cc); + if (nowait) { + tfilenum = filenum; + cc = XAWAITIOX(&tfilenum, + &buf, + &count_xferred, + &tag, + timeout, + NULL); + TEST_CHK_CCIGNORE(cc); + count_read = count_xferred; + } + ferr = XFILE_GETINFO_(-1, &lasterr, NULL, 0, NULL, NULL, NULL); + TEST_CHK_FEOK(ferr); + getri(&ri); + if (lasterr != XZFIL_ERR_OK) + assert(ri.file_number); + else { + p = &recv_buffer[count_read]; + while ((p > recv_buffer) && (*p != '=')) + p--; + assert(*p == '='); + p++; + sscanf(p, "%d", &filenumt); + assert(filenumt == ri.file_number); + } + strcat(recv_buffer, "- reply from "); + strcat(recv_buffer, my_name); + count_read = (short) (strlen(recv_buffer) + 1); + cc = XREPLYX(recv_buffer, + count_read, + &count_written, + 0, + XZFIL_ERR_OK); + TEST_CHK_CCEQ(cc); + } + ferr = XFILE_CLOSE_(filenum, 0); + TEST_CHK_FEOK(ferr); + } + ferr = file_mon_process_shutdown(); + TEST_CHK_FEOK(ferr); + util_test_finish(client); + return 0; +} diff --git a/pool/shard007/C++/0093574_GPhoto2ViewfinderImpl.cpp b/pool/shard007/C++/0093574_GPhoto2ViewfinderImpl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0ea0433eec3559e65324728522874257851e2d7a --- /dev/null +++ b/pool/shard007/C++/0093574_GPhoto2ViewfinderImpl.cpp @@ -0,0 +1,188 @@ +// +// RemotePhotoTool - remote camera control software +// Copyright (C) 2008-2020 Michael Fink +// +/// \file GPhoto2ViewfinderImpl.cpp gPhoto2 - Viewfinder impl +// +#include "stdafx.h" +#include "GPhoto2ViewfinderImpl.hpp" +#include "GPhoto2PropertyAccess.hpp" +#include "GPhoto2Include.hpp" +#include "SingleThreadExecutor.hpp" +#include "PeriodicExecuteTimer.hpp" + +using GPhoto2::ViewfinderImpl; + +ViewfinderImpl::ViewfinderImpl(RefSp ref, + std::shared_ptr<_Camera> camera, + std::shared_ptr<PropertyAccess> properties, + SingleThreadExecutor& executor) + :m_ref(ref), + m_camera(camera), + m_properties(properties), + m_executor(executor), + m_eventTimerStopped(false) +{ +} + +ViewfinderImpl::~ViewfinderImpl() +{ + try + { + Close(); + } + catch (...) + { + } +} + +bool ViewfinderImpl::GetCapability(T_enViewfinderCapability viewfinderCapability) const +{ + switch (viewfinderCapability) + { + case Viewfinder::capOutputTypeVideoOut: + return m_properties->IsAvailPropertyName("output"); + + case Viewfinder::capGetHistogram: + return false; // TODO check for EOS histogram property? + + default: + ATLASSERT(false); + break; + } + + return false; +} + +void ViewfinderImpl::SetOutputType(T_enOutputType outputType) +{ + int outputValue = 0; + switch (outputType) + { + case Viewfinder::outputTypeUndefined: + return; // do nothing + + case Viewfinder::outputTypeLCD: + outputValue = 0; + break; + + case Viewfinder::outputTypeVideoOut: + outputValue = 1; + break; + + case Viewfinder::outputTypeOff: + outputValue = 2; + break; + + default: + ATLASSERT(false); + return; + } + + std::vector<CString> validValuesList = m_properties->GetValidValues("output"); + + if (static_cast<size_t>(outputValue) >= validValuesList.size()) + return; // index not available + + Variant value; + value.Set(validValuesList[outputValue]); + value.SetType(Variant::typeInt32); + + m_properties->SetPropertyByName(_T("output"), value); +} + +void ViewfinderImpl::SetAvailImageHandler(T_fnOnAvailViewfinderImage onAvailViewfinderImage) +{ + { + LightweightMutex::LockType lock{ m_mutexFnOnAvailViewfinderImage }; + + m_onAvailViewfinderImage = onAvailViewfinderImage; + } + + if (onAvailViewfinderImage != nullptr) + StartBackgroundThread(); + else + StopBackgroundThread(); +} + +void ViewfinderImpl::GetHistogram(T_enHistogramType histogramType, std::vector<unsigned int>& histogramData) +{ + // TODO implement + UNUSED(histogramType); + UNUSED(histogramData); +} + +void ViewfinderImpl::Close() +{ + StopBackgroundThread(); +} + +void ViewfinderImpl::StartBackgroundThread() +{ + m_viewfinderImageTimer.reset(); // clear old timers + + m_viewfinderImageTimer.reset( + new PeriodicExecuteTimer( + m_executor, + 50, // 50 ms results in 20 fps + std::bind(&ViewfinderImpl::OnGetViewfinderImage, this) + )); +} + +void ViewfinderImpl::StopBackgroundThread() +{ + if (m_viewfinderImageTimer == nullptr) + return; + + m_eventTimerStopped.Reset(); + + m_executor.Schedule( + std::bind(&ViewfinderImpl::AsyncStopBackgroundThread, shared_from_this())); + + m_eventTimerStopped.Wait(); +} + +void ViewfinderImpl::AsyncStopBackgroundThread() +{ + m_viewfinderImageTimer.reset(); + + m_eventTimerStopped.Set(); +} + +void ViewfinderImpl::OnGetViewfinderImage() +{ + { + LightweightMutex::LockType lock(m_mutexFnOnAvailViewfinderImage); + + if (m_onAvailViewfinderImage == nullptr) + return; + } + + std::vector<BYTE> imageData; + GetImage(imageData); + + LightweightMutex::LockType lock(m_mutexFnOnAvailViewfinderImage); + + if (m_onAvailViewfinderImage != nullptr) + m_onAvailViewfinderImage(imageData); +} + +void ViewfinderImpl::GetImage(std::vector<BYTE>& imageData) +{ + CameraFile* rawFile = nullptr; + int ret = gp_file_new(&rawFile); + CheckError(_T("gp_file_new"), ret, __FILE__, __LINE__); + + auto file = std::shared_ptr<CameraFile>(rawFile, gp_file_free); + + ret = gp_camera_capture_preview(m_camera.get(), file.get(), m_ref->GetContext().get()); + CheckError(_T("gp_camera_capture_preview"), ret, __FILE__, __LINE__); + + unsigned long size = 0; + const char* data = nullptr; + ret = gp_file_get_data_and_size(file.get(), &data, &size); + CheckError(_T("gp_file_get_data_and_size"), ret, __FILE__, __LINE__); + + const BYTE* dataBytes = reinterpret_cast<const BYTE*>(data); + imageData.assign(dataBytes, dataBytes + size); +} diff --git a/pool/shard007/C++/0093579_rotatable_file_writer_test.cpp b/pool/shard007/C++/0093579_rotatable_file_writer_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bc6903964434ea6b0384b034a9aafa809f287c87 --- /dev/null +++ b/pool/shard007/C++/0093579_rotatable_file_writer_test.cpp @@ -0,0 +1,132 @@ +/* Copyright 2013 10gen Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mongo/platform/basic.h" + +#include <fstream> + +#include "mongo/logger/rotatable_file_writer.h" +#include "mongo/unittest/unittest.h" + +namespace { + using namespace mongo; + using namespace mongo::logger; + + const std::string logFileName("LogTest_RotatableFileAppender.txt"); + const std::string logFileNameRotated("LogTest_RotatableFileAppender_Rotated.txt"); + + // TODO(schwerin): Create a safe, uniform mechanism by which unit tests may read and write + // temporary files. + class RotatableFileWriterTest : public mongo::unittest::Test { + public: + RotatableFileWriterTest() { + unlink(logFileName.c_str()); + unlink(logFileNameRotated.c_str()); + } + + virtual ~RotatableFileWriterTest() { + unlink(logFileName.c_str()); + unlink(logFileNameRotated.c_str()); + } + }; + + TEST_F(RotatableFileWriterTest, RotationTest) { + using namespace logger; + + { + RotatableFileWriter writer; + RotatableFileWriter::Use writerUse(&writer); + ASSERT_OK(writerUse.setFileName(logFileName, false)); + ASSERT_TRUE(writerUse.stream() << "Level 1 message." << std::endl); + ASSERT_TRUE(writerUse.stream() << "Level 2 message." << std::endl); + ASSERT_OK(writerUse.rotate(logFileNameRotated)); + ASSERT_TRUE(writerUse.stream() << "Level 3 message." << std::endl); + ASSERT_TRUE(writerUse.stream() << "Level 4 message." << std::endl); + } + + { + std::ifstream ifs(logFileNameRotated.c_str()); + ASSERT_TRUE(ifs.is_open()); + ASSERT_TRUE(ifs.good()); + std::string input; + ASSERT_TRUE(std::getline(ifs, input)); + ASSERT_EQUALS(input, "Level 1 message."); + ASSERT_TRUE(std::getline(ifs, input)); + ASSERT_EQUALS(input, "Level 2 message."); + ASSERT_TRUE(std::getline(ifs, input).fail()); + ASSERT_TRUE(ifs.eof()); + } + + { + std::ifstream ifs(logFileName.c_str()); + ASSERT_TRUE(ifs.is_open()); + ASSERT_TRUE(ifs.good()); + std::string input; + ASSERT_TRUE(std::getline(ifs, input)); + ASSERT_EQUALS(input, "Level 3 message."); + ASSERT_TRUE(std::getline(ifs, input)); + ASSERT_EQUALS(input, "Level 4 message."); + ASSERT_TRUE(std::getline(ifs, input).fail()); + ASSERT_TRUE(ifs.eof()); + } + + { + RotatableFileWriter writer; + RotatableFileWriter::Use writerUse(&writer); + ASSERT_OK(writerUse.setFileName(logFileName, true)); + ASSERT_TRUE(writerUse.stream() << "Level 5 message." << std::endl); + ASSERT_TRUE(writerUse.stream() << "Level 6 message." << std::endl); + } + + { + std::ifstream ifs(logFileName.c_str()); + ASSERT_TRUE(ifs.is_open()); + ASSERT_TRUE(ifs.good()); + std::string input; + ASSERT_TRUE(std::getline(ifs, input)); + ASSERT_EQUALS(input, "Level 3 message."); + ASSERT_TRUE(std::getline(ifs, input)); + ASSERT_EQUALS(input, "Level 4 message."); + ASSERT_FALSE(std::getline(ifs, input).fail()); + ASSERT_EQUALS(input, "Level 5 message."); + ASSERT_TRUE(std::getline(ifs, input)); + ASSERT_EQUALS(input, "Level 6 message."); + ASSERT_TRUE(std::getline(ifs, input).fail()); + ASSERT_TRUE(ifs.eof()); + } + + { + RotatableFileWriter writer; + RotatableFileWriter::Use writerUse(&writer); + ASSERT_OK(writerUse.setFileName(logFileName, false)); + ASSERT_TRUE(writerUse.stream() << "Level 7 message." << std::endl); + ASSERT_TRUE(writerUse.stream() << "Level 8 message." << std::endl); + } + + { + std::ifstream ifs(logFileName.c_str()); + ASSERT_TRUE(ifs.is_open()); + ASSERT_TRUE(ifs.good()); + std::string input; + ASSERT_TRUE(std::getline(ifs, input)); + ASSERT_EQUALS(input, "Level 7 message."); + ASSERT_FALSE(std::getline(ifs, input).fail()); + ASSERT_EQUALS(input, "Level 8 message."); + ASSERT_TRUE(std::getline(ifs, input).fail()); + ASSERT_TRUE(ifs.eof()); + } + } + +} // namespace mongo diff --git a/pool/shard007/C++/0093599_FileSystemLocalRead.cpp b/pool/shard007/C++/0093599_FileSystemLocalRead.cpp new file mode 100644 index 0000000000000000000000000000000000000000..15ab2dc6c2ba4e23a0845435e9afa786ddabdb6b --- /dev/null +++ b/pool/shard007/C++/0093599_FileSystemLocalRead.cpp @@ -0,0 +1,207 @@ +/* + * This file is part of Micro Bench + * <https://github.com/duckmaestro/Micro-Bench>. + * + * Micro Bench is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Micro Bench is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + * + */ + + +#include "FileSystemLocalRead.h" +#include "Windows.h" +#include <cassert> +#include <sstream> +#include <iostream> + +FileSystemLocalRead::FileSystemLocalRead(StopwatchStack& ss) + : FileSystemExperiment(L"File System Local Reads", ss) +{ + _defaultNumIterations = 2; +} + +FileSystemLocalRead::~FileSystemLocalRead(void) +{ +} + +void FileSystemLocalRead::Run(void) +{ + srand((unsigned int)time(NULL)); + uint32_t sectorSize = -1; + uint32_t blockSize; + uint32_t sectorsPerBlock = 1; + StopwatchStack& ss = _stopwatch; + void* tagSeq = L"FileSystem -- Unbuffered Read Latency Synchronous"; + void* tagRand = L"FileSystem == Unbuffered Read Latency Asynchronous"; + // make sure test files are both synchronous (for sequential reads) and asynchronous (for random ones) + // create files without buffering (access disk directly) + + CreateTestFiles(); + + sectorSize = GetLogicalSectorSize(); + assert(sectorSize > 1); + + blockSize = sectorSize * sectorsPerBlock; + uint64_t log2Sector = FileSystemExperiment::GetLog2(sectorSize); + + for (int i = 0; i < 20/*numberFileSizes*/; i++) + { + // let the user at the console know we're still working. + for(int k = 0; k < i; k++) + { + std::wcout << L"."; + } + + ss.ResetTagHistory(tagSeq); //start afresh with each new file size + ss.ResetTagHistory(tagRand); + int shiftAmount = (int)(i + log2Sector); + uint64_t currentFileSize = FileSystemExperiment::GuaranteedShift(1, shiftAmount); + uint64_t estimatedSlotSize = 1 << 14; //size of a physical sector + uint64_t estimatedCacheSize = 1 << 24; //8MB buffer cache size + + // output message naming: + std::wstring seqResultName; + { + std::wstringstream temp; + temp << L"Unbuffered File Read Latency Sequential, File Size:\t" << FileSystemExperiment::GuaranteedShift(1, shiftAmount) << " bytes"; + seqResultName = temp.str(); + } + std::wstring fileName = FileSystemExperiment::GetTestFilenameBySize(currentFileSize); + HANDLE fileHandle; + // open file with NoBuffer + fileHandle = (HANDLE)FileSystemExperiment::OpenFileNoBuffering(fileName); //see "get current path link above" + // now we have an open file directly to disk, measure time to read to it + for(int j = 0; j < 10/*_defaultNumIterations*/; j++) + { + void *seqInputBuffer; + seqInputBuffer = malloc((size_t)estimatedSlotSize); + if(seqInputBuffer==NULL) + { + throw std::exception("Malloc Returned Null, not enough memory"); + } + // http://msdn.microsoft.com/en-us/library/windows/desktop/aa365541(v=vs.85).aspx + + LONG offset = (j * (int)estimatedCacheSize) % (int64_t)currentFileSize; + if(offset==0) + { + // read sequentially until we reach the end of the file, then reset at beginning + LONG repoForHighSpot=0; + if(SetFilePointer(fileHandle, offset, &repoForHighSpot, 0) == INVALID_SET_FILE_POINTER){ + HRESULT errorCode; + errorCode=GetLastError(); + throw std::exception("Set Pointer Failed"); + } + } + ss.Push(tagSeq); + + // http://msdn.microsoft.com/en-us/library/windows/desktop/aa365467(v=vs.85).aspx + DWORD amountRead; + if(!ReadFile(fileHandle, seqInputBuffer, (DWORD)estimatedSlotSize, &amountRead, NULL)) + { + HRESULT errorCode; + errorCode = GetLastError(); + throw std::exception("File Read Failed"); + } + ss.Pop(); + + free(seqInputBuffer); + } + + FileSystemExperiment::CloseFile(fileHandle); + PushResultMedianAsMicroseconds( + seqResultName, + (ss.GetTagHistory(tagSeq)), + -ss.GetOverheadSimpleAsTicks() + ); + + /************************************************************************************** + * + * Repeat with RandIO + * + ***************************************************************************************/ + + { + std::vector<uint64_t> quickVector; + uint64_t bigAmountOfBytes = FileSystemExperiment::GuaranteedShift(1, 21+log2Sector); + quickVector.push_back(bigAmountOfBytes); //2GB should be enough to clear the fileCache 8GB would make sure + CreateTestFiles(quickVector, false); //don't create it if we don't need to + std::wstring bigFileName = GetTestFilenameBySize(bigAmountOfBytes); + FileSystemExperiment::ReadEntireFile(bigFileName); + } + + + std::wstring randResultName; + { + std::wstringstream temp; + temp << L"Unbuffered File Read Latency Random, File Size:\t" << FileSystemExperiment::GuaranteedShift(1, shiftAmount) << " bytes"; + randResultName = temp.str(); + } + + // open file with NoBuffer + fileHandle = (HANDLE)FileSystemExperiment::OpenFileNoBuffering(fileName); //see "get current path link above" + + // now we have an open file directly to disk, measure time to read to it + uint32_t maxRandValue = (uint32_t) (currentFileSize / estimatedCacheSize); //can't read more slots than there are in file + for(int j=0; j < 10 /*_defaultNumIterations*/; j++) + { + void *randInputBuffer; + randInputBuffer = malloc((size_t)estimatedSlotSize); + if(randInputBuffer==NULL){ + throw std::exception("Malloc Returned Null, not enough memory"); + } + + // http://msdn.microsoft.com/en-us/library/windows/desktop/aa365541(v=vs.85).aspx + + // get random "slot" to read + LONG offset = 0; + if(maxRandValue > 1) + { + uint32_t randVal = rand() % maxRandValue; + offset = (LONG) (randVal * estimatedCacheSize); + } + LONG repoForHighSpot = 0; + if(INVALID_SET_FILE_POINTER == SetFilePointer(fileHandle, offset, &repoForHighSpot, 0)) + { + HRESULT errorCode; + errorCode = GetLastError(); + throw std::exception("Set Pointer Failed"); + } + ss.Push(tagRand); + + // http://msdn.microsoft.com/en-us/library/windows/desktop/aa365467(v=vs.85).aspx + + DWORD amountRead; + if(!ReadFile(fileHandle, randInputBuffer, (DWORD) estimatedSlotSize, &amountRead, NULL)) + { + HRESULT errorCode; + errorCode = GetLastError(); + throw std::exception("File Read Failed"); + } + ss.Pop(); + + free(randInputBuffer); + } + + FileSystemExperiment::CloseFile(fileHandle); + + PushResultMedianAsMicroseconds( + randResultName, + (ss.GetTagHistory(tagRand)), + -ss.GetOverheadSimpleAsTicks() + ); + } + std::wcout << L"\n" << std::endl; +} + + + diff --git a/pool/shard007/C++/0093611_utils.cc b/pool/shard007/C++/0093611_utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..87c3486775886182d3981f2a9111ac98e593915d --- /dev/null +++ b/pool/shard007/C++/0093611_utils.cc @@ -0,0 +1,56 @@ +// 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 "extensions/browser/api/bluetooth_low_energy/utils.h" + +namespace extensions { +namespace api { +namespace bluetooth_low_energy { + +namespace { + +// Converts a list of CharacteristicProperty to a base::ListValue of strings. +scoped_ptr<base::ListValue> CharacteristicPropertiesToValue( + const std::vector<CharacteristicProperty> properties) { + scoped_ptr<base::ListValue> property_list(new base::ListValue()); + for (std::vector<CharacteristicProperty>::const_iterator iter = + properties.begin(); + iter != properties.end(); + ++iter) + property_list->Append(new base::StringValue(ToString(*iter))); + return property_list.Pass(); +} + +} // namespace + +scoped_ptr<base::DictionaryValue> CharacteristicToValue(Characteristic* from) { + // Copy the properties. Use Characteristic::ToValue to generate the result + // dictionary without the properties, to prevent json_schema_compiler from + // failing. + std::vector<CharacteristicProperty> properties = from->properties; + from->properties.clear(); + scoped_ptr<base::DictionaryValue> to = from->ToValue(); + to->SetWithoutPathExpansion( + "properties", CharacteristicPropertiesToValue(properties).release()); + return to.Pass(); +} + +scoped_ptr<base::DictionaryValue> DescriptorToValue(Descriptor* from) { + // Copy the characteristic properties and set them later manually. + std::vector<CharacteristicProperty> properties = + from->characteristic.properties; + from->characteristic.properties.clear(); + scoped_ptr<base::DictionaryValue> to = from->ToValue(); + + base::DictionaryValue* chrc_value = NULL; + to->GetDictionaryWithoutPathExpansion("characteristic", &chrc_value); + DCHECK(chrc_value); + chrc_value->SetWithoutPathExpansion( + "properties", CharacteristicPropertiesToValue(properties).release()); + return to.Pass(); +} + +} // namespace bluetooth_low_energy +} // namespace api +} // namespace extensions diff --git a/pool/shard007/C++/0093612_pathManager.cpp b/pool/shard007/C++/0093612_pathManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..459eecd59e0102b72efcb01e2bd787162608eb70 --- /dev/null +++ b/pool/shard007/C++/0093612_pathManager.cpp @@ -0,0 +1,275 @@ +//! \file +/* +** Copyright (C) - Triton +** +** This program is under the terms of the Apache License 2.0. +*/ + +#include <triton/astContext.hpp> +#include <triton/exceptions.hpp> +#include <triton/pathManager.hpp> +#include <triton/symbolicEnums.hpp> + + + +namespace triton { + namespace engines { + namespace symbolic { + + PathManager::PathManager(const triton::modes::SharedModes& modes, const triton::ast::SharedAstContext& astCtxt) + : modes(modes), astCtxt(astCtxt) { + } + + + PathManager::PathManager(const PathManager& other) + : modes(other.modes), astCtxt(other.astCtxt) { + this->pathConstraints = other.pathConstraints; + } + + + PathManager& PathManager::operator=(const PathManager& other) { + this->astCtxt = other.astCtxt; + this->modes = other.modes; + this->pathConstraints = other.pathConstraints; + return *this; + } + + + triton::usize PathManager::getSizeOfPathConstraints(void) const { + return this->pathConstraints.size(); + } + + + /* Returns the logical conjunction vector of path constraint */ + const std::vector<triton::engines::symbolic::PathConstraint>& PathManager::getPathConstraints(void) const { + return this->pathConstraints; + } + + + /* Returns the logical conjunction vector of path constraint of a given thread */ + std::vector<triton::engines::symbolic::PathConstraint> PathManager::getPathConstraintsOfThread(triton::uint32 threadId) const { + std::vector<triton::engines::symbolic::PathConstraint> ret; + + for (auto& pc : this->pathConstraints) { + if (pc.getThreadId() == threadId) { + ret.push_back(pc); + } + } + + return ret; + } + + + /* Returns the logical conjunction vector of path constraint from a given range */ + std::vector<triton::engines::symbolic::PathConstraint> PathManager::getPathConstraints(triton::usize start, triton::usize end) const { + triton::usize pcsize = this->getSizeOfPathConstraints(); + + if (start > pcsize) { + return {}; + } + + if (start < pcsize && end > pcsize) { + std::vector<triton::engines::symbolic::PathConstraint>::const_iterator first = this->pathConstraints.begin() + start; + std::vector<triton::engines::symbolic::PathConstraint>::const_iterator last = this->pathConstraints.end(); + return {first, last}; + } + + if (start < pcsize && end < pcsize && end > start) { + std::vector<triton::engines::symbolic::PathConstraint>::const_iterator first = this->pathConstraints.begin() + start; + std::vector<triton::engines::symbolic::PathConstraint>::const_iterator last = this->pathConstraints.begin() + end; + return {first, last}; + } + + throw triton::exceptions::PathManager("PathManager::getPathConstraints(): Invalid items extraction."); + } + + + /* Returns the current path predicate as an AST of logical conjunction of each taken branch. */ + triton::ast::SharedAbstractNode PathManager::getPathPredicate(void) const { + std::vector<triton::engines::symbolic::PathConstraint>::const_iterator it; + + /* by default PC is T (top) */ + auto node = this->astCtxt->equal( + this->astCtxt->bvtrue(), + this->astCtxt->bvtrue() + ); + + /* Then, we create a conjunction of path constraint */ + for (it = this->pathConstraints.begin(); it != this->pathConstraints.end(); it++) { + node = this->astCtxt->land(node, it->getTakenPredicate()); + } + + return node; + } + + + + std::vector<triton::ast::SharedAbstractNode> PathManager::getPredicatesToReachAddress(triton::uint64 addr) const { + std::vector<triton::ast::SharedAbstractNode> predicates; + + /* by default PC is T (top) */ + auto node = this->astCtxt->equal( + this->astCtxt->bvtrue(), + this->astCtxt->bvtrue() + ); + + /* Go through all path constraints */ + for (auto pc = this->pathConstraints.begin(); pc != this->pathConstraints.end(); pc++) { + auto branches = pc->getBranchConstraints(); + bool isMultib = (branches.size() >= 2); + + /* Check if one of the branch constraint may reach the targeted address */ + for (auto branch = branches.begin(); branch != branches.end(); branch++) { + /* if source branch == target, add the current path predicate */ + if (std::get<1>(*branch) == addr) { + predicates.push_back(node); + } + /* + * if dst branch == target, do the conjunction of the current + * path predicate and the branch constraint. + */ + if (std::get<2>(*branch) == addr) { + predicates.push_back(this->astCtxt->land(node, std::get<3>(*branch))); + } + /* + * if it's a direct branch (call reg, jmp reg) and not a standalone + * constraint. Try to reach the targeted address. + */ + if (isMultib == false && std::get<1>(*branch) != 0 && std::get<2>(*branch) != 0) { + if (std::get<3>(*branch)->getType() == triton::ast::EQUAL_NODE) { + auto ip = std::get<3>(*branch)->getChildren()[0]; + predicates.push_back(this->astCtxt->land(node, this->astCtxt->equal(ip, this->astCtxt->bv(addr, ip->getBitvectorSize())))); + } + } + } /* branch constraints */ + + /* Continue to create the conjunction of the current path predicate */ + node = this->astCtxt->land(node, pc->getTakenPredicate()); + } /* path constraint */ + + return predicates; + } + + + /* Pushs constraints of a branch instruction to the path predicate. */ + void PathManager::pushPathConstraint(const triton::arch::Instruction& inst, const triton::engines::symbolic::SharedSymbolicExpression& expr) { + triton::engines::symbolic::PathConstraint pco; + triton::uint64 srcAddr = 0; + triton::uint64 dstAddr = 0; + triton::uint32 size = 0; + + triton::ast::SharedAbstractNode pc = expr->getAst(); + if (pc == nullptr) + throw triton::exceptions::PathManager("PathManager::pushPathConstraint(): The node cannot be null."); + + /* If PC_TRACKING_SYMBOLIC is enabled, Triton will track path constraints only if they are symbolized. */ + if (this->modes->isModeEnabled(triton::modes::PC_TRACKING_SYMBOLIC) && !pc->isSymbolized()) + return; + + /* If ONLY_ON_TAINTED is enabled and the expression untainted, Triton will skip the storing process. */ + if (this->modes->isModeEnabled(triton::modes::ONLY_ON_TAINTED) && !expr->isTainted) + return; + + /* Basic block taken */ + srcAddr = inst.getAddress(); + dstAddr = pc->evaluate().convert_to<triton::uint64>(); + size = pc->getBitvectorSize(); + + if (size == 0) + throw triton::exceptions::PathManager("PathManager::pushPathConstraint(): The node size cannot be zero."); + + if (pc->getType() == triton::ast::ZX_NODE) + pc = pc->getChildren()[1]; + + /* Setting the thread id */ + pco.setThreadId(inst.getThreadId()); + + /* Multiple branches */ + if (pc->getType() == triton::ast::ITE_NODE) { + /* Condition */ + triton::ast::SharedAbstractNode cond = pc->getChildren()[0]; + + /* Then */ + triton::uint64 bb1 = pc->getChildren()[1]->evaluate().convert_to<triton::uint64>(); + triton::ast::SharedAbstractNode bb1pc = cond; + + /* Else */ + triton::uint64 bb2 = pc->getChildren()[2]->evaluate().convert_to<triton::uint64>(); + triton::ast::SharedAbstractNode bb2pc = this->astCtxt->lnot(cond); + + /* Branch A */ + pco.addBranchConstraint( + bb1 == dstAddr, /* is taken ? */ + srcAddr, /* from */ + bb1, /* to */ + bb1pc /* expr which must be true to take the branch */ + ); + + /* Branch B */ + pco.addBranchConstraint( + bb2 == dstAddr, /* is taken ? */ + srcAddr, /* from */ + bb2, /* to */ + bb2pc /* expr which must be true to take the branch */ + ); + + this->pathConstraints.push_back(pco); + } + + /* Direct branch */ + else { + pco.addBranchConstraint( + true, /* always taken */ + srcAddr, /* from */ + dstAddr, /* to */ + /* expr which must be true to take the branch */ + this->astCtxt->equal(pc, this->astCtxt->bv(dstAddr, size)) + ); + this->pathConstraints.push_back(pco); + } + } + + + /* Pushes constraint created from node to the current path predicate. */ + void PathManager::pushPathConstraint(const triton::ast::SharedAbstractNode& node) { + triton::engines::symbolic::PathConstraint pco; + + if (node->isLogical() == false) + throw triton::exceptions::PathManager("PathManager::pushPathConstraint(): The node must be a logical node."); + + /* If PC_TRACKING_SYMBOLIC is enabled, Triton will track path constraints only if they are symbolized. */ + if (this->modes->isModeEnabled(triton::modes::PC_TRACKING_SYMBOLIC) && !node->isSymbolized()) + return; + + pco.addBranchConstraint( + true, /* always taken */ + 0, /* from: not used */ + 0, /* to: not used */ + node /* expr which must be true to take the branch */ + ); + + this->pathConstraints.push_back(pco); + } + + + /* Pushes constraint to the current path predicate. */ + void PathManager::pushPathConstraint(const triton::engines::symbolic::PathConstraint& pco) { + this->pathConstraints.push_back(pco); + } + + + /* Pops the last constraints added to the path predicate. */ + void PathManager::popPathConstraint(void) { + if (this->pathConstraints.size()) + this->pathConstraints.pop_back(); + } + + + /* Clears the current path predicate. */ + void PathManager::clearPathConstraints(void) { + this->pathConstraints.clear(); + } + + }; /* symbolic namespace */ + }; /* engines namespace */ +}; /*triton namespace */ diff --git a/pool/shard007/C++/0093621_passreftoobj.cpp b/pool/shard007/C++/0093621_passreftoobj.cpp new file mode 100644 index 0000000000000000000000000000000000000000..946383b854d7938c905f199847419028f4add9be --- /dev/null +++ b/pool/shard007/C++/0093621_passreftoobj.cpp @@ -0,0 +1,80 @@ +//Listing 12.3 +// Passing references to objects +#include <iostream> +using namespace std; + +class SimpleCat +{ + + public: + SimpleCat(); + SimpleCat(SimpleCat&); + ~SimpleCat(); + int GetAge() const { return itsAge; } + void SetAge(int age) { itsAge = age; } + + private: + int itsAge; +}; + + + + SimpleCat::SimpleCat(){ + + cout << "Simple Cat Constructor...\n"; + itsAge = 1; +} + +SimpleCat::SimpleCat(SimpleCat&){ + + cout << "Simple Cat Copy Constructor...\n"; + +} + +SimpleCat::~SimpleCat(){ + + cout << "Simple Cat Destructor...\n"; + +} + +const SimpleCat & FunctionTwo (const SimpleCat & theCat); + +int main(int argc, char *argv[]){ + + cout << "Making a cat...\n"; + + SimpleCat Frisky; + + cout << "Frisky is " << Frisky.GetAge() + << " years old\n"; + + int age = 5; + Frisky.SetAge(age); + + cout << "Frisky is " << Frisky.GetAge() + << " years old\n"; + + cout << "Calling FunctionTwo...\n"; + + FunctionTwo(Frisky); + + cout << "Frisky is " << Frisky.GetAge() + << " years old\n"; + + return 0; + + } + + + + // functionTwo passes a ref to a const object + +const SimpleCat & FunctionTwo (const SimpleCat & theCat){ + cout << "Function Two. Returning...\n"; + cout << "Frisky is now " << theCat.GetAge() + << " years old \n"; + + // theCat.SetAge(8); const! + + return theCat; +} \ No newline at end of file diff --git a/pool/shard007/C++/0093623_Logger.cpp b/pool/shard007/C++/0093623_Logger.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e23050aefa401623e28056e85e4ae8f7b93b6e14 --- /dev/null +++ b/pool/shard007/C++/0093623_Logger.cpp @@ -0,0 +1,267 @@ +/* + * OpenBTS provides an open source alternative to legacy telco protocols and + * traditionally complex, proprietary hardware systems. + * + * Copyright 2009, 2010 Free Software Foundation, Inc. + * Copyright 2010 Kestrel Signal Processing, Inc. + * Copyright 2011-2014 Range Networks, Inc. + * + * This software is distributed under the terms of the GNU Affero General + * Public License version 3. See the COPYING and NOTICE files in the main + * directory for licensing information. + * + * This use of this software may be subject to additional restrictions. + * See the LEGAL file in the main directory for details. + */ + + +#include <string.h> +#include <cstdio> +#include <fstream> +#include <string> +#include <stdarg.h> + +#include "Configuration.h" +#include "Logger.h" +#include "Threads.h" // pat added + + +using namespace std; + +// Reference to a global config table, used all over the system. +extern ConfigurationTable gConfig; + + +/**@ The global alarms table. */ +//@{ +Mutex alarmsLock; +list<string> alarmsList; +void addAlarm(const string&); +//@} + + + +// (pat) If Log messages are printed before the classes in this module are inited +// (which happens when static classes have constructors that do work) +// the OpenBTS just crashes. +// Prevent that by setting sLoggerInited to true when this module is inited. +static bool sLoggerInited = 0; +static struct CheckLoggerInitStatus { + CheckLoggerInitStatus() { sLoggerInited = 1; } +} sCheckloggerInitStatus; + + + +/** Names of the logging levels. */ +const char *levelNames[] = { + "EMERG", "ALERT", "CRIT", "ERR", "WARNING", "NOTICE", "INFO", "DEBUG" +}; +int numLevels = 8; +bool gLogToConsole = 0; +FILE *gLogToFile = NULL; +Mutex gLogToLock; + + +int levelStringToInt(const string& name) +{ + // Reverse search, since the numerically larger levels are more common. + for (int i=numLevels-1; i>=0; i--) { + if (name == levelNames[i]) return i; + } + + // Common substitutions. + if (name=="INFORMATION") return 6; + if (name=="WARN") return 4; + if (name=="ERROR") return 3; + if (name=="CRITICAL") return 2; + if (name=="EMERGENCY") return 0; + + // Unknown level. + return -1; +} + +/** Given a string, return the corresponding level name. */ +int lookupLevel(const string& key) +{ + string val = gConfig.getStr(key); + int level = levelStringToInt(val); + + if (level == -1) { + string defaultLevel = gConfig.mSchema["Log.Level"].getDefaultValue(); + level = levelStringToInt(defaultLevel); + _LOG(CRIT) << "undefined logging level (" << key << " = \"" << val << "\") defaulting to \"" << defaultLevel << ".\" Valid levels are: EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO or DEBUG"; + gConfig.set(key, defaultLevel); + } + + return level; +} + + +int getLoggingLevel(const char* filename) +{ + // Default level? + if (!filename) return lookupLevel("Log.Level"); + + // This can afford to be inefficient since it is not called that often. + const string keyName = string("Log.Level.") + string(filename); + if (gConfig.defines(keyName)) return lookupLevel(keyName); + return lookupLevel("Log.Level"); +} + + + +int gGetLoggingLevel(const char* filename) +{ + // This is called a lot and needs to be efficient. + + static Mutex sLogCacheLock; + static map<uint64_t,int> sLogCache; + static unsigned sCacheCount; + static const unsigned sCacheRefreshCount = 1000; + + if (filename==NULL) return gGetLoggingLevel(""); + + HashString hs(filename); + uint64_t key = hs.hash(); + + sLogCacheLock.lock(); + // Time for a cache flush? + if (sCacheCount>sCacheRefreshCount) { + sLogCache.clear(); + sCacheCount=0; + } + // Is it cached already? + map<uint64_t,int>::const_iterator where = sLogCache.find(key); + sCacheCount++; + if (where!=sLogCache.end()) { + int retVal = where->second; + sLogCacheLock.unlock(); + return retVal; + } + // Look it up in the config table and cache it. + // FIXME: Figure out why unlock and lock below fix the config table deadlock. + // (pat) Probably because getLoggingLevel may call LOG recursively via lookupLevel(). + sLogCacheLock.unlock(); + int level = getLoggingLevel(filename); + sLogCacheLock.lock(); + sLogCache.insert(pair<uint64_t,int>(key,level)); + sLogCacheLock.unlock(); + return level; +} + + + + + +// copies the alarm list and returns it. list supposed to be small. +list<string> gGetLoggerAlarms() +{ + alarmsLock.lock(); + list<string> ret; + // excuse the "complexity", but to use std::copy with a list you need + // an insert_iterator - copy technically overwrites, doesn't insert. + insert_iterator< list<string> > ii(ret, ret.begin()); + copy(alarmsList.begin(), alarmsList.end(), ii); + alarmsLock.unlock(); + return ret; +} + +/** Add an alarm to the alarm list. */ +void addAlarm(const string& s) +{ + alarmsLock.lock(); + alarmsList.push_back(s); + unsigned maxAlarms = gConfig.getNum("Log.Alarms.Max"); + while (alarmsList.size() > maxAlarms) alarmsList.pop_front(); + alarmsLock.unlock(); +} + + +Log::~Log() +{ + if (mDummyInit) return; + // Anything at or above LOG_CRIT is an "alarm". + // Save alarms in the local list and echo them to stderr. + if (mPriority <= LOG_CRIT) { + if (sLoggerInited) addAlarm(mStream.str().c_str()); + cerr << mStream.str() << endl; + } + // Current logging level was already checked by the macro. + // So just log. + syslog(mPriority, "%s", mStream.str().c_str()); + // pat added for easy debugging. + if (gLogToConsole||gLogToFile) { + int mlen = mStream.str().size(); + int neednl = (mlen==0 || mStream.str()[mlen-1] != '\n'); + gLogToLock.lock(); + if (gLogToConsole) { + // The COUT() macro prevents messages from stomping each other but adds uninteresting thread numbers, + // so just use std::cout. + std::cout << mStream.str(); + if (neednl) std::cout<<"\n"; + } + if (gLogToFile) { + fputs(mStream.str().c_str(),gLogToFile); + if (neednl) {fputc('\n',gLogToFile);} + fflush(gLogToFile); + } + gLogToLock.unlock(); + } +} + + +Log::Log(const char* name, const char* level, int facility) +{ + mDummyInit = true; + gLogInit(name, level, facility); +} + + +ostringstream& Log::get() +{ + assert(mPriority<numLevels); + mStream << levelNames[mPriority] << ' '; + return mStream; +} + + + +void gLogInit(const char* name, const char* level, int facility) +{ + // Set the level if one has been specified. + if (level) { + gConfig.set("Log.Level",level); + } + + // Pat added, tired of the syslog facility. + // Both the transceiver and OpenBTS use this same facility, but only OpenBTS/OpenBTS-UMTS may use this log file: + string str = gConfig.getStr("Log.File"); + if (gLogToFile==0 && str.length() && 0==strncmp(gCmdName,"Open",4)) { + const char *fn = str.c_str(); + if (fn && *fn && strlen(fn)>3) { // strlen because a garbage char is getting in sometimes. + gLogToFile = fopen(fn,"w"); // New log file each time we start. + if (gLogToFile) { + time_t now; + time(&now); + fprintf(gLogToFile,"Starting at %s",ctime(&now)); + fflush(gLogToFile); + std::cout << "Logging to file: " << fn << "\n"; + } + } + } + + // Open the log connection. + openlog(name,0,facility); +} + + +void gLogEarly(int level, const char *fmt, ...) +{ + va_list args; + + va_start(args, fmt); + vsyslog(level | LOG_USER, fmt, args); + va_end(args); +} + +// vim: ts=4 sw=4 diff --git a/pool/shard007/C++/0093628_cluster_extraction.cpp b/pool/shard007/C++/0093628_cluster_extraction.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb6eaf28347ba73f444ad6d76a3e2a94be80db42 --- /dev/null +++ b/pool/shard007/C++/0093628_cluster_extraction.cpp @@ -0,0 +1,120 @@ +/* Author Bastian Steder +From the PCL tutorials +Program to extract clusters from a PCD File +Important Parameters: Distance Threshold, Cluster Tolerance and Size +The Default Values are commented */ +// Luiz Felipe + +#include <pcl/ModelCoefficients.h> +#include <pcl/point_types.h> +#include <pcl/io/pcd_io.h> +#include <pcl/filters/extract_indices.h> +#include <pcl/filters/voxel_grid.h> +#include <pcl/features/normal_3d.h> +#include <pcl/kdtree/kdtree.h> +#include <pcl/sample_consensus/method_types.h> +#include <pcl/sample_consensus/model_types.h> +#include <pcl/segmentation/sac_segmentation.h> +#include <pcl/segmentation/extract_clusters.h> + + +int +main (int argc, char** argv) +{ + // Read in the cloud data + pcl::PCDReader reader; + pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>), cloud_f (new pcl::PointCloud<pcl::PointXYZ>); + + // DELETE LATER + pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered (new pcl::PointCloud<pcl::PointXYZ>); + + reader.read ("paper_pcd_0.pcd", *cloud_filtered); +// reader.read ("rock_pcd_0.pcd", *cloud); + + std::cout << "PointCloud before filtering has: " << cloud_filtered->points.size () << " data points." << std::endl; //* change later back to cloud + + +/* NO FILTER BECAUSE SMALL CLOUD DATA + + // Create the filtering object: downsample the dataset using a leaf size of 1cm + pcl::VoxelGrid<pcl::PointXYZ> vg; +//pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered (new pcl::PointCloud<pcl::PointXYZ>); + vg.setInputCloud (cloud); + vg.setLeafSize (0.01f, 0.01f, 0.01f); + vg.filter (*cloud_filtered); + std::cout << "PointCloud after filtering has: " << cloud_filtered->points.size () << " data points." << std::endl; //* + + END NO FILTER*/ + + // Create the segmentation object for the planar model and set all the parameters + pcl::SACSegmentation<pcl::PointXYZ> seg; + pcl::PointIndices::Ptr inliers (new pcl::PointIndices); + pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients); + pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_plane (new pcl::PointCloud<pcl::PointXYZ> ()); + pcl::PCDWriter writer; + seg.setOptimizeCoefficients (true); + seg.setModelType (pcl::SACMODEL_PLANE); + seg.setMethodType (pcl::SAC_RANSAC); + seg.setMaxIterations (100); //100 + seg.setDistanceThreshold (0.005); //0.02 + + int i=0, nr_points = (int) cloud_filtered->points.size (); + while (cloud_filtered->points.size () > 0.3 * nr_points) + { + // Segment the largest planar component from the remaining cloud + seg.setInputCloud (cloud_filtered); + seg.segment (*inliers, *coefficients); + if (inliers->indices.size () == 0) + { + std::cout << "Could not estimate a planar model for the given dataset." << std::endl; + break; + } + + // Extract the planar inliers from the input cloud + pcl::ExtractIndices<pcl::PointXYZ> extract; + extract.setInputCloud (cloud_filtered); + extract.setIndices (inliers); + extract.setNegative (false); + + // Get the points associated with the planar surface + extract.filter (*cloud_plane); + std::cout << "PointCloud representing the planar component: " << cloud_plane->points.size () << " data points." << std::endl; + + // Remove the planar inliers, extract the rest + extract.setNegative (true); + extract.filter (*cloud_f); + *cloud_filtered = *cloud_f; + } + + // Creating the KdTree object for the search method of the extraction + pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>); + tree->setInputCloud (cloud_filtered); + + std::vector<pcl::PointIndices> cluster_indices; + pcl::EuclideanClusterExtraction<pcl::PointXYZ> ec; + ec.setClusterTolerance (0.5); // 2cm + ec.setMinClusterSize (10); + ec.setMaxClusterSize (5000); + ec.setSearchMethod (tree); + ec.setInputCloud (cloud_filtered); + ec.extract (cluster_indices); + + int j = 0; + for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin (); it != cluster_indices.end (); ++it) + { + pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_cluster (new pcl::PointCloud<pcl::PointXYZ>); + for (std::vector<int>::const_iterator pit = it->indices.begin (); pit != it->indices.end (); pit++) + cloud_cluster->points.push_back (cloud_filtered->points[*pit]); //* + cloud_cluster->width = cloud_cluster->points.size (); + cloud_cluster->height = 1; + cloud_cluster->is_dense = true; + + std::cout << "PointCloud representing the Cluster: " << cloud_cluster->points.size () << " data points." << std::endl; + std::stringstream ss; + ss << "cloud_cluster_" << j << ".pcd"; + writer.write<pcl::PointXYZ> (ss.str (), *cloud_cluster, false); //* + j++; + } + + return (0); +} diff --git a/pool/shard007/C++/0093631_ui_progressbar.cpp b/pool/shard007/C++/0093631_ui_progressbar.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c69ab40f2eb16cccbbf35fda6157937ab531b37f --- /dev/null +++ b/pool/shard007/C++/0093631_ui_progressbar.cpp @@ -0,0 +1,89 @@ +#include "ui_progressbar.h" + +#include <util\container.h> +#include <util\math_base.h> + +#include "util_sprite.h" + +const std::string UIProgressbar::BOTTOM_ANIM_ = "_bottom"; +const std::string UIProgressbar::MID_ANIM_ = "_mid"; +const std::string UIProgressbar::TOP_ANIM_ = "_top"; + +UIProgressbar::UIProgressbar() +: hasMidAnim_() +, maxValue_(100.f) +, curValue_() +{ + +} + +void UIProgressbar::Update(float delta) +{ + if (!visibled_) + return; + + __super::Update(delta); + + UTIL_FOREACH(i, anims_, Anims) + i->second.Update(delta); +} + +void UIProgressbar::Render(RenderTarget& target) const +{ + if (!visibled_) + return; + + UTIL_FOREACH(i, anims_, Anims) + target.Draw(i->second); + + __super::Render(target); +} + +void UIProgressbar::PostSetTopLeft() +{ + __super::PostSetTopLeft(); + if (hasMidAnim_) + anims_[MID_ANIM_].SetX(GetLeft()); +} + +void UIProgressbar::PostSetWidthHeight() +{ + __super::PostSetWidthHeight(); + UpdateMidAnim(); +} + +void UIProgressbar::PostSetAnim(const std::string name, Animation& anim) +{ + __super::PostSetAnim(name, anim); + + if (name == MID_ANIM_) + { + hasMidAnim_ = true; + UpdateMidAnim(); + SetCenter(anims_[MID_ANIM_], 0.f, 0.5f); + anims_[MID_ANIM_].SetX(GetLeft()); + } +} + +void UIProgressbar::UpdateMidAnim() +{ + if (!hasMidAnim_) + return; + + Vector2f size = GetWidthHeight(); + size.x *= curValue_ / maxValue_; + size.x = util::ClamUp(size.x, 1.f); // 下限 1 像素,size.x <= 0 则在 SFML 内部不作处理 + anims_[MID_ANIM_].Resize(size); +} + +void UIProgressbar::SetMaxValue(float val) +{ + maxValue_ = val; + UpdateMidAnim(); +} + +void UIProgressbar::SetCurValue(float val) +{ + curValue_ = val; + UpdateMidAnim(); +} diff --git a/pool/shard007/C++/0093645_music_room.cpp b/pool/shard007/C++/0093645_music_room.cpp new file mode 100644 index 0000000000000000000000000000000000000000..34217de18467e4b72660dc1fe30b3f74eb2a783a --- /dev/null +++ b/pool/shard007/C++/0093645_music_room.cpp @@ -0,0 +1,65 @@ +/* ScummVM - Graphic Adventure Engine + * + * ScummVM is the legal property of its developers, whose names + * are too numerous to list here. Please refer to the COPYRIGHT + * file distributed with this source distribution. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ + +#include "common/textconsole.h" +#include "titanic/sound/music_room.h" +#include "titanic/sound/sound.h" +#include "titanic/game_manager.h" +#include "titanic/titanic.h" + +namespace Titanic { + +CMusicHandler *CMusicRoom::_musicHandler; + +CMusicRoom::CMusicRoom(CGameManager *gameManager) : + _gameManager(gameManager) { + _sound = &_gameManager->_sound; + _items.resize(4); +} + +CMusicRoom::~CMusicRoom() { + destroyMusicHandler(); +} + +CMusicHandler *CMusicRoom::createMusicHandler() { + if (_musicHandler) + destroyMusicHandler(); + + _musicHandler = new CMusicHandler(_gameManager->_project, &_sound->_soundManager); + return _musicHandler; +} + +void CMusicRoom::destroyMusicHandler() { + delete _musicHandler; + _musicHandler = nullptr; +} + +void CMusicRoom::startMusic(int musicId) { + // TODO +} + +void CMusicRoom::stopMusic() { + if (_musicHandler) + _musicHandler->stop(); +} + +} // End of namespace Titanic diff --git a/pool/shard007/C++/0093646_Flattening_a_Linked_List.cpp b/pool/shard007/C++/0093646_Flattening_a_Linked_List.cpp new file mode 100644 index 0000000000000000000000000000000000000000..343d2d1e41de6ff87e64b5d59e782ba5182cbedb --- /dev/null +++ b/pool/shard007/C++/0093646_Flattening_a_Linked_List.cpp @@ -0,0 +1,20 @@ +Node * merge(Node * a, Node * b){ + if(a == NULL) return b; + if(b == NULL) return a; + Node * mergedLL = new Node; + if(a->data < b->data){ + mergedLL = a; + mergedLL->bottom = merge(a->bottom, b); + } + else{ + mergedLL = b; + mergedLL->bottom = merge(a, b->bottom); + } + return mergedLL; +} + +Node *flatten(Node *root) +{ + if(root == NULL || root->next == NULL) return root; + return merge(root, flatten(root->next)); +} diff --git a/pool/shard007/C++/0093652_MonteCarlo.cpp b/pool/shard007/C++/0093652_MonteCarlo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cf95ab3999816121634668577257660bca6cad2e --- /dev/null +++ b/pool/shard007/C++/0093652_MonteCarlo.cpp @@ -0,0 +1,75 @@ +#include <pnp/learning_plan/algo/MonteCarlo.h> + +#include <iostream> +#include <cmath> + +using namespace std; + +namespace learnpnp { + +MonteCarlo::MonteCarlo ( const std::string &filePath, const MonteCarlo::ParamType& parameters ) : + Learner ( filePath, parameters.initialValue ), + e(), + accumulatedV(), + par ( parameters ), + ticks ( 1 ), + scheduler ( new ConstantAlpha ( parameters.alpha ) ) {} + +MonteCarlo::MonteCarlo ( const std::string &filePath, const ParamType& parameters, AlphaScheduler *sched ) : + Learner ( filePath, parameters.initialValue ), + e(), + accumulatedV(), + par ( parameters ), + ticks ( 1 ), + scheduler ( sched ) {} + + +void MonteCarlo::updateV ( const Marking ¤t, double reward,const Marking &next ) { + + if ( accumulatedV.find ( current ) == accumulatedV.end() ) + accumulatedV.insert ( make_pair ( current,.0 ) ); + + e[current] = 1; + + std::map<Marking, double>::iterator VIt = accumulatedV.begin(); + + for ( ; VIt != accumulatedV.end(); ++VIt ) { + const Marking &s = ( *VIt ).first; + double &accumulatedV_s = ( *VIt ).second; + double &e_s = e[s]; //see comment on TDLambda + + accumulatedV_s += reward * e_s; + e_s *= pow ( par.gamma,ticks ) ; + } + + ticks = 1; +} + +void MonteCarlo::tick() { + ++ticks; +} + +void MonteCarlo::finalizeV() { + + std::map<Marking, double>::iterator VIt = accumulatedV.begin(); + + for ( ; VIt != accumulatedV.end(); ++VIt ) { + + const Marking &s = ( *VIt ).first; + const double &accumulatedV_s = ( *VIt ).second; + + scheduler->visited ( s ); + +// std::cout << "V= " << V_s << "accumulatedV= " << accumulatedV_s << std::endl; + setValueOf ( s, valueOf ( s ) + scheduler->alpha ( s ) * ( accumulatedV_s - valueOf ( s ) ) ); +// std::cout << "V= " << V_s << std::endl; + } + +} + + +MonteCarlo::~MonteCarlo() { + delete scheduler; +} + +} diff --git a/pool/shard007/C++/0093656_vuMeter.cpp b/pool/shard007/C++/0093656_vuMeter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b93dd4bab3baaf82c57d23bcaed261571a3ba52f --- /dev/null +++ b/pool/shard007/C++/0093656_vuMeter.cpp @@ -0,0 +1,208 @@ +#include "VuMeter.h" + +#include <QtGui/QPainter> + +namespace Limitless +{ + +VuMeter::VuMeter(QWidget *parent): QWidget(parent) +{ + m_backgroundColor=QColor(0, 0, 0); + m_cellColor=QColor(80, 80, 80); + + m_highColor=Qt::red; + m_color=Qt::yellow; + m_lowColor=Qt::green; + + m_maxiumValue=1.0f; + m_minimumValue=0.0f; + m_value=0.0f; + + m_cells=40; + m_vertical=true; +} + +QSize VuMeter::minimumSizeHint() const +{ + QSize size; + + if(m_vertical) + { + size.setHeight(m_cells*4+1); + size.setWidth(6); + } + else + { + size.setWidth(m_cells*4+1); + size.setHeight(6); + } + + return size; +} + +QSize VuMeter::sizeHint() const +{ + QSize size; + + if(m_vertical) + { + size.setHeight(m_cells*4+3); + size.setWidth(8); + } + else + { + size.setWidth(m_cells*4+3); + size.setHeight(8); + } + + return size; +} + +void VuMeter::setVertical(bool value) +{ + m_vertical=value; + + if(value) + { + setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); + } + else + { + setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); + } + setMinimumSize(minimumSizeHint()); +} + +void VuMeter::setValue(float value) +{ + m_value=value; + update(); +} + +void VuMeter::paintEvent(QPaintEvent *event) +{ + if(m_vertical) + paintVertical(); + else + paintHorizontal(); +} + +void VuMeter::paintVertical() +{ + QPainter painter(this); + QRect rect=painter.window(); + + painter.setRenderHint(QPainter::Antialiasing); + + int cellSpacers=m_cells+1; + int height=rect.height()-cellSpacers; //need minum 1 pixel space between blocks + int cellHeight=height/m_cells; + + int extra=(rect.height()-(cellHeight*m_cells)-cellSpacers)/2; + + painter.setBrush(m_backgroundColor); + painter.drawRect(rect); + + int cellIndex=ceil(m_value*m_cells); + int colorIndex=ceil(0.70*m_cells); + int highColorIndex=ceil(0.90*m_cells); + + if(cellIndex < 0) + cellIndex=0; + else if(cellIndex > m_cells) + cellIndex=m_cells; + + QRect cellRect(rect.x()+1, rect.height()-cellHeight-extra-1, rect.width()-2, cellHeight); + QColor currentColor=m_lowColor; + int changeIndex=colorIndex; + + painter.setBrush(m_lowColor); + for(size_t i=0; i<cellIndex; ++i) + { + if(i>=changeIndex) + { + if(changeIndex==colorIndex) + { + painter.setBrush(m_color); + changeIndex=highColorIndex; + } + else if(changeIndex==highColorIndex) + { + painter.setBrush(m_highColor); + changeIndex=m_cells; + } + } + + painter.drawRect(cellRect); + cellRect.setBottom(cellRect.y()-1); + cellRect.setTop(cellRect.y()-cellHeight-1); + } + + painter.setBrush(m_cellColor); + for(size_t i=cellIndex; i<m_cells; ++i) + { + painter.drawRect(cellRect); + cellRect.setBottom(cellRect.y()-1); + cellRect.setTop(cellRect.y()-cellHeight-1); + } +} + +void VuMeter::paintHorizontal() +{ + QPainter painter(this); + QRect rect=painter.window(); + + painter.setRenderHint(QPainter::Antialiasing); + + int cellSpacers=m_cells+1; + int width=rect.width()-cellSpacers; //need minum 1 pixel space between blocks + int cellWidth=width/m_cells; + + int extra=(rect.width()-(cellWidth*m_cells)-cellSpacers)/2; + + painter.setBrush(m_backgroundColor); + painter.drawRect(rect); + + int cellIndex=ceil(m_value*m_cells); + int colorIndex=ceil(0.5*m_cells); + int highColorIndex=ceil(0.75*m_cells); + + if(cellIndex < 0) + cellIndex=0; + else if(cellIndex > m_cells) + cellIndex=m_cells; + + QRect cellRect(rect.left(), rect.y()+1, cellWidth, rect.height()-2); + QColor currentColor=m_lowColor; + int changeIndex=colorIndex; + + painter.setBrush(m_lowColor); + for(size_t i=0; i<cellIndex; ++i) + { + if(i>=changeIndex) + { + if(changeIndex==colorIndex) + { + painter.setBrush(m_color); + changeIndex=highColorIndex; + } + else if(changeIndex==highColorIndex) + { + painter.setBrush(m_highColor); + changeIndex=m_cells; + } + } + + painter.drawRect(cellRect); + cellRect.translate(cellWidth+1, 0); + } + + painter.setBrush(m_cellColor); + for(size_t i=cellIndex; i<m_cells; ++i) + { + painter.drawRect(cellRect); + cellRect.translate(cellWidth+1, 0); + } +} + +}//namespace Limitless \ No newline at end of file diff --git a/pool/shard007/C++/0093658_fx_ufixed_limits_long.cpp b/pool/shard007/C++/0093658_fx_ufixed_limits_long.cpp new file mode 100644 index 0000000000000000000000000000000000000000..821afab7739b78c578887c86c7a3aa1971401458 --- /dev/null +++ b/pool/shard007/C++/0093658_fx_ufixed_limits_long.cpp @@ -0,0 +1,115 @@ +/***************************************************************************** + + Licensed to Accellera Systems Initiative Inc. (Accellera) under one or + more contributor license agreements. See the NOTICE file distributed + with this work for additional information regarding copyright ownership. + Accellera licenses this file to you under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with the + License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + + *****************************************************************************/ + +/***************************************************************************** + + fx_ufixed_limits_long.cpp -- + + Original Author: Martin Janssen, Synopsys, Inc., 2002-02-15 + + *****************************************************************************/ + +/***************************************************************************** + + MODIFICATION LOG - modifiers, enter your name, affiliation, date and + changes you are making here. + + Name, Affiliation, Date: + Description of Modification: + + *****************************************************************************/ + +// This may look like C code, but it is really -*- C++ -*- +// +// fx_ufixed<8, 5>_limits.cxx -- +// Copyright Synopsys 1998 +// Author : Ric Hilderink +// Created On : Fri Jan 8 14:30:41 1999 +// Status : none +// + + +#include <limits.h> +#include <float.h> +#include <math.h> +#define SC_INCLUDE_FX +#include "systemc.h" + +#define SHOW(a) out << #a << " : " << a.to_string(SC_HEX) << "\n" +#define SHOW_EXP(a) { res = a; out << #a << " : " << res.to_string(SC_HEX) << "\n"; } + + +#define SHOW_EXPRS(a, b) \ + SHOW_EXP(a b zero_min); \ + SHOW_EXP(a b zero_plus); \ + SHOW_EXP(a b zero); \ + SHOW_EXP(a b long_max); \ + SHOW_EXP(a b long_min); \ + SHOW_EXP(a b int_max); \ + SHOW_EXP(a b int_min); \ + SHOW_EXP(a b uint_max); \ + SHOW_EXP(a b ulong_max); \ + SHOW_EXP(a b double_min); \ + SHOW_EXP(a b double_max); \ + SHOW_EXP(a b float_min); \ + SHOW_EXP(a b float_max); + +#define SHOW_EXPS(a) \ + SHOW_EXPRS(a, /) \ + SHOW_EXPRS(a, *) \ + SHOW_EXPRS(a, +) \ + SHOW_EXPRS(a, -) \ + SHOW_EXPRS(a, >) \ + SHOW_EXPRS(a, <) \ + SHOW_EXPRS(a, >=) \ + SHOW_EXPRS(a, <=) \ + SHOW_EXPRS(a, ==) \ + SHOW_EXPRS(a, !=) \ + SHOW_EXPRS(a, * a *) + + +void test_fx_ufixed_limits_long(ostream& out) +{ + out << "****************** limits fx_ufixed<8, 5>_long\n"; + + sc_ufixed<8, 5> zero_min("-0"); SHOW(zero_min); + sc_ufixed<8, 5> zero_plus("+0"); SHOW(zero_plus); + sc_ufixed<8, 5> zero(0); SHOW(zero); + + sc_ufixed<8, 5> long_max(LONG_MAX); SHOW(long_max); + sc_ufixed<8, 5> long_min(LONG_MIN); SHOW(long_min); + sc_ufixed<8, 5> int_max(INT_MAX); SHOW(int_max); + sc_ufixed<8, 5> int_min(INT_MIN); SHOW(int_min); + sc_ufixed<8, 5> uint_max(UINT_MAX); SHOW(uint_max); + sc_ufixed<8, 5> ulong_max(ULONG_MAX); SHOW(ulong_max); + + sc_ufixed<8, 5> double_min(DBL_MIN); SHOW(double_min); + sc_ufixed<8, 5> double_max(DBL_MAX); SHOW(double_max); + sc_ufixed<8, 5> float_min(FLT_MIN); SHOW(float_min); + sc_ufixed<8, 5> float_max(FLT_MAX); SHOW(float_max); + + // sc_ufixed<8, 5> res; + + // SHOW_EXPS(long_max); + // SHOW_EXPS(long_min); + // SHOW_EXPS(int_max); + // SHOW_EXPS(int_min); + // SHOW_EXPS(uint_max); + // SHOW_EXPS(ulong_max); +} diff --git a/pool/shard007/C++/0093681_2.cc b/pool/shard007/C++/0093681_2.cc new file mode 100644 index 0000000000000000000000000000000000000000..98c1407427860676578829b32dcd6d3a6adbeac9 --- /dev/null +++ b/pool/shard007/C++/0093681_2.cc @@ -0,0 +1,58 @@ +// 2001-10-30 Benjamin Kosnik <bkoz@redhat.com> + +// Copyright (C) 2001-2014 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// <http://www.gnu.org/licenses/>. + +// 21.3.5 string modifiers + +#include <string> +#include <cstdio> +#include <testsuite_hooks.h> + +// assign(const basic_string& __str, size_type __pos, size_type __n) +void +test02() +{ + bool test __attribute__((unused)) = true; + + using namespace std; + + string one = "Selling England by the pound"; + string two = one; + string three = "Brilliant trees"; + + one.assign(one, 8, 100); + VERIFY( one == "England by the pound" ); + + one.assign(one, 8, 0); + VERIFY( one == "" ); + + one.assign(two, 8, 7); + VERIFY( one == "England" ); + + one.assign(three, 10, 100); + VERIFY( one == "trees" ); + + three.assign(one, 0, 3); + VERIFY( three == "tre" ); +} + +int main() +{ + test02(); + return 0; +} diff --git a/pool/shard007/C++/0093685_tcp_server.cpp b/pool/shard007/C++/0093685_tcp_server.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c08480ae8922d7960e3e7989315bb63504b3e43 --- /dev/null +++ b/pool/shard007/C++/0093685_tcp_server.cpp @@ -0,0 +1,145 @@ +#include <xdc/std.h> +#include <xdc/cfg/global.h> +#include <xdc/runtime/Error.h> +#include <xdc/runtime/System.h> + +#include <ti/sysbios/BIOS.h> +#include <ti/sysbios/knl/Task.h> +#include <ti/drivers/GPIO.h> + +extern "C" { +#include <string.h> +#include <stdio.h> +#include <sys/socket.h> +} + +#include "util/NonCopyable.h" +#include "onewire/onewire.h" + +#include "board.h" + +#define TELNET_PORT 23 + + +class CanServer : util::NonCopyable +{ +public: + CanServer(); + ~CanServer(); + + void run(); + +private: + void handle_connection(int client_fd); + +private: + int server_fd_; + bool started_; +}; + + +CanServer::CanServer() : + server_fd_(-1), + started_(false) +{ + server_fd_ = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (server_fd_ == -1) + return; + + struct ::sockaddr_in local_addr; + ::memset(&local_addr, 0, sizeof(local_addr)); + local_addr.sin_family = AF_INET; + local_addr.sin_addr.s_addr = htonl(INADDR_ANY); + local_addr.sin_port = htons(TELNET_PORT); + + if (::bind(server_fd_, reinterpret_cast<struct ::sockaddr*>(&local_addr), sizeof(local_addr)) == -1) + return; + + if (::listen(server_fd_, 1) == -1) + return; + + int optval = 1; + if (::setsockopt(server_fd_, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval)) < 0) + return; + + started_ = true; +} + +CanServer::~CanServer() +{ + if (server_fd_ != -1) + ::close(server_fd_); +} + +void CanServer::run() +{ + if (!started_) + return; + + struct ::sockaddr_in client_addr; + ::socklen_t socklen = sizeof(client_addr); + + int client_fd = -1; + while ((client_fd = ::accept(server_fd_, reinterpret_cast<struct ::sockaddr*>(&client_addr), &socklen)) != -1) + { + handle_connection(client_fd); + ::close(client_fd); + } +} + +static void send_str(int fd, const char* str) +{ + ::send(fd, str, ::strlen(str), 0); +} + +void CanServer::handle_connection(int client_fd) +{ + send_str(client_fd, "Measuring temperature...\n"); + + util::Pin rx(Board_OW_RX), tx(Board_OW_TX); + onewire::Master master(rx, tx); + + onewire::ThermometerSession session(master); + send_str(client_fd, "Issue RESET...\n"); + if (!session.reset()) + { + send_str(client_fd, "No PD pulse :(\n"); + return; + } + + onewire::UniqueId id = 0; + session.read_rom(id); + + char tmp[64]; + sprintf(tmp, "uid = 0x%llx\n", id); + send_str(client_fd, tmp); + return; + + session.skip_rom(); + + send_str(client_fd, "CONVERT T\n"); + session.convert_t(onewire::ThermometerSession::Wait); + + send_str(client_fd, "Done, now reading temperature\n"); + + if (!session.reset()) + { + send_str(client_fd, "No PD pulse :(\n"); + return; + } + + session.skip_rom(); + + onewire::Temperature t = session.read_t(); + + char buf[48]; + ::sprintf(buf, "T = %f\n", t.fp_value()); + send_str(client_fd, buf); +} + + +extern "C" +void tcp_server(UArg, UArg) +{ + CanServer().run(); +} diff --git a/pool/shard007/C++/0093690_SkColorFilterImageFilter.cpp b/pool/shard007/C++/0093690_SkColorFilterImageFilter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..acd6fac25e4a793405a87dc0f4d5559d0538b18f --- /dev/null +++ b/pool/shard007/C++/0093690_SkColorFilterImageFilter.cpp @@ -0,0 +1,160 @@ +/* + * Copyright 2012 The Android Open Source Project + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include "SkColorFilterImageFilter.h" +#include "SkBitmap.h" +#include "SkCanvas.h" +#include "SkColorMatrixFilter.h" +#include "SkDevice.h" +#include "SkColorFilter.h" +#include "SkReadBuffer.h" +#include "SkWriteBuffer.h" + +namespace { + +void mult_color_matrix(SkScalar a[20], SkScalar b[20], SkScalar out[20]) { + for (int j = 0; j < 4; ++j) { + for (int i = 0; i < 5; ++i) { + out[i+j*5] = 4 == i ? a[4+j*5] : 0; + for (int k = 0; k < 4; ++k) + out[i+j*5] += SkScalarMul(a[k+j*5], b[i+k*5]); + } + } +} + +// To detect if we need to apply clamping after applying a matrix, we check if +// any output component might go outside of [0, 255] for any combination of +// input components in [0..255]. +// Each output component is an affine transformation of the input component, so +// the minimum and maximum values are for any combination of minimum or maximum +// values of input components (i.e. 0 or 255). +// E.g. if R' = x*R + y*G + z*B + w*A + t +// Then the maximum value will be for R=255 if x>0 or R=0 if x<0, and the +// minimum value will be for R=0 if x>0 or R=255 if x<0. +// Same goes for all components. +bool component_needs_clamping(SkScalar row[5]) { + SkScalar maxValue = row[4] / 255; + SkScalar minValue = row[4] / 255; + for (int i = 0; i < 4; ++i) { + if (row[i] > 0) + maxValue += row[i]; + else + minValue += row[i]; + } + return (maxValue > 1) || (minValue < 0); +} + +bool matrix_needs_clamping(SkScalar matrix[20]) { + return component_needs_clamping(matrix) + || component_needs_clamping(matrix+5) + || component_needs_clamping(matrix+10) + || component_needs_clamping(matrix+15); +} + +}; + +SkColorFilterImageFilter* SkColorFilterImageFilter::Create(SkColorFilter* cf, + SkImageFilter* input, const CropRect* cropRect, uint32_t uniqueID) { + SkASSERT(cf); + if (NULL == cf) { + return NULL; + } + SkScalar colorMatrix[20], inputMatrix[20]; + SkColorFilter* inputColorFilter; + if (input && cf->asColorMatrix(colorMatrix) + && input->asColorFilter(&inputColorFilter) + && (inputColorFilter)) { + SkAutoUnref autoUnref(inputColorFilter); + if (inputColorFilter->asColorMatrix(inputMatrix) && !matrix_needs_clamping(inputMatrix)) { + SkScalar combinedMatrix[20]; + mult_color_matrix(colorMatrix, inputMatrix, combinedMatrix); + SkAutoTUnref<SkColorFilter> newCF(SkColorMatrixFilter::Create(combinedMatrix)); + return SkNEW_ARGS(SkColorFilterImageFilter, (newCF, input->getInput(0), cropRect, 0)); + } + } + return SkNEW_ARGS(SkColorFilterImageFilter, (cf, input, cropRect, uniqueID)); +} + +SkColorFilterImageFilter::SkColorFilterImageFilter(SkColorFilter* cf, + SkImageFilter* input, const CropRect* cropRect, uint32_t uniqueID) + : INHERITED(1, &input, cropRect, uniqueID), fColorFilter(SkRef(cf)) { +} + +SkFlattenable* SkColorFilterImageFilter::CreateProc(SkReadBuffer& buffer) { + SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1); + SkAutoTUnref<SkColorFilter> cf(buffer.readColorFilter()); + return Create(cf, common.getInput(0), &common.cropRect(), common.uniqueID()); +} + +void SkColorFilterImageFilter::flatten(SkWriteBuffer& buffer) const { + this->INHERITED::flatten(buffer); + buffer.writeFlattenable(fColorFilter); +} + +SkColorFilterImageFilter::~SkColorFilterImageFilter() { + fColorFilter->unref(); +} + +bool SkColorFilterImageFilter::onFilterImage(Proxy* proxy, const SkBitmap& source, + const Context& ctx, + SkBitmap* result, + SkIPoint* offset) const { + SkBitmap src = source; + SkIPoint srcOffset = SkIPoint::Make(0, 0); + if (getInput(0) && !getInput(0)->filterImage(proxy, source, ctx, &src, &srcOffset)) { + return false; + } + + SkIRect bounds; + if (!this->applyCropRect(ctx, src, srcOffset, &bounds)) { + return false; + } + + SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height())); + if (NULL == device.get()) { + return false; + } + SkCanvas canvas(device.get()); + SkPaint paint; + + paint.setXfermodeMode(SkXfermode::kSrc_Mode); + paint.setColorFilter(fColorFilter); + canvas.drawSprite(src, srcOffset.fX - bounds.fLeft, srcOffset.fY - bounds.fTop, &paint); + + *result = device.get()->accessBitmap(false); + offset->fX = bounds.fLeft; + offset->fY = bounds.fTop; + return true; +} + +bool SkColorFilterImageFilter::asColorFilter(SkColorFilter** filter) const { + if (!cropRectIsSet()) { + if (filter) { + *filter = fColorFilter; + fColorFilter->ref(); + } + return true; + } + return false; +} + +#ifndef SK_IGNORE_TO_STRING +void SkColorFilterImageFilter::toString(SkString* str) const { + str->appendf("SkColorFilterImageFilter: ("); + + str->appendf("input: ("); + + if (this->getInput(0)) { + this->getInput(0)->toString(str); + } + + str->appendf(") color filter: "); + fColorFilter->toString(str); + + str->append(")"); +} +#endif diff --git a/pool/shard007/C++/0093691_module.cpp b/pool/shard007/C++/0093691_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9b50c94e6de47b0dbf87ed0a1a63f60da86ca544 --- /dev/null +++ b/pool/shard007/C++/0093691_module.cpp @@ -0,0 +1,154 @@ +#include <Python.h> + +#include <exception> +#include <iostream> + +#include "lightstep/tracer.h" +#include "python_bridge_tracer/module.h" +#include "python_bridge_tracer/python_object_wrapper.h" +#include "python_bridge_tracer/python_string_wrapper.h" +#include "python_bridge_tracer/utility.h" +#include "tracer/counting_metrics_observer.h" +#include "tracer/json_options.h" +#include "tracer/lightstep_tracer_factory.h" +#include "tracer/tracer_impl.h" + +namespace lightstep { +//-------------------------------------------------------------------------------------------------- +// ExtractScopeManager +//-------------------------------------------------------------------------------------------------- +static bool ExtractScopeManager( + PyObject* keywords, + python_bridge_tracer::PythonObjectWrapper& result) noexcept { + python_bridge_tracer::PythonObjectWrapper scope_manager = + PyDict_GetItemString(keywords, "scope_manager"); + if (scope_manager == nullptr) { + return true; + } + if (PyDict_DelItemString(keywords, "scope_manager") == -1) { + return false; + } + result = std::move(scope_manager); + return true; +} + +//-------------------------------------------------------------------------------------------------- +// MakeTracer +//-------------------------------------------------------------------------------------------------- +static PyObject* MakeTracer(PyObject* /*self*/, PyObject* /*args*/, + PyObject* keywords) noexcept { + if (keywords == nullptr) { + PyErr_Format(PyExc_RuntimeError, "no keyword arguments provided"); + return nullptr; + } + python_bridge_tracer::PythonObjectWrapper scope_manager; + if (!ExtractScopeManager(keywords, scope_manager)) { + return nullptr; + } + python_bridge_tracer::PythonObjectWrapper dumps_function = + python_bridge_tracer::getModuleAttribute("json", "dumps"); + if (dumps_function.error()) { + return nullptr; + } + python_bridge_tracer::PythonStringWrapper json_config = + PyObject_CallFunctionObjArgs(dumps_function, keywords, nullptr); + if (json_config.error()) { + return nullptr; + } + std::string error_message; + auto tracer_options_maybe = MakeTracerOptions( + static_cast<opentracing::string_view>(json_config).data(), error_message); + if (!tracer_options_maybe) { + PyErr_Format(PyExc_RuntimeError, "failed to construct tracer: %s", + error_message.c_str()); + return nullptr; + } + auto& tracer_options = *tracer_options_maybe; + tracer_options.metrics_observer.reset(new CountingMetricsObserver{}); + auto tracer = MakeLightStepTracer(std::move(tracer_options)); + if (tracer == nullptr) { + PyErr_Format(PyExc_RuntimeError, "failed to construct tracer"); + return nullptr; + } + return python_bridge_tracer::makeTracer(std::move(tracer), scope_manager); +} + +//-------------------------------------------------------------------------------------------------- +// GetNumSpansSent +//-------------------------------------------------------------------------------------------------- +static PyObject* GetNumSpansSent(PyObject* self, void* /*ignored*/) noexcept { + auto& tracer = python_bridge_tracer::extractTracer(self); + auto metrics_observer = + static_cast<lightstep::TracerImpl&>(tracer).recorder().metrics_observer(); + if (metrics_observer == nullptr) { + Py_RETURN_NONE; + } + return PyLong_FromLong( + static_cast<const CountingMetricsObserver*>(metrics_observer) + ->num_spans_sent); +} + +//-------------------------------------------------------------------------------------------------- +// GetNumSpansDropped +//-------------------------------------------------------------------------------------------------- +static PyObject* GetNumSpansDropped(PyObject* self, + void* /*ignored*/) noexcept { + auto& tracer = python_bridge_tracer::extractTracer(self); + auto metrics_observer = + static_cast<lightstep::TracerImpl&>(tracer).recorder().metrics_observer(); + if (metrics_observer == nullptr) { + Py_RETURN_NONE; + } + return PyLong_FromLong( + static_cast<const CountingMetricsObserver*>(metrics_observer) + ->num_spans_dropped); +} +} // namespace lightstep + +//-------------------------------------------------------------------------------------------------- +// ModuleMethods +//-------------------------------------------------------------------------------------------------- +static PyMethodDef ModuleMethods[] = { + {"Tracer", reinterpret_cast<PyCFunction>(lightstep::MakeTracer), + METH_VARARGS | METH_KEYWORDS, PyDoc_STR("Construct the LightStep tracer")}, + {nullptr, nullptr}}; + +//-------------------------------------------------------------------------------------------------- +// flush +//-------------------------------------------------------------------------------------------------- +namespace python_bridge_tracer { +void flush(opentracing::Tracer& tracer, + std::chrono::microseconds timeout) noexcept { + auto& lightstep_tracer = static_cast<lightstep::LightStepTracer&>(tracer); + if (timeout.count() > 0) { + lightstep_tracer.FlushWithTimeout(timeout); + } else { + lightstep_tracer.Flush(); + } +} +} // namespace python_bridge_tracer + +//-------------------------------------------------------------------------------------------------- +// PyInit_lightstep_streaming +//-------------------------------------------------------------------------------------------------- +extern "C" { +PYTHON_BRIDGE_TRACER_DEFINE_MODULE(lightstep_streaming) { + auto module = python_bridge_tracer::makeModule( + "lightstep_streaming", "bridge to LightStep's C++ tracer", ModuleMethods); + if (module == nullptr) { + PYTHON_BRIDGE_TRACER_MODULE_RETURN(nullptr); + } + std::vector<PyGetSetDef> tracer_getsets = { + {const_cast<char*>("num_spans_sent"), + reinterpret_cast<getter>(lightstep::GetNumSpansSent), nullptr, + const_cast<char*>(PyDoc_STR("Returns the number of spans sent"))}, + {const_cast<char*>("num_spans_dropped"), + reinterpret_cast<getter>(lightstep::GetNumSpansDropped), nullptr, + const_cast<char*>(PyDoc_STR("Returns the number of spans dropped"))}}; + if (!python_bridge_tracer::setupClasses(module, {}, tracer_getsets)) { + std::cerr << "Failed to set up python classes\n"; + std::terminate(); + } + PYTHON_BRIDGE_TRACER_MODULE_RETURN(module); +} +} // extern "C" diff --git a/pool/shard007/C++/0093695_main_meshResampling.cpp b/pool/shard007/C++/0093695_main_meshResampling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4d05ae9f15882eac6fbd2ac43e551c7ffd10c19b --- /dev/null +++ b/pool/shard007/C++/0093695_main_meshResampling.cpp @@ -0,0 +1,208 @@ +// This file is part of the AliceVision project. +// Copyright (c) 2017 AliceVision contributors. +// This Source Code Form is subject to the terms of the Mozilla Public License, +// v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at https://mozilla.org/MPL/2.0/. + +#include <aliceVision/system/cmdline.hpp> +#include <aliceVision/system/Logger.hpp> +#include <aliceVision/system/Timer.hpp> +#include <aliceVision/mvsUtils/common.hpp> + +#include <geogram/mesh/mesh.h> +#include <geogram/mesh/mesh_io.h> +#include <geogram/mesh/mesh_geometry.h> +#include <geogram/mesh/mesh_preprocessing.h> +#include <geogram/mesh/mesh_decimate.h> +#include <geogram/mesh/mesh_remesh.h> + +#include <geogram/basic/command_line.h> +#include <geogram/basic/command_line_args.h> + +#include <boost/program_options.hpp> +#include <boost/filesystem.hpp> + +// These constants define the current software version. +// They must be updated when the command line is changed. +#define ALICEVISION_SOFTWARE_VERSION_MAJOR 1 +#define ALICEVISION_SOFTWARE_VERSION_MINOR 0 + +using namespace aliceVision; + +namespace bfs = boost::filesystem; +namespace po = boost::program_options; + +int main(int argc, char* argv[]) +{ + system::Timer timer; + + std::string verboseLevel = system::EVerboseLevel_enumToString(system::Logger::getDefaultVerboseLevel()); + std::string inputMeshPath; + std::string outputMeshPath; + + float simplificationFactor = 0; + int fixedNbVertices = 0; + int minVertices = 0; + int maxVertices = 0; + unsigned int nbLloydIter = 40; + bool flipNormals = false; + + po::options_description allParams("AliceVision meshResampling"); + + po::options_description requiredParams("Required parameters"); + requiredParams.add_options() + ("input,i", po::value<std::string>(&inputMeshPath)->required(), + "Input Mesh (OBJ file format).") + ("output,o", po::value<std::string>(&outputMeshPath)->required(), + "Output mesh (OBJ file format)."); + + po::options_description optionalParams("Optional parameters"); + optionalParams.add_options() + ("simplificationFactor", po::value<float>(&simplificationFactor)->default_value(simplificationFactor), + "Simplification factor.") + ("nbVertices", po::value<int>(&fixedNbVertices)->default_value(fixedNbVertices), + "Fixed number of output vertices.") + ("minVertices", po::value<int>(&minVertices)->default_value(minVertices), + "Min number of output vertices.") + ("maxVertices", po::value<int>(&maxVertices)->default_value(maxVertices), + "Max number of output vertices.") + ("nbLloydIter", po::value<unsigned int>(&nbLloydIter)->default_value(nbLloydIter), + "Number of iterations for Lloyd pre-smoothing.") + ("flipNormals", po::value<bool>(&flipNormals)->default_value(flipNormals), + "Option to flip face normals. It can be needed as it depends on the vertices order in triangles and the convention change from one software to another."); + + po::options_description logParams("Log parameters"); + logParams.add_options() + ("verboseLevel,v", po::value<std::string>(&verboseLevel)->default_value(verboseLevel), + "verbosity level (fatal, error, warning, info, debug, trace)."); + + allParams.add(requiredParams).add(optionalParams).add(logParams); + + po::variables_map vm; + + try + { + po::store(po::parse_command_line(argc, argv, allParams), vm); + + if(vm.count("help") || (argc == 1)) + { + ALICEVISION_COUT(allParams); + return EXIT_SUCCESS; + } + + po::notify(vm); + } + catch(boost::program_options::required_option& e) + { + ALICEVISION_CERR("ERROR: " << e.what() << std::endl); + ALICEVISION_COUT("Usage:\n\n" << allParams); + return EXIT_FAILURE; + } + catch(boost::program_options::error& e) + { + ALICEVISION_CERR("ERROR: " << e.what() << std::endl); + ALICEVISION_COUT("Usage:\n\n" << allParams); + return EXIT_FAILURE; + } + + ALICEVISION_COUT("Program called with the following parameters:"); + ALICEVISION_COUT(vm); + + // set verbose level + system::Logger::get()->setLogLevel(verboseLevel); + + bfs::path outDirectory = bfs::path(outputMeshPath).parent_path(); + if(!bfs::is_directory(outDirectory)) + bfs::create_directory(outDirectory); + + GEO::initialize(); + + ALICEVISION_LOG_INFO("Geogram initialized."); + + GEO::Mesh M_in, M_out; + { + if(!GEO::mesh_load(inputMeshPath, M_in)) + { + ALICEVISION_LOG_ERROR("Failed to load mesh file: \"" << inputMeshPath << "\"."); + return 1; + } + } + + ALICEVISION_LOG_INFO("Mesh file: \"" << inputMeshPath << "\" loaded."); + + int nbInputPoints = M_in.vertices.nb(); + int nbOutputPoints = 0; + if(fixedNbVertices != 0) + { + nbOutputPoints = fixedNbVertices; + } + else + { + if(simplificationFactor != 0.0) + { + nbOutputPoints = simplificationFactor * nbInputPoints; + } + if(minVertices != 0) + { + if(nbInputPoints > minVertices && nbOutputPoints < minVertices) + nbOutputPoints = minVertices; + } + if(maxVertices != 0) + { + if(nbInputPoints > maxVertices && nbOutputPoints > maxVertices) + nbOutputPoints = maxVertices; + } + } + + ALICEVISION_LOG_INFO("Input mesh: " << nbInputPoints << " vertices and " << M_in.facets.nb() << " facets."); + ALICEVISION_LOG_INFO("Target output mesh: " << nbOutputPoints << " vertices."); + + { + GEO::CmdLine::import_arg_group("standard"); + GEO::CmdLine::import_arg_group("remesh"); // needed for remesh_smooth + GEO::CmdLine::import_arg_group("algo"); + GEO::CmdLine::import_arg_group("post"); + GEO::CmdLine::import_arg_group("opt"); + GEO::CmdLine::import_arg_group("poly"); + + const unsigned int nbNewtonIter = 0; + const unsigned int newtonM = 0; + + ALICEVISION_LOG_INFO("Start mesh resampling."); + GEO::remesh_smooth( + M_in, M_out, + nbOutputPoints, + 3, // 3 dimensions + nbLloydIter, // Number of iterations for Lloyd pre-smoothing + nbNewtonIter, // Number of iterations for Newton-CVT + newtonM // Number of evaluations for Hessian approximation + ); + ALICEVISION_LOG_INFO("Mesh resampling done."); + } + ALICEVISION_LOG_INFO("Output mesh: " << M_out.vertices.nb() << " vertices and " << M_out.facets.nb() << " facets."); + + if(M_out.facets.nb() == 0) + { + ALICEVISION_LOG_ERROR("The output mesh is empty."); + return 1; + } + if(flipNormals) + { + for(GEO::index_t i = 0; i < M_out.facets.nb(); ++i) + { + M_out.facets.flip(i); + } + } + + ALICEVISION_LOG_INFO("Save mesh."); + if(!GEO::mesh_save(M_out, outputMeshPath)) + { + ALICEVISION_LOG_ERROR("Failed to save mesh file: \"" << outputMeshPath << "\"."); + return EXIT_FAILURE; + } + + ALICEVISION_LOG_INFO("Mesh file: \"" << outputMeshPath << "\" saved."); + + ALICEVISION_LOG_INFO("Task done in (s): " + std::to_string(timer.elapsed())); + return EXIT_SUCCESS; +} diff --git a/pool/shard007/C++/0093704_CWE590_Free_Memory_Not_on_Heap__delete_array_char_declare_72a.cpp b/pool/shard007/C++/0093704_CWE590_Free_Memory_Not_on_Heap__delete_array_char_declare_72a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3b0a20cd96cd64a04ba18faae041241dc63e381c --- /dev/null +++ b/pool/shard007/C++/0093704_CWE590_Free_Memory_Not_on_Heap__delete_array_char_declare_72a.cpp @@ -0,0 +1,114 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE590_Free_Memory_Not_on_Heap__delete_array_char_declare_72a.cpp +Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete_array.label.xml +Template File: sources-sink-72a.tmpl.cpp +*/ +/* + * @description + * CWE: 590 Free Memory Not on Heap + * BadSource: declare Data buffer is declared on the stack + * GoodSource: Allocate memory on the heap + * Sinks: + * BadSink : Print then free data + * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files + * + * */ + +#include "std_testcase.h" +#include <vector> + +#include <wchar.h> + +using namespace std; + +namespace CWE590_Free_Memory_Not_on_Heap__delete_array_char_declare_72 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink(vector<char *> dataVector); + +void bad() +{ + char * data; + vector<char *> dataVector; + data = NULL; /* Initialize data */ + { + /* FLAW: data is allocated on the stack and deallocated in the BadSink */ + char dataBuffer[100]; + memset(dataBuffer, 'A', 100-1); /* fill with 'A's */ + dataBuffer[100-1] = '\0'; /* null terminate */ + data = dataBuffer; + } + /* Put data in a vector */ + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + badSink(dataVector); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good function declarations */ + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(vector<char *> dataVector); + +static void goodG2B() +{ + char * data; + vector<char *> dataVector; + data = NULL; /* Initialize data */ + { + /* FIX: data is allocated on the heap and deallocated in the BadSink */ + char * dataBuffer = new char[100]; + memset(dataBuffer, 'A', 100-1); /* fill with 'A's */ + dataBuffer[100-1] = '\0'; /* null terminate */ + data = dataBuffer; + } + /* Put data in a vector */ + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + goodG2BSink(dataVector); +} + +void good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +using namespace CWE590_Free_Memory_Not_on_Heap__delete_array_char_declare_72; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard007/C++/0093718_DialogLineEdit.cpp b/pool/shard007/C++/0093718_DialogLineEdit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3bf77886f0b5c9d6d2daddbc47ec89b8b298e040 --- /dev/null +++ b/pool/shard007/C++/0093718_DialogLineEdit.cpp @@ -0,0 +1,69 @@ +/*************************************************************************** + * * + * Copyright (C) 2007 by Kanardia d.o.o. [see www.kanardia.eu] * + * Writen by: * + * Ales Krajnc [ales.krajnc@kanardia.eu] * + * * + * Status: Open Source * + * * + * License: GPL - GNU General Public License * + * See 'COPYING.html' for more details about the license. * + * * + ***************************************************************************/ + +#include <QtGui> +#include "GraphicsSingleton.h" + +#include "DialogLineEdit.h" + +DialogLineEdit::DialogLineEdit( + const QString& qsLblText, + const QString& qsInitialInputText, + QWidget *pParent) + : AbstractNesisDialog(pParent) +{ + QVBoxLayout* pMainLayout = new QVBoxLayout; + setLayout(pMainLayout); + + const QFont& font = GraphicsSingleton::GetInstance()->GetFont(GraphicsSingleton::fDialog); + const QFont& fontBuddy = GraphicsSingleton::GetInstance()->GetFont(GraphicsSingleton::fKnobBuddy); + + // Label on top + QLabel* pLbl; + pLbl = new QLabel(qsLblText); + pLbl->setFont(font); + pMainLayout->addWidget(pLbl); + + // Edit and filter + buddy + QHBoxLayout* pEdtLayout = new QHBoxLayout; + pMainLayout->addLayout(pEdtLayout); + // Edit + m_pEdt = new NesisEditBox2(QString()); + m_pEdt->SetEditMode(); + m_pEdt->setText(qsInitialInputText); + m_pEdt->setFont(font); + pEdtLayout->addWidget(m_pEdt); + // buddy + QLabel* plBuddy = new QLabel; + plBuddy->setFont(fontBuddy); + plBuddy->hide(); + m_pEdt->SetBuddy(plBuddy); + pEdtLayout->addWidget(plBuddy); + + connect(m_pEdt, SIGNAL(NesisOk()), this, SLOT(accept())); + connect(m_pEdt, SIGNAL(NesisCancel()), this, SLOT(reject())); +} + + +DialogLineEdit::~DialogLineEdit() +{ +} + +// -------------------------------------------------------------------- + +QString DialogLineEdit::GetInputText() const +{ + return m_pEdt->text(); +} + +// -------------------------------------------------------------------- diff --git a/pool/shard007/C++/0093720_pcm_encoder.cpp b/pool/shard007/C++/0093720_pcm_encoder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e1171db8d8ae3d17b4ffe0cd74c551ded62e28f --- /dev/null +++ b/pool/shard007/C++/0093720_pcm_encoder.cpp @@ -0,0 +1,87 @@ +/*** + This file is part of snapcast + Copyright (C) 2014-2021 Johannes Pohl + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +***/ + +#include "pcm_encoder.hpp" +#include "common/aixlog.hpp" +#include "common/endian.hpp" +#include <memory> + + +namespace encoder +{ + +static constexpr auto ID_RIFF = 0x46464952; +static constexpr auto ID_WAVE = 0x45564157; +static constexpr auto ID_FMT = 0x20746d66; +static constexpr auto ID_DATA = 0x61746164; + +static constexpr auto LOG_TAG = "PcmEnc"; + +namespace +{ +template <typename T> +void assign(void* pointer, T val) +{ + T* p = (T*)pointer; + *p = val; +} +} // namespace + + +PcmEncoder::PcmEncoder(const std::string& codecOptions) : Encoder(codecOptions) +{ + headerChunk_.reset(new msg::CodecHeader("pcm")); +} + + +void PcmEncoder::encode(const msg::PcmChunk& chunk) +{ + // copy the chunk into a shared_ptr + auto pcmChunk = std::make_shared<msg::PcmChunk>(chunk); + encoded_callback_(*this, pcmChunk, pcmChunk->durationMs()); +} + + +void PcmEncoder::initEncoder() +{ + LOG(INFO, LOG_TAG) << "Init\n"; + headerChunk_->payloadSize = 44; + headerChunk_->payload = static_cast<char*>(realloc(headerChunk_->payload, headerChunk_->payloadSize)); + char* payload = headerChunk_->payload; + assign(payload, SWAP_32(ID_RIFF)); + assign(payload + 4, SWAP_32(36)); + assign(payload + 8, SWAP_32(ID_WAVE)); + assign(payload + 12, SWAP_32(ID_FMT)); + assign(payload + 16, SWAP_32(16)); + assign(payload + 20, SWAP_16(1)); + assign(payload + 22, SWAP_16(sampleFormat_.channels())); + assign(payload + 24, SWAP_32(sampleFormat_.rate())); + assign(payload + 28, SWAP_32(sampleFormat_.rate() * sampleFormat_.bits() * sampleFormat_.channels() / 8)); + assign(payload + 32, SWAP_16(sampleFormat_.channels() * ((sampleFormat_.bits() + 7) / 8))); + assign(payload + 34, SWAP_16(sampleFormat_.bits())); + assign(payload + 36, SWAP_32(ID_DATA)); + assign(payload + 40, SWAP_32(0)); +} + + +std::string PcmEncoder::name() const +{ + return "pcm"; +} + +} // namespace encoder diff --git a/pool/shard007/C++/0093723_tinystr.cpp b/pool/shard007/C++/0093723_tinystr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..91e7f74c5ad7bc551ea51fac8107122e9a5ea038 --- /dev/null +++ b/pool/shard007/C++/0093723_tinystr.cpp @@ -0,0 +1,111 @@ +/* +www.sourceforge.net/projects/tinyxml + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any +damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must +not claim that you wrote the original software. If you use this +software in a product, an acknowledgment in the product documentation +would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and +must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source +distribution. +*/ + + +#ifndef TIXML_USE_STL + +#include "tinystr.h" + +// Error value for find primitive +const TiXmlstring::size_type TiXmlstring::npos = static_cast< TiXmlstring::size_type >(-1); + + +// Null rep. +TiXmlstring::Rep TiXmlstring::nullrep_ = { 0, 0, { '\0' } }; + + +void TiXmlstring::reserve (size_type cap) +{ + if (cap > capacity()) + { + TiXmlstring tmp; + tmp.init(length(), cap); + memcpy(tmp.start(), data(), length()); + swap(tmp); + } +} + + +TiXmlstring& TiXmlstring::assign(const char* str, size_type len) +{ + size_type cap = capacity(); + if (len > cap || cap > 3*(len + 8)) + { + TiXmlstring tmp; + tmp.init(len); + memcpy(tmp.start(), str, len); + swap(tmp); + } + else + { + memmove(start(), str, len); + set_size(len); + } + return *this; +} + + +TiXmlstring& TiXmlstring::append(const char* str, size_type len) +{ + size_type newsize = length() + len; + if (newsize > capacity()) + { + reserve (newsize + capacity()); + } + memmove(finish(), str, len); + set_size(newsize); + return *this; +} + + +TiXmlstring operator + (const TiXmlstring & a, const TiXmlstring & b) +{ + TiXmlstring tmp; + tmp.reserve(a.length() + b.length()); + tmp += a; + tmp += b; + return tmp; +} + +TiXmlstring operator + (const TiXmlstring & a, const char* b) +{ + TiXmlstring tmp; + TiXmlstring::size_type b_len = static_cast<TiXmlstring::size_type>( strlen(b) ); + tmp.reserve(a.length() + b_len); + tmp += a; + tmp.append(b, b_len); + return tmp; +} + +TiXmlstring operator + (const char* a, const TiXmlstring & b) +{ + TiXmlstring tmp; + TiXmlstring::size_type a_len = static_cast<TiXmlstring::size_type>( strlen(a) ); + tmp.reserve(a_len + b.length()); + tmp.append(a, a_len); + tmp += b; + return tmp; +} + + +#endif // TIXML_USE_STL diff --git a/pool/shard007/C++/0093724_boss_sulfuron_harbinger.cpp b/pool/shard007/C++/0093724_boss_sulfuron_harbinger.cpp new file mode 100644 index 0000000000000000000000000000000000000000..87cb5c5f3e5ef738d548b34c8a1267973fa0f1d1 --- /dev/null +++ b/pool/shard007/C++/0093724_boss_sulfuron_harbinger.cpp @@ -0,0 +1,211 @@ +/* + * Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/> + * Copyright (C) 2005-2012 MaNGOS <http://www.getmangos.com/> + * Copyright (C) 2008-2012 Trinity <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* ScriptData +SDName: Boss_Sulfuron_Harbringer +SD%Complete: 80 +SDComment: Adds NYI +SDCategory: Molten Core +EndScriptData */ + +#include "ScriptPCH.h" +#include "molten_core.h" + +#define SPELL_DARKSTRIKE 19777 +#define SPELL_DEMORALIZINGSHOUT 19778 +#define SPELL_INSPIRE 19779 +#define SPELL_KNOCKDOWN 19780 +#define SPELL_FLAMESPEAR 19781 + +//Adds Spells +#define SPELL_HEAL 19775 +#define SPELL_SHADOWWORDPAIN 19776 +#define SPELL_IMMOLATE 20294 + +class boss_sulfuron : public CreatureScript +{ +public: + boss_sulfuron() : CreatureScript("boss_sulfuron") { } + + CreatureAI* GetAI(Creature* pCreature) const + { + return new boss_sulfuronAI (pCreature); + } + + struct boss_sulfuronAI : public ScriptedAI + { + boss_sulfuronAI(Creature *c) : ScriptedAI(c) {} + + uint32 Darkstrike_Timer; + uint32 DemoralizingShout_Timer; + uint32 Inspire_Timer; + uint32 Knockdown_Timer; + uint32 Flamespear_Timer; + + void Reset() + { + Darkstrike_Timer=10000; //These times are probably wrong + DemoralizingShout_Timer = 15000; + Inspire_Timer = 13000; + Knockdown_Timer = 6000; + Flamespear_Timer = 2000; + } + + void EnterCombat(Unit * /*who*/) + { + } + + void UpdateAI(const uint32 diff) + { + if (!UpdateVictim()) + return; + + //DemoralizingShout_Timer + if (DemoralizingShout_Timer <= diff) + { + DoCast(me->getVictim(), SPELL_DEMORALIZINGSHOUT); + DemoralizingShout_Timer = 15000 + rand()%5000; + } else DemoralizingShout_Timer -= diff; + + //Inspire_Timer + if (Inspire_Timer <= diff) + { + Creature *pTarget = NULL; + std::list<Creature*> pList = DoFindFriendlyMissingBuff(45.0f, SPELL_INSPIRE); + if (!pList.empty()) + { + std::list<Creature*>::const_iterator i = pList.begin(); + advance(i, (rand()%pList.size())); + pTarget = (*i); + } + + if (pTarget) + DoCast(pTarget, SPELL_INSPIRE); + + DoCast(me, SPELL_INSPIRE); + + Inspire_Timer = 20000 + rand()%6000; + } else Inspire_Timer -= diff; + + //Knockdown_Timer + if (Knockdown_Timer <= diff) + { + DoCast(me->getVictim(), SPELL_KNOCKDOWN); + Knockdown_Timer = 12000 + rand()%3000; + } else Knockdown_Timer -= diff; + + //Flamespear_Timer + if (Flamespear_Timer <= diff) + { + Unit *pTarget = NULL; + pTarget = SelectUnit(SELECT_TARGET_RANDOM, 0); + if (pTarget) DoCast(pTarget, SPELL_FLAMESPEAR); + + Flamespear_Timer = 12000 + rand()%4000; + } else Flamespear_Timer -= diff; + + //DarkStrike_Timer + if (Darkstrike_Timer <= diff) + { + DoCast(me, SPELL_DARKSTRIKE); + Darkstrike_Timer = 15000 + rand()%3000; + } else Darkstrike_Timer -= diff; + + DoMeleeAttackIfReady(); + } + }; +}; + +class mob_flamewaker_priest : public CreatureScript +{ +public: + mob_flamewaker_priest() : CreatureScript("mob_flamewaker_priest") { } + + CreatureAI* GetAI(Creature* pCreature) const + { + return new mob_flamewaker_priestAI (pCreature); + } + + struct mob_flamewaker_priestAI : public ScriptedAI + { + mob_flamewaker_priestAI(Creature *c) : ScriptedAI(c) {} + + uint32 Heal_Timer; + uint32 ShadowWordPain_Timer; + uint32 Immolate_Timer; + + void Reset() + { + Heal_Timer = 15000+rand()%15000; + ShadowWordPain_Timer = 2000; + Immolate_Timer = 8000; + } + + void EnterCombat(Unit * /*who*/) + { + } + + void UpdateAI(const uint32 diff) + { + if (!UpdateVictim()) + return; + + //Casting Heal to Sulfuron or other Guards. + if (Heal_Timer <= diff) + { + Unit* pUnit = DoSelectLowestHpFriendly(60.0f, 1); + if (!pUnit) + return; + + DoCast(pUnit, SPELL_HEAL); + + Heal_Timer = 15000+rand()%5000; + } else Heal_Timer -= diff; + + //ShadowWordPain_Timer + if (ShadowWordPain_Timer <= diff) + { + Unit *pTarget = NULL; + pTarget = SelectUnit(SELECT_TARGET_RANDOM, 0); + if (pTarget) DoCast(pTarget, SPELL_SHADOWWORDPAIN); + + ShadowWordPain_Timer = 18000+rand()%8000; + } else ShadowWordPain_Timer -= diff; + + //Immolate_Timer + if (Immolate_Timer <= diff) + { + Unit *pTarget = NULL; + pTarget = SelectUnit(SELECT_TARGET_RANDOM, 0); + if (pTarget) DoCast(pTarget, SPELL_IMMOLATE); + + Immolate_Timer = 15000+rand()%10000; + } else Immolate_Timer -= diff; + + DoMeleeAttackIfReady(); + } + }; +}; + +void AddSC_boss_sulfuron() +{ + new boss_sulfuron(); + new mob_flamewaker_priest(); +} \ No newline at end of file diff --git a/pool/shard007/C++/0093736_PutRequest.cpp b/pool/shard007/C++/0093736_PutRequest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..413668915d4aa90064e47c16c5d614264076f2f7 --- /dev/null +++ b/pool/shard007/C++/0093736_PutRequest.cpp @@ -0,0 +1,66 @@ +/* +* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ +#include <aws/dynamodb/model/PutRequest.h> +#include <aws/core/utils/json/JsonSerializer.h> + +#include <utility> + +using namespace Aws::DynamoDB::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +PutRequest::PutRequest() : + m_itemHasBeenSet(false) +{ +} + +PutRequest::PutRequest(const JsonValue& jsonValue) : + m_itemHasBeenSet(false) +{ + *this = jsonValue; +} + +PutRequest& PutRequest::operator =(const JsonValue& jsonValue) +{ + if(jsonValue.ValueExists("Item")) + { + Aws::Map<Aws::String, JsonValue> itemJsonMap = jsonValue.GetObject("Item").GetAllObjects(); + for(auto& itemItem : itemJsonMap) + { + m_item[itemItem.first] = itemItem.second.AsObject(); + } + m_itemHasBeenSet = true; + } + + return *this; +} + +JsonValue PutRequest::Jsonize() const +{ + JsonValue payload; + + if(m_itemHasBeenSet) + { + JsonValue itemJsonMap; + for(auto& itemItem : m_item) + { + itemJsonMap.WithObject(itemItem.first, itemItem.second.Jsonize()); + } + payload.WithObject("Item", std::move(itemJsonMap)); + + } + + return std::move(payload); +} \ No newline at end of file diff --git a/pool/shard007/C++/0093739_accept.cpp b/pool/shard007/C++/0093739_accept.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2127cc3cea204afb7e20389e6b5746cc9f4213fa --- /dev/null +++ b/pool/shard007/C++/0093739_accept.cpp @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS) + * + * This file is part of libbitcoin. + * + * libbitcoin is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License with + * additional permissions to the one published by the Free Software + * Foundation, either version 3 of the License, or (at your option) + * any later version. For more information see LICENSE. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ +/* + Accept connections from Bitcoin nodes on port 8333. +*/ +#ifdef _WIN32 +#include <iostream> +#endif +#include <bitcoin/bitcoin.hpp> + +using namespace bc; + +using std::placeholders::_1; +using std::placeholders::_2; + +// Listening has started. +// Wait to accept a connection. +void listening_started(const std::error_code& ec, acceptor_ptr accept); +// Connection to another Bitcoin node has been established. +// Wait for version message. +void accepted_connection(const std::error_code& ec, channel_ptr node, + acceptor_ptr accept); +// Version message received. +// Display the user agent. +void version_received(const std::error_code& ec, const version_type& version, + channel_ptr node); +void node_stopped(const std::error_code& ec); + +void listening_started(const std::error_code& ec, acceptor_ptr accept) +{ + if (ec) + { + log_error() << "Listen: " << ec.message(); + return; + } + // Accept first connection. + accept->accept( + std::bind(accepted_connection, _1, _2, accept)); +} + +void accepted_connection(const std::error_code& ec, channel_ptr node, + acceptor_ptr accept) +{ + if (ec) + { + log_error() << "Accept: " << ec.message(); + return; + } + log_info() << "Accepted connection!"; + node->subscribe_stop(node_stopped); + // Now we need to keep it alive otherwise the connection is closed. + node->subscribe_version( + std::bind(version_received, _1, _2, node)); + // Keep accepting more connections. + accept->accept( + std::bind(accepted_connection, _1, _2, accept)); +} + +void version_received(const std::error_code& ec, const version_type& version, + channel_ptr node) +{ + // error::service_stopped means the connection was closed. + if (ec == error::service_stopped) + return; + else if (ec) + { + log_error() << "Version message: " << ec.message(); + return; + } + log_info() << "User agent: " << version.user_agent; +} + +void node_stopped(const std::error_code& ec) +{ + if (ec == error::service_stopped) + log_info() << "Connection closed."; + else if (ec) + log_error() << "Connection closed: " << ec.message(); +} + +int main() +{ + threadpool pool(4); + network net(pool); + net.listen(8333, listening_started); + std::cin.get(); + pool.stop(); + pool.join(); + return 0; +} + diff --git a/pool/shard007/C++/0093761_Camera.cpp b/pool/shard007/C++/0093761_Camera.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ed4ffa47d489bacfe02cb57a8fafc60d2fb3d552 --- /dev/null +++ b/pool/shard007/C++/0093761_Camera.cpp @@ -0,0 +1,36 @@ +#include "Camera.h" +#include "MathHelper.h" + + +Camera::Camera() + : position(0, 0, 0), + direction(0, 0, -1), + up(0, 1, 0), + fov(45), + focalLength(1.0f), + viewDistance(_INFINITY) +{ +} + + +Camera::~Camera() +{ +} + +//Calculates camera properties based on the aspect ratio of the image +void Camera::calculate(float aspectRatio) +{ + up = glm::normalize(up); + direction = glm::normalize(direction); + + //convert fov to radians + float fovRad = fov*3.1415f / 180.0f; + + float thfov = tan(fovRad / 2); + + right = glm::cross(direction, up); + right = glm::normalize(right); + + right *= thfov * aspectRatio; + up *= thfov; +} diff --git a/pool/shard007/C++/0093770_pole_zero_filter.cc b/pool/shard007/C++/0093770_pole_zero_filter.cc new file mode 100644 index 0000000000000000000000000000000000000000..4156d7e7952a9f1ae4e01078b43ccd60c9c55da5 --- /dev/null +++ b/pool/shard007/C++/0093770_pole_zero_filter.cc @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +#include "modules/audio_processing/vad/pole_zero_filter.h" + +#include <string.h> +#include <algorithm> + +namespace webrtc { + +PoleZeroFilter* PoleZeroFilter::Create(const float* numerator_coefficients, + size_t order_numerator, + const float* denominator_coefficients, + size_t order_denominator) { + if (order_numerator > kMaxFilterOrder || + order_denominator > kMaxFilterOrder || denominator_coefficients[0] == 0 || + numerator_coefficients == NULL || denominator_coefficients == NULL) + return NULL; + return new PoleZeroFilter(numerator_coefficients, order_numerator, + denominator_coefficients, order_denominator); +} + +PoleZeroFilter::PoleZeroFilter(const float* numerator_coefficients, + size_t order_numerator, + const float* denominator_coefficients, + size_t order_denominator) + : past_input_(), + past_output_(), + numerator_coefficients_(), + denominator_coefficients_(), + order_numerator_(order_numerator), + order_denominator_(order_denominator), + highest_order_(std::max(order_denominator, order_numerator)) { + memcpy(numerator_coefficients_, numerator_coefficients, + sizeof(numerator_coefficients_[0]) * (order_numerator_ + 1)); + memcpy(denominator_coefficients_, denominator_coefficients, + sizeof(denominator_coefficients_[0]) * (order_denominator_ + 1)); + + if (denominator_coefficients_[0] != 1) { + for (size_t n = 0; n <= order_numerator_; n++) + numerator_coefficients_[n] /= denominator_coefficients_[0]; + for (size_t n = 0; n <= order_denominator_; n++) + denominator_coefficients_[n] /= denominator_coefficients_[0]; + } +} + +template <typename T> +static float FilterArPast(const T* past, + size_t order, + const float* coefficients) { + float sum = 0.0f; + size_t past_index = order - 1; + for (size_t k = 1; k <= order; k++, past_index--) + sum += coefficients[k] * past[past_index]; + return sum; +} + +int PoleZeroFilter::Filter(const int16_t* in, + size_t num_input_samples, + float* output) { + if (in == NULL || output == NULL) + return -1; + // This is the typical case, just a memcpy. + const size_t k = std::min(num_input_samples, highest_order_); + size_t n; + for (n = 0; n < k; n++) { + output[n] = in[n] * numerator_coefficients_[0]; + output[n] += FilterArPast(&past_input_[n], order_numerator_, + numerator_coefficients_); + output[n] -= FilterArPast(&past_output_[n], order_denominator_, + denominator_coefficients_); + + past_input_[n + order_numerator_] = in[n]; + past_output_[n + order_denominator_] = output[n]; + } + if (highest_order_ < num_input_samples) { + for (size_t m = 0; n < num_input_samples; n++, m++) { + output[n] = in[n] * numerator_coefficients_[0]; + output[n] += + FilterArPast(&in[m], order_numerator_, numerator_coefficients_); + output[n] -= FilterArPast(&output[m], order_denominator_, + denominator_coefficients_); + } + // Record into the past signal. + memcpy(past_input_, &in[num_input_samples - order_numerator_], + sizeof(in[0]) * order_numerator_); + memcpy(past_output_, &output[num_input_samples - order_denominator_], + sizeof(output[0]) * order_denominator_); + } else { + // Odd case that the length of the input is shorter that filter order. + memmove(past_input_, &past_input_[num_input_samples], + order_numerator_ * sizeof(past_input_[0])); + memmove(past_output_, &past_output_[num_input_samples], + order_denominator_ * sizeof(past_output_[0])); + } + return 0; +} + +} // namespace webrtc diff --git a/pool/shard007/C++/0093775_TaskOptTarget.cpp b/pool/shard007/C++/0093775_TaskOptTarget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..92fbd593fa86a94a98f6e6219d3ff1377d71deac --- /dev/null +++ b/pool/shard007/C++/0093775_TaskOptTarget.cpp @@ -0,0 +1,94 @@ +/* Copyright_License { + + XCSoar Glide Computer - http://www.xcsoar.org/ + Copyright (C) 2000-2015 The XCSoar Project + A detailed list of copyright holders can be found in the file "AUTHORS". + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +} + */ + +#include "TaskOptTarget.hpp" +#include "Task/Ordered/Points/AATPoint.hpp" +#include "Task/Ordered/Points/StartPoint.hpp" +#include "Util/Tolerances.hpp" +#include "Util/Clamp.hpp" + +TaskOptTarget::TaskOptTarget(const std::vector<OrderedTaskPoint*>& tps, + const unsigned activeTaskPoint, + const AircraftState &_aircraft, + const GlideSettings &settings, + const GlidePolar &_gp, + AATPoint &_tp_current, + const FlatProjection &projection, + StartPoint *_ts) + :ZeroFinder(fixed(0.02), fixed(0.98), fixed(TOLERANCE_OPT_TARGET)), + tm(tps.cbegin(), tps.cend(), activeTaskPoint, settings, _gp, + /* ignore the travel to the start point */ + false), + aircraft(_aircraft), + tp_start(_ts), + tp_current(_tp_current), + iso(_tp_current, projection) +{ +} + +fixed +TaskOptTarget::f(const fixed p) +{ + // set task targets + SetTarget(p); + + res = tm.glide_solution(aircraft); + + return res.time_elapsed; +} + +bool +TaskOptTarget::valid(const fixed tp) +{ + f(tp); + return res.IsOk(); +} + +fixed +TaskOptTarget::search(const fixed tp) +{ + if (tp_current.IsTargetLocked()) { + // can't move, don't bother + return fixed(-1); + } + if (iso.IsValid()) { + tm.target_save(); + const fixed t = find_min(tp); + if (!valid(t)) { + // invalid, so restore old value + tm.target_restore(); + return fixed(-1); + } else { + return t; + } + } else { + return fixed(-1); + } +} + +void +TaskOptTarget::SetTarget(const fixed p) +{ + const GeoPoint loc = iso.Parametric(Clamp(p, xmin, xmax)); + tp_current.SetTarget(loc); + tp_start->ScanDistanceRemaining(aircraft.location); +} diff --git a/pool/shard007/C++/0093779_raft_service.cc b/pool/shard007/C++/0093779_raft_service.cc new file mode 100644 index 0000000000000000000000000000000000000000..7e2750fb28ec5b907fedf49a6cfcfbe6900c3bc1 --- /dev/null +++ b/pool/shard007/C++/0093779_raft_service.cc @@ -0,0 +1,78 @@ +// Copyright 2017 Wu Tao +// +// 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 "raft_service.h" +#include "raft_task_executor.h" +#include "raft_timer.h" + +#include "base/logging.h" +#include "base/simple_channel.h" + +#include <yaraft/pb_utils.h> + +namespace consensus { + +static pb::StatusCode yaraftErrorCodeToRpcStatusCode(yaraft::Error::ErrorCodes code) { + switch (code) { + case yaraft::Error::StepLocalMsg: + return pb::StepLocalMsg; + case yaraft::Error::StepPeerNotFound: + return pb::StepPeerNotFound; + default: + LOG(FATAL) << "Unexpected error code: " << yaraft::Error::toString(code); + return pb::OK; + } +} + +void RaftServiceImpl::Step(google::protobuf::RpcController *controller, + const pb::StepRequest *request, pb::StepResponse *response, + google::protobuf::Closure *done) { + yaraft::pb::Message *msg = const_cast<pb::StepRequest *>(request)->mutable_message(); + + response->set_code(pb::OK); + + Barrier barrier; + executor_->Submit(std::bind( + [&](yaraft::RawNode *node) { + auto s = node->Step(*msg); + if (UNLIKELY(!s.IsOK())) { + response->set_code(yaraftErrorCodeToRpcStatusCode(s.Code())); + } + barrier.Signal(); + }, + std::placeholders::_1)); + barrier.Wait(); + + done->Run(); +} + +void RaftServiceImpl::Status(::google::protobuf::RpcController *controller, + const pb::StatusRequest *request, pb::StatusResponse *response, + ::google::protobuf::Closure *done) { + Barrier barrier; + executor_->Submit(std::bind( + [&](yaraft::RawNode *node) { + response->set_leader(node->LeaderHint()); + response->set_raftindex(node->LastIndex()); + response->set_raftterm(node->CurrentTerm()); + + barrier.Signal(); + }, + std::placeholders::_1)); + barrier.Wait(); + + done->Run(); +} + +} // namespace consensus diff --git a/pool/shard007/C++/0093782_search_terms_data.cc b/pool/shard007/C++/0093782_search_terms_data.cc new file mode 100644 index 0000000000000000000000000000000000000000..c6c72ba2060b267312df588c90dcddfc0f10adcb --- /dev/null +++ b/pool/shard007/C++/0093782_search_terms_data.cc @@ -0,0 +1,67 @@ +// 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 "components/search_engines/search_terms_data.h" + +#include "base/logging.h" +#include "components/google/core/browser/google_url_tracker.h" +#include "url/gurl.h" + +SearchTermsData::SearchTermsData() { +} + +SearchTermsData::~SearchTermsData() { +} + +std::string SearchTermsData::GoogleBaseURLValue() const { + return GoogleURLTracker::kDefaultGoogleHomepage; +} + +std::string SearchTermsData::GoogleBaseSuggestURLValue() const { + // Start with the Google base URL. + const GURL base_url(GoogleBaseURLValue()); + DCHECK(base_url.is_valid()); + + GURL::Replacements repl; + + // Replace any existing path with "/complete/". + // SetPathStr() requires its argument to stay in scope as long as |repl| is, + // so "/complete/" can't be passed to SetPathStr() directly, it needs to be in + // a variable. + const std::string suggest_path("/complete/"); + repl.SetPathStr(suggest_path); + + // Clear the query and ref. + repl.ClearQuery(); + repl.ClearRef(); + return base_url.ReplaceComponents(repl).spec(); +} + +std::string SearchTermsData::GetApplicationLocale() const { + return "en"; +} + +base::string16 SearchTermsData::GetRlzParameterValue(bool from_app_list) const { + return base::string16(); +} + +std::string SearchTermsData::GetSearchClient() const { + return std::string(); +} + +std::string SearchTermsData::GetSuggestClient() const { + return std::string(); +} + +std::string SearchTermsData::GetSuggestRequestIdentifier() const { + return std::string(); +} + +std::string SearchTermsData::NTPIsThemedParam() const { + return std::string(); +} + +std::string SearchTermsData::GoogleImageSearchSource() const { + return std::string(); +} diff --git a/pool/shard007/C++/0093794_camera.cpp b/pool/shard007/C++/0093794_camera.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bec2e832f32f6cabc2c78f3fb0700b3c86e6fbbe --- /dev/null +++ b/pool/shard007/C++/0093794_camera.cpp @@ -0,0 +1,135 @@ +/****************************************************************************** + * The MIT License (MIT) + * + * Copyright (c) 2015-2019 Baldur Karlsson + * Copyright (c) 2014 Crytek + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + ******************************************************************************/ + +#include "camera.h" +#include <math.h> +#include <string.h> +#include "common/common.h" +#include "matrix.h" + +void Camera::ResetArcball() +{ + dirty = true; + + arcrot = Quatf::AxisAngle(Vec3f(1, 0, 0), 0.0f); +} + +// https://en.wikibooks.org/wiki/OpenGL_Programming/Modern_OpenGL_Tutorial_Arcball +void Camera::RotateArcball(float ax, float ay, float bx, float by) +{ + Vec3f a, b; + + Vec2f from(ax, ay); + Vec2f to(bx, by); + + float az = from.x * from.x + from.y * from.y; + float bz = to.x * to.x + to.y * to.y; + + // keep the controls stable by rejecting very small movements. + if(fabsf(az - bz) < 1e-5f) + return; + + if(az < 1.0f) + { + a = Vec3f(from.x, from.y, sqrt(1.0f - az)); + } + else + { + a = Vec3f(from.x, from.y, 0.0f); + a.Normalise(); + } + + if(bz < 1.0f) + { + b = Vec3f(to.x, to.y, sqrt(1.0f - bz)); + } + else + { + b = Vec3f(to.x, to.y, 0.0f); + b.Normalise(); + } + + float angle = acosf(RDCMIN(1.0f, a.Dot(b))); + + Vec3f axis = a.Cross(b); + axis.Normalise(); + + dirty = true; + + Quatf delta = Quatf::AxisAngle(axis, angle); + arcrot = arcrot * delta; +} + +void Camera::Update() +{ + if(!dirty) + return; + + if(type == CameraType::FPSLook) + { + Matrix4f p = Matrix4f::Translation(-pos); + Matrix4f r = Matrix4f::RotationXYZ(-angles); + + mat = r.Mul(p); + basis = mat.Transpose(); + } + else + { + Matrix4f p = Matrix4f::Translation(-pos); + Matrix4f r = arcrot.GetMatrix(); + Matrix4f d = Matrix4f::Translation(Vec3f(0.0f, 0.0f, dist)); + + mat = d.Mul(r.Mul(p)); + } +} + +const Matrix4f Camera::GetMatrix() +{ + Update(); + return mat; +} + +FloatVector Camera::GetPosition() +{ + return FloatVector(pos.x, pos.y, pos.z, 1.0f); +} + +FloatVector Camera::GetForward() +{ + Vec3f fwd = basis.GetForward(); + return FloatVector(fwd.x, fwd.y, fwd.z, 1.0f); +} + +FloatVector Camera::GetRight() +{ + Vec3f right = basis.GetRight(); + return FloatVector(right.x, right.y, right.z, 1.0f); +} + +FloatVector Camera::GetUp() +{ + Vec3f up = basis.GetUp(); + return FloatVector(up.x, up.y, up.z, 1.0f); +} diff --git a/pool/shard007/C++/0093797_ModTapdance.cpp b/pool/shard007/C++/0093797_ModTapdance.cpp new file mode 100644 index 0000000000000000000000000000000000000000..42702f7c1299c16f6c8aab76d6effc27cfd400f9 --- /dev/null +++ b/pool/shard007/C++/0093797_ModTapdance.cpp @@ -0,0 +1,230 @@ +#include "ModTapdance.h" + +CModTapdance::CModTapdance(void) +{ + // nothing +} + +void CModTapdance::Begin(void) +{ + CModTemplate::Begin(); + ModGUID = 6; // GUID of this specific mod + + if (Global.HasUSB) + { + + // resets all arrays, not needed but nice against compilers + for (byte i = 0; i < 10; i++) + { + KeyID[i] = 255; // if 255 then slot is not used + KeyTimeout[i] = 0; + KeyCounter[i] = 0; + IsDown[i] = false; + } + } +} + +void CModTapdance::LoadData(void) +{ + CModTemplate::LoadData(); + + // loads number of tapdance keys and timeout settings + if (Global.HasUSB) + { + + TapdanceCount = GetData(0); + TimeoutSetting = GetData(1); + } +} + +void CModTapdance::PressTapdance(byte id) +{ + bool exists = false; + for (byte i = 0; i < 10; i++) // iterate through the arrays + { + if (KeyID[i] == id) // it was previously pressed + { + exists = true; + IsDown[i] = true; + if (KeyTimeout[i] > 0) // it wasn't timed out + { + KeyTimeout[i] = TimeoutSetting; + KeyCounter[i]++; // increment tapdance value + } + break; + } + } + + if (!exists) // run this if it was not pressed before + { + for (byte i = 0; i < 10; i++) // iterate through the arrays + { + if (KeyID[i] == 255) // find first occurance of an empty slot + { + exists = true; + IsDown[i] = true; + KeyID[i] = id; + KeyTimeout[i] = TimeoutSetting; + KeyCounter[i] = 0; + break; // breaks out of the loop so that not every 255 gets infected + } + } + } + +} + +void CModTapdance::ReleaseTapdance(byte id) +{ + + for (byte i = 0; i < 10; i++) // iterate through the arrays + { + if (KeyID[i] == id) // it was previously pressed + { + IsDown[i] = false; + if (KeyTimeout[i] > 0) + { + // do nothing + } + else + { + ReleaseTapKey(id, KeyCounter[i]); + KeyID[i] = 255; // clears keyid state; + } + } + } +} + +void CModTapdance::Loop(void) +{ + CModTemplate::Loop(); + + if (Animus.Async1MSDelay()) + { + + if (Global.HasUSB) + { + + if (tickTock < 5) + { + tickTock++; + } + else // runs once every 5 cycles (about 5ms) + { + for (byte i = 0; i < 10; i++) + { + + if (KeyID[i] != 255) // it was previously pressed + { + if (KeyTimeout[i] > 0) + { + KeyTimeout[i]--; + } + else + { + PressTapKey(KeyID[i], KeyCounter[i]); + if (!IsDown[i]) + { + ReleaseTapKey(KeyID[i], KeyCounter[i]); + KeyID[i] = 255; // clears keyid state; + } + } + } + } + tickTock = 0; + } + } + } +} + +void CModTapdance::PressTapKey(byte id, byte counter) +{ + short startingAddr = 2; + for (byte i = 0; i < id; i++) // this retrieves the starting address of the specific macro + { + startingAddr = startingAddr + 1 + GetData(startingAddr) * 2; + } + + byte keyLength = GetData(startingAddr); + if (counter <= keyLength) + { + Animus.PressKey(GetData(startingAddr + 1 + counter * 2), GetData(startingAddr + 2 + counter * 2)); + } +} + +void CModTapdance::ReleaseTapKey(byte id, byte counter) +{ + short startingAddr = 2; + for (byte i = 0; i < id; i++) // this retrieves the starting address of the specific macro + { + startingAddr = startingAddr + 1 + GetData(startingAddr) * 2; + } + + byte keyLength = GetData(startingAddr); + if (counter <= keyLength) + { + Animus.ReleaseKey(GetData(startingAddr + 1 + counter * 2), GetData(startingAddr + 2 + counter * 2)); + } +} + + +void CModTapdance::PrePress(byte val, byte type) +{ + CModTemplate::PrePress(val, type); + + if (Global.HasUSB) + { + + for (byte i = 0; i < 10; i++) // iterate through the arrays + { + if (KeyID[i] != 255) // it was previously pressed + { + if (val == KeyID[i] && type == 33) // same key as self, ignore + { + // do nothing + } + else if (KeyTimeout[i] > 0) // press tap key if another key is pressed + { + PressTapKey(KeyID[i], KeyCounter[i]); + if (!IsDown[i]) + { + ReleaseTapKey(KeyID[i], KeyCounter[i]); + KeyID[i] = 255; // clears keyid state; + } + } + } + } + } +} +void CModTapdance::PressKey(byte val, byte type) +{ + CModTemplate::PressKey(val, type); + + if (Global.HasUSB) + { + if (type == 33) + { + PressTapdance(val); + } + } +} +void CModTapdance::ReleaseKey(byte val, byte type) +{ + CModTemplate::ReleaseKey(val, type); + + if (Global.HasUSB) + { + + if (type == 33) + { + ReleaseTapdance(val); + } + } +} + +void CModTapdance::SerialComms(byte mode) +{ + CModTemplate::SerialComms(mode); +} + + +CModTapdance ModTapdance; diff --git a/pool/shard007/C++/0093799_cppgettext.cpp b/pool/shard007/C++/0093799_cppgettext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b8438378ca50ace540358d73f1e3bfe2ec48a139 --- /dev/null +++ b/pool/shard007/C++/0093799_cppgettext.cpp @@ -0,0 +1,69 @@ +/// C++ gettext interface +/// @author David Siroky <siroky@dasir.cz> +/// @license see LICENSE.txt +/// @file + +#include "cppgettext.h" + +//###################################################################### +//###################################################################### + +Translations *g_installed_translations = NULL; + +//###################################################################### +//###################################################################### + +char *cppgettext(const char *msgid) +{ + if (g_installed_translations != NULL) + return g_installed_translations->gettext(msgid); + return (char *)msgid; +} + +//###################################################################### +//###################################################################### + +Translations::Translations() +{ + fallback = NULL; +} + +//###################################################################### + +Translations::~Translations() +{ + fallback = NULL; + // reset global gettext() function + if (g_installed_translations == this) + g_installed_translations = NULL; +} + +//###################################################################### + +void Translations::set_fallback(Translations *tr_fallback) +{ + fallback = tr_fallback; +} + +//###################################################################### + +char *Translations::gettext(const char *original) +{ + auto it = parser.translation_map.find(std::string(original)); + if (it == parser.translation_map.end()) + { + if (fallback != NULL) + return fallback->gettext(original); + else + return (char *)original; + } + return (char *)it->second.c_str(); +} + +//###################################################################### + +/// "redirect" global gettext() function to this class +void Translations::install() +{ + g_installed_translations = this; +} diff --git a/pool/shard007/C++/0093808_uldaman.cpp b/pool/shard007/C++/0093808_uldaman.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ad927216db2abd9f084f577f372991cea3fe521d --- /dev/null +++ b/pool/shard007/C++/0093808_uldaman.cpp @@ -0,0 +1,252 @@ + /* + * Copyright (C) 2010-2013 Project SkyFire <http://www.projectskyfire.org/> + * Copyright (C) 2010-2013 Oregon <http://www.oregoncore.com/> + * Copyright (C) 2006-2008 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> + * Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +/* ScriptData +SDName: Uldaman +SD%Complete: 100 +SDComment: Quest support: 2240, 2278 + 1 trash mob +SDCategory: Uldaman +EndScriptData */ + +/* ContentData +mob_jadespine_basilisk +npc_lore_keeper_of_norgannon +go_keystone_chamber +at_map_chamber +EndContentData */ + +#include "ScriptPCH.h" +#include "uldaman.h" + +#define QUEST_HIDDEN_CHAMBER 2240 + +/*###### +## mob_jadespine_basilisk +######*/ + +#define SPELL_CSLUMBER 3636 + +struct mob_jadespine_basiliskAI : public ScriptedAI +{ + mob_jadespine_basiliskAI(Creature *c) : ScriptedAI(c) {} + + uint32 Cslumber_Timer; + + void Reset() + { + Cslumber_Timer = 2000; + } + + void EnterCombat(Unit * /*who*/) + { + } + + void UpdateAI(const uint32 diff) + { + //Return since we have no target + if (!UpdateVictim()) + return; + + //Cslumber_Timer + if (Cslumber_Timer <= diff) + { + //Cast + // DoCast(me->getVictim(), SPELL_CSLUMBER); + DoCast(me->getVictim(), SPELL_CSLUMBER, true); + + //Stop attacking target thast asleep and pick new target + Cslumber_Timer = 28000; + + Unit* Target = SelectUnit(SELECT_TARGET_TOPAGGRO, 0); + + if (!Target || Target == me->getVictim()) + Target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true); + + if (Target) + me->TauntApply(Target); + } else Cslumber_Timer -= diff; + + DoMeleeAttackIfReady(); + } +}; + +CreatureAI* GetAI_mob_jadespine_basilisk(Creature* creature) +{ + return new mob_jadespine_basiliskAI (creature); +} + +/*###### +## npc_lore_keeper_of_norgannon +######*/ + +#define GOSSIP_HELLO_KEEPER "Who are the Earthen?" +#define GOSSIP_SELECT_KEEPER1 "What is a \"subterranean being matrix\"?" +#define GOSSIP_SELECT_KEEPER2 "What are the anomalies you speak of?" +#define GOSSIP_SELECT_KEEPER3 "What is a resilient foundation of construction?" +#define GOSSIP_SELECT_KEEPER4 "So... the Earthen were made out of stone?" +#define GOSSIP_SELECT_KEEPER5 "Anything else I should know about the Earthen?" +#define GOSSIP_SELECT_KEEPER6 "I think I understand the Creators' design intent for the Earthen now. What are the Earthen's anomalies that you spoke of earlier?" +#define GOSSIP_SELECT_KEEPER7 "What high-stress environments would cause the Earthen to destabilize?" +#define GOSSIP_SELECT_KEEPER8 "What happens when the Earthen destabilize?" +#define GOSSIP_SELECT_KEEPER9 "Troggs?! Are the troggs you mention the same as the ones in the world today?" +#define GOSSIP_SELECT_KEEPER10 "You mentioned two results when the Earthen destabilize. What is the second?" +#define GOSSIP_SELECT_KEEPER11 "Dwarves!!! Now you're telling me that dwarves originally came from the Earthen?!" +#define GOSSIP_SELECT_KEEPER12 "These dwarves are the same ones today, yes? Do the dwarves maintain any other links to the Earthen?" +#define GOSSIP_SELECT_KEEPER13 "Who are the Creators?" +#define GOSSIP_SELECT_KEEPER14 "This is a lot to think about." +#define GOSSIP_SELECT_KEEPER15 "I will access the discs now." + +bool GossipHello_npc_lore_keeper_of_norgannon(Player* player, Creature* creature) +{ + if (player->GetQuestStatus(2278) == QUEST_STATUS_INCOMPLETE) + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HELLO_KEEPER, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); + + player->SEND_GOSSIP_MENU(1079, creature->GetGUID()); + + return true; +} + +bool GossipSelect_npc_lore_keeper_of_norgannon(Player* player, Creature* creature, uint32 /*uiSender*/, uint32 uiAction) +{ + switch (uiAction) + { + case GOSSIP_ACTION_INFO_DEF+1: + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_KEEPER1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2); + player->SEND_GOSSIP_MENU(1080, creature->GetGUID()); + break; + case GOSSIP_ACTION_INFO_DEF+2: + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_KEEPER2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+3); + player->SEND_GOSSIP_MENU(1081, creature->GetGUID()); + break; + case GOSSIP_ACTION_INFO_DEF+3: + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_KEEPER3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+4); + player->SEND_GOSSIP_MENU(1082, creature->GetGUID()); + break; + case GOSSIP_ACTION_INFO_DEF+4: + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_KEEPER4, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+5); + player->SEND_GOSSIP_MENU(1083, creature->GetGUID()); + break; + case GOSSIP_ACTION_INFO_DEF+5: + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_KEEPER5, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+6); + player->SEND_GOSSIP_MENU(1084, creature->GetGUID()); + break; + case GOSSIP_ACTION_INFO_DEF+6: + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_KEEPER6, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+7); + player->SEND_GOSSIP_MENU(1085, creature->GetGUID()); + break; + case GOSSIP_ACTION_INFO_DEF+7: + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_KEEPER7, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+8); + player->SEND_GOSSIP_MENU(1086, creature->GetGUID()); + break; + case GOSSIP_ACTION_INFO_DEF+8: + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_KEEPER8, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+9); + player->SEND_GOSSIP_MENU(1087, creature->GetGUID()); + break; + case GOSSIP_ACTION_INFO_DEF+9: + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_KEEPER9, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+10); + player->SEND_GOSSIP_MENU(1088, creature->GetGUID()); + break; + case GOSSIP_ACTION_INFO_DEF+10: + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_KEEPER10, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+11); + player->SEND_GOSSIP_MENU(1089, creature->GetGUID()); + break; + case GOSSIP_ACTION_INFO_DEF+11: + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_KEEPER11, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+12); + player->SEND_GOSSIP_MENU(1090, creature->GetGUID()); + break; + case GOSSIP_ACTION_INFO_DEF+12: + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_KEEPER12, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+13); + player->SEND_GOSSIP_MENU(1091, creature->GetGUID()); + break; + case GOSSIP_ACTION_INFO_DEF+13: + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_KEEPER13, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+14); + player->SEND_GOSSIP_MENU(1092, creature->GetGUID()); + break; + case GOSSIP_ACTION_INFO_DEF+14: + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_KEEPER14, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+15); + player->SEND_GOSSIP_MENU(1093, creature->GetGUID()); + break; + case GOSSIP_ACTION_INFO_DEF+15: + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_KEEPER15, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+16); + player->SEND_GOSSIP_MENU(1094, creature->GetGUID()); + break; + case GOSSIP_ACTION_INFO_DEF+16: + player->CLOSE_GOSSIP_MENU(); + player->AreaExploredOrEventHappens(2278); + break; + } + return true; +} + +/*###### +## go_keystone_chamber +######*/ + +bool GOHello_go_keystone_chamber(Player* player, GameObject* go) +{ + ScriptedInstance* instance = go->GetInstanceScript(); + + if (!instance) + return false; + + if (instance) + instance->SetData(DATA_IRONAYA_SEAL, IN_PROGRESS); //door animation and save state. + + return false; +} + +/*###### +## at_map_chamber +######*/ + +bool AT_map_chamber(Player* player, const AreaTriggerEntry *at) +{ + if (player && player->GetQuestStatus(QUEST_HIDDEN_CHAMBER) == QUEST_STATUS_INCOMPLETE) + player->AreaExploredOrEventHappens(QUEST_HIDDEN_CHAMBER); + + return true; +} + +void AddSC_uldaman() +{ + Script *newscript; + + newscript = new Script; + newscript->Name = "mob_jadespine_basilisk"; + newscript->GetAI = &GetAI_mob_jadespine_basilisk; + newscript->RegisterSelf(); + + newscript = new Script; + newscript->Name = "npc_lore_keeper_of_norgannon"; + newscript->pGossipHello = &GossipHello_npc_lore_keeper_of_norgannon; + newscript->pGossipSelect = &GossipSelect_npc_lore_keeper_of_norgannon; + newscript->RegisterSelf(); + + newscript = new Script; + newscript->Name = "go_keystone_chamber"; + newscript->pGOHello = &GOHello_go_keystone_chamber; + newscript->RegisterSelf(); + + newscript = new Script; + newscript->Name = "at_map_chamber"; + newscript->pAreaTrigger = &AT_map_chamber; + newscript->RegisterSelf(); +} + diff --git a/pool/shard007/C++/0093811_fuzzy_range_query.cpp b/pool/shard007/C++/0093811_fuzzy_range_query.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6320f91ec31a2c9bc4655e701da87a5d7b502ace --- /dev/null +++ b/pool/shard007/C++/0093811_fuzzy_range_query.cpp @@ -0,0 +1,45 @@ +#include <CGAL/Cartesian_d.h> +#include <CGAL/point_generators_d.h> +#include <CGAL/Kd_tree.h> +#include <CGAL/Fuzzy_sphere.h> +#include <CGAL/Fuzzy_iso_box.h> +#include <CGAL/Search_traits_d.h> + +typedef CGAL::Cartesian_d<double> K; +typedef K::Point_d Point_d; +typedef CGAL::Search_traits_d<K> Traits; +typedef CGAL::Random_points_in_cube_d<Point_d> Random_points_iterator; +typedef CGAL::Counting_iterator<Random_points_iterator> N_Random_points_iterator; +typedef CGAL::Kd_tree<Traits> Tree; +typedef CGAL::Fuzzy_sphere<Traits> Fuzzy_sphere; +typedef CGAL::Fuzzy_iso_box<Traits> Fuzzy_iso_box; + +int main() { + const int D = 4; + const int N = 1000; + // generator for random data points in the square ( (-1000,-1000), (1000,1000) ) + Random_points_iterator rpit(4, 1000.0); + + // Insert N points in the tree + Tree tree(N_Random_points_iterator(rpit,0), + N_Random_points_iterator(rpit,N)); + + // define range query objects + double pcoord[D] = { 300, 300, 300, 300 }; + double qcoord[D] = { 900.0, 900.0, 900.0, 900.0 }; + Point_d p(D, pcoord, pcoord+D); + Point_d q(D, qcoord, qcoord+D); + Fuzzy_sphere fs(p, 700.0, 100.0); + Fuzzy_iso_box fib(p, q, 100.0); + + std::cout << "points approximately in fuzzy range query" << std::endl; + std::cout << "with center (300.0, 300.0, 300.0, 300.0)" << std::endl; + std::cout << "and fuzzy radius <200.0,400.0> are:" << std::endl; + tree.search(std::ostream_iterator<Point_d>(std::cout, "\n"), fs); + + std::cout << "points approximately in fuzzy range query "; + std::cout << "[<200,4000>,<800,1000>]]^4 are:" << std::endl; + + tree.search(std::ostream_iterator<Point_d>(std::cout, "\n"), fib); + return 0; +} diff --git a/pool/shard007/C++/0093812_ec_signature_creator_unittest.cc b/pool/shard007/C++/0093812_ec_signature_creator_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..018ba54a23cab185c49aceac0b4483d899cf737a --- /dev/null +++ b/pool/shard007/C++/0093812_ec_signature_creator_unittest.cc @@ -0,0 +1,58 @@ +// Copyright (c) 2012 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 "crypto/ec_signature_creator.h" + +#include <stdint.h> + +#include <memory> +#include <string> +#include <vector> + +#include "crypto/ec_private_key.h" +#include "crypto/signature_verifier.h" +#include "testing/gtest/include/gtest/gtest.h" + +// TODO(rch): Add some exported keys from each to +// test interop between NSS and OpenSSL. + +TEST(ECSignatureCreatorTest, BasicTest) { + // Do a verify round trip. + std::unique_ptr<crypto::ECPrivateKey> key_original( + crypto::ECPrivateKey::Create()); + ASSERT_TRUE(key_original.get()); + + std::vector<uint8_t> key_info; + ASSERT_TRUE( + key_original->ExportEncryptedPrivateKey(std::string(), 1000, &key_info)); + std::vector<uint8_t> pubkey_info; + ASSERT_TRUE(key_original->ExportPublicKey(&pubkey_info)); + + std::unique_ptr<crypto::ECPrivateKey> key( + crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo( + std::string(), key_info, pubkey_info)); + ASSERT_TRUE(key.get()); + ASSERT_TRUE(key->key() != NULL); + + std::unique_ptr<crypto::ECSignatureCreator> signer( + crypto::ECSignatureCreator::Create(key.get())); + ASSERT_TRUE(signer.get()); + + std::string data("Hello, World!"); + std::vector<uint8_t> signature; + ASSERT_TRUE(signer->Sign(reinterpret_cast<const uint8_t*>(data.c_str()), + data.size(), &signature)); + + std::vector<uint8_t> public_key_info; + ASSERT_TRUE(key_original->ExportPublicKey(&public_key_info)); + + crypto::SignatureVerifier verifier; + ASSERT_TRUE(verifier.VerifyInit( + crypto::SignatureVerifier::ECDSA_SHA256, &signature[0], signature.size(), + &public_key_info.front(), public_key_info.size())); + + verifier.VerifyUpdate(reinterpret_cast<const uint8_t*>(data.c_str()), + data.size()); + ASSERT_TRUE(verifier.VerifyFinal()); +} diff --git a/pool/shard007/C++/0093813_HSAAPIAnalyzer.cpp b/pool/shard007/C++/0093813_HSAAPIAnalyzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7c4588f7215ee4061ceb645c0195e431458c3bc9 --- /dev/null +++ b/pool/shard007/C++/0093813_HSAAPIAnalyzer.cpp @@ -0,0 +1,31 @@ +//============================================================================== +// Copyright (c) 2015 Advanced Micro Devices, Inc. All rights reserved. +/// \author AMD Developer Tools Team +/// \file +/// \brief This file defines base HSAAPIAnalyzer class and HSAAPIAnalyzerManager class which is a IParserListener +//============================================================================== + +#include "HSAAPIAnalyzer.h" + +void HSAAPIAnalyzerManager::OnParse(HSAAPIInfo* pAPIInfo, bool& stopParsing) +{ + stopParsing = false; + + // On-the-fly analysis + for (AnalyzerList::iterator it = m_analyzers.begin(); it != m_analyzers.end(); it++) + { + if ((*it)->IsEnabled()) + { + (*it)->Analyze(pAPIInfo); + } + } + + // Build flattened APIs list for post-parsing analysis + if (m_apisToFlatten.size() > 0) + { + if (m_apisToFlatten.find(pAPIInfo->m_apiID) != m_apisToFlatten.end()) + { + m_flattenedAPIs.insert(pAPIInfo); + } + } +} diff --git a/pool/shard007/C++/0093814_ifstream.cpp b/pool/shard007/C++/0093814_ifstream.cpp new file mode 100644 index 0000000000000000000000000000000000000000..68943af6a231bf6e37a0b272211e790e55cee323 --- /dev/null +++ b/pool/shard007/C++/0093814_ifstream.cpp @@ -0,0 +1,143 @@ +/*************************************************************************** + * + * ifstream.cpp - basic_ifstream example. + * + * $Id$ + * + *************************************************************************** + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing + * permissions and limitations under the License. + * + * Copyright 1994-2006 Rogue Wave Software. + * + **************************************************************************/ + +#include <fstream> // for fstream +#include <iomanip> // for setw +#include <ios> // for dec, hex, oct, right, showbase +#include <iostream> // for cerr, cout +#include <locale> // for isspace() + +#include <examples.h> + + +int main ( ) +{ + const char ntbs[] = "Le minot passait la piece a frotter."; + + try { + + // create a read/write file-stream object + std::ifstream in ("ifstream.results.out", + std::ios::in | std::ios::out | std::ios::trunc); + + if (!in.is_open ()) + throw (std::ios::failure ("open error")); + + // associate the ostream object's buffer with the ifstream object + std::ostream out (in.rdbuf ()); + + // output ntbs in out + out << ntbs << '\n'; + + // seek to the beginning of the file + in.seekg (0); + + char c; + + // output each space-separated word on a separate line + while (in.get (c)) { + if ((std::isspace)(c, in.getloc ())) + std::cout << '\n'; + else + std::cout << c; + } + + std::cout << '\n'; + + // clear stream state, failbit | eofbit set by last call to get () + in.clear (); + + // move back to the beginning of the file + in.seekg (0); + + char buf [40]; + + // guard against buffer overflow + in.width (sizeof buf); + + // set right justification + std::cout << std::right; + + // does the same thing as the previous code + // output each word on a separate line in a field of width 10 + while (in >> buf) { + std::cout.width (10); + std::cout << buf << '\n'; + } + + std::cout << '\n'; + + // clear the stream state + in.clear (); + + // output the base info before each integer + out << std::showbase; + + std::ostream::pos_type pos= out.tellp (); + + const long x = 10; + + // output x in hex with a field with of 10 + out << std::hex << std::setw (10) << x << '\n'; + + // output x in oct with a field with of 10 + out << std::oct << std::setw (10) << x << '\n'; + + // output x in dec with a field with of 10 + out << std::dec << std::setw (10) << x << '\n'; + + // move back to the beginning of the file + in.seekg (0); + + // output the entire file + std::cout << in.rdbuf () << '\n'; + + // clear the stream state + in.clear (); + + // seek the input sequence to pos + in.seekg (pos); + + long a = 0; + long b = 0; + long d = 0; + + in.unsetf (std::ios::basefield); + + // read the previous outputted integer + in >> a >> b >> d; + + // output 3 times 10 + std::cout << a << '\n' << b << '\n' << d << '\n'; + } + catch (std::ios::failure e) { + std::cerr << e.what () << '\n'; + } + + return 0; +} diff --git a/pool/shard007/C++/0093816_memory_allocator_dump_unittest.cc b/pool/shard007/C++/0093816_memory_allocator_dump_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..8c14560bf28acd14e658c08ef09f18e9753d43bd --- /dev/null +++ b/pool/shard007/C++/0093816_memory_allocator_dump_unittest.cc @@ -0,0 +1,95 @@ +// 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. + +#include "base/trace_event/memory_allocator_dump.h" + +#include "base/trace_event/memory_dump_provider.h" +#include "base/trace_event/process_memory_dump.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace base { +namespace trace_event { + +namespace { +class FakeMemoryAllocatorDumpProvider : public MemoryDumpProvider { + public: + FakeMemoryAllocatorDumpProvider() { + DeclareAllocatorAttribute({"attr1", "count"}); + DeclareAllocatorAttribute({"attr2", "bytes"}); + } + + bool DumpInto(ProcessMemoryDump* pmd) override { + MemoryAllocatorDump* mad_foo = pmd->CreateAllocatorDump("foo"); + mad_foo->set_physical_size_in_bytes(4096); + mad_foo->set_allocated_objects_count(42); + mad_foo->set_allocated_objects_size_in_bytes(1000); + mad_foo->SetExtraAttribute("attr1", 1234); + mad_foo->SetExtraAttribute("attr2", 99); + + MemoryAllocatorDump* mad_bar = pmd->CreateAllocatorDump("foo/bar", mad_foo); + mad_bar->set_physical_size_in_bytes(1); + mad_bar->set_allocated_objects_count(2); + mad_bar->set_allocated_objects_size_in_bytes(3); + + pmd->CreateAllocatorDump("baz"); + // Leave the rest of |baz| deliberately uninitialized, to check that + // CreateAllocatorDump returns a properly zero-initialized object. + + return true; + } + + const char* GetFriendlyName() const override { return "mock_allocator"; } +}; +} // namespace + +TEST(MemoryAllocatorDumpTest, DumpIntoProcessMemoryDump) { + FakeMemoryAllocatorDumpProvider fmadp; + ProcessMemoryDump pmd; + + fmadp.DumpInto(&pmd); + + ASSERT_EQ(3u, pmd.allocator_dumps().size()); + + const MemoryAllocatorDump* mad_foo = pmd.GetAllocatorDump("foo"); + ASSERT_NE(nullptr, mad_foo); + EXPECT_EQ("foo", mad_foo->name()); + ASSERT_EQ(nullptr, mad_foo->parent()); + EXPECT_EQ(4096u, mad_foo->physical_size_in_bytes()); + EXPECT_EQ(42u, mad_foo->allocated_objects_count()); + EXPECT_EQ(1000u, mad_foo->allocated_objects_size_in_bytes()); + + // Check the extra attributes of |mad_foo|. + EXPECT_EQ(1234, mad_foo->GetExtraIntegerAttribute("attr1")); + EXPECT_EQ(99, mad_foo->GetExtraIntegerAttribute("attr2")); + + const MemoryAllocatorDump* mad_bar = pmd.GetAllocatorDump("foo/bar"); + ASSERT_NE(nullptr, mad_bar); + EXPECT_EQ("foo/bar", mad_bar->name()); + ASSERT_EQ(mad_foo, mad_bar->parent()); + EXPECT_EQ(1u, mad_bar->physical_size_in_bytes()); + EXPECT_EQ(2u, mad_bar->allocated_objects_count()); + EXPECT_EQ(3u, mad_bar->allocated_objects_size_in_bytes()); + + const MemoryAllocatorDump* mad_baz = pmd.GetAllocatorDump("baz"); + ASSERT_NE(nullptr, mad_baz); + EXPECT_EQ("baz", mad_baz->name()); + ASSERT_EQ(nullptr, mad_baz->parent()); + EXPECT_EQ(0u, mad_baz->physical_size_in_bytes()); + EXPECT_EQ(0u, mad_baz->allocated_objects_count()); + EXPECT_EQ(0u, mad_baz->allocated_objects_size_in_bytes()); +} + +// DEATH tests are not supported in Android / iOS. +#if !defined(NDEBUG) && !defined(OS_ANDROID) && !defined(OS_IOS) +TEST(MemoryAllocatorDumpTest, ForbidDuplicatesDeathTest) { + FakeMemoryAllocatorDumpProvider fmadp; + ProcessMemoryDump pmd; + pmd.CreateAllocatorDump("dump_1"); + pmd.CreateAllocatorDump("dump_2"); + ASSERT_DEATH(pmd.CreateAllocatorDump("dump_1"), ""); +} +#endif + +} // namespace trace_event +} // namespace base diff --git a/pool/shard007/C++/0093820_CWE690_NULL_Deref_From_Return__long_realloc_72a.cpp b/pool/shard007/C++/0093820_CWE690_NULL_Deref_From_Return__long_realloc_72a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fee7fab0d98ff6388712b893b636ef5855fd025c --- /dev/null +++ b/pool/shard007/C++/0093820_CWE690_NULL_Deref_From_Return__long_realloc_72a.cpp @@ -0,0 +1,101 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE690_NULL_Deref_From_Return__long_realloc_72a.cpp +Label Definition File: CWE690_NULL_Deref_From_Return.free.label.xml +Template File: source-sinks-72a.tmpl.cpp +*/ +/* + * @description + * CWE: 690 Unchecked Return Value To NULL Pointer + * BadSource: realloc Allocate data using realloc() + * Sinks: + * GoodSink: Check to see if the data allocation failed and if not, use data + * BadSink : Don't check for NULL and use data + * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files + * + * */ + +#include "std_testcase.h" +#include <vector> + +#include <wchar.h> + +using namespace std; + +namespace CWE690_NULL_Deref_From_Return__long_realloc_72 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink(vector<long *> dataVector); + +void bad() +{ + long * data; + vector<long *> dataVector; + data = NULL; /* Initialize data */ + /* POTENTIAL FLAW: Allocate memory without checking if the memory allocation function failed */ + data = (long *)realloc(data, 1*sizeof(long)); + /* Put data in a vector */ + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + badSink(dataVector); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodB2G uses the BadSource with the GoodSink */ +void goodB2GSink(vector<long *> dataVector); + +static void goodB2G() +{ + long * data; + vector<long *> dataVector; + data = NULL; /* Initialize data */ + /* POTENTIAL FLAW: Allocate memory without checking if the memory allocation function failed */ + data = (long *)realloc(data, 1*sizeof(long)); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + goodB2GSink(dataVector); +} + +void good() +{ + goodB2G(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +using namespace CWE690_NULL_Deref_From_Return__long_realloc_72; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard007/C++/0093824_Window2.cpp b/pool/shard007/C++/0093824_Window2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..994d96e080af0f8655c93e0b27dfc9d3a7f67117 --- /dev/null +++ b/pool/shard007/C++/0093824_Window2.cpp @@ -0,0 +1,200 @@ +// Windows/Control/Window2.cpp + +#include "StdAfx.h" + +#ifndef _UNICODE +#include "../../Common/StringConvert.h" +#endif + +#include "Window2.h" + +#ifndef _UNICODE +extern bool g_IsNT; +#endif + +namespace NWindows { + +#ifndef _UNICODE +ATOM MyRegisterClass(CONST WNDCLASSW *wndClass); +#endif + +namespace NControl { + +#ifdef UNDER_CE +#define MY_START_WM_CREATE WM_CREATE +#else +#define MY_START_WM_CREATE WM_NCCREATE +#endif + +static LRESULT CALLBACK WindowProcedure(HWND aHWND, UINT message, WPARAM wParam, LPARAM lParam) +{ + CWindow tempWindow(aHWND); + if (message == MY_START_WM_CREATE) + tempWindow.SetUserDataLongPtr((LONG_PTR)(((LPCREATESTRUCT)lParam)->lpCreateParams)); + CWindow2 *window = (CWindow2 *)(tempWindow.GetUserDataLongPtr()); + if (window != NULL && message == MY_START_WM_CREATE) + window->Attach(aHWND); + if (window == 0) + { + #ifndef _UNICODE + if (g_IsNT) + return DefWindowProcW(aHWND, message, wParam, lParam); + else + #endif + return DefWindowProc(aHWND, message, wParam, lParam); + } + return window->OnMessage(message, wParam, lParam); +} + +bool CWindow2::CreateEx(DWORD exStyle, LPCTSTR className, LPCTSTR windowName, + DWORD style, int x, int y, int width, int height, + HWND parentWindow, HMENU idOrHMenu, HINSTANCE instance) +{ + WNDCLASS wc; + if (!::GetClassInfo(instance, className, &wc)) + { + // wc.style = CS_HREDRAW | CS_VREDRAW; + wc.style = 0; + wc.lpfnWndProc = WindowProcedure; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; + wc.hInstance = instance; + wc.hIcon = NULL; + wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); + wc.lpszMenuName = NULL; + wc.lpszClassName = className; + if (::RegisterClass(&wc) == 0) + return false; + } + return CWindow::CreateEx(exStyle, className, windowName, style, + x, y, width, height, parentWindow, idOrHMenu, instance, this); +} + +#ifndef _UNICODE + +bool CWindow2::CreateEx(DWORD exStyle, LPCWSTR className, LPCWSTR windowName, + DWORD style, int x, int y, int width, int height, + HWND parentWindow, HMENU idOrHMenu, HINSTANCE instance) +{ + bool needRegister; + if (g_IsNT) + { + WNDCLASSW wc; + needRegister = ::GetClassInfoW(instance, className, &wc) == 0; + } + else + { + WNDCLASSA windowClassA; + AString classNameA; + LPCSTR classNameP; + if (IS_INTRESOURCE(className)) + classNameP = (LPCSTR)className; + else + { + classNameA = GetSystemString(className); + classNameP = classNameA; + } + needRegister = ::GetClassInfoA(instance, classNameP, &windowClassA) == 0; + } + if (needRegister) + { + WNDCLASSW wc; + // wc.style = CS_HREDRAW | CS_VREDRAW; + wc.style = 0; + wc.lpfnWndProc = WindowProcedure; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; + wc.hInstance = instance; + wc.hIcon = NULL; + wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); + wc.lpszMenuName = NULL; + wc.lpszClassName = className; + if (MyRegisterClass(&wc) == 0) + return false; + } + return CWindow::CreateEx(exStyle, className, windowName, style, + x, y, width, height, parentWindow, idOrHMenu, instance, this); +} + +#endif + +LRESULT CWindow2::DefProc(UINT message, WPARAM wParam, LPARAM lParam) +{ + #ifndef _UNICODE + if (g_IsNT) + return DefWindowProcW(_window, message, wParam, lParam); + else + #endif + return DefWindowProc(_window, message, wParam, lParam); +} + +LRESULT CWindow2::OnMessage(UINT message, WPARAM wParam, LPARAM lParam) +{ + LRESULT result; + switch (message) + { + case WM_CREATE: + if (!OnCreate((CREATESTRUCT *)lParam)) + return -1; + break; + case WM_COMMAND: + if (OnCommand(wParam, lParam, result)) + return result; + break; + case WM_NOTIFY: + if (OnNotify((UINT)wParam, (LPNMHDR) lParam, result)) + return result; + break; + case WM_DESTROY: + OnDestroy(); + break; + case WM_CLOSE: + OnClose(); + return 0; + case WM_SIZE: + if (OnSize(wParam, LOWORD(lParam), HIWORD(lParam))) + return 0; + } + return DefProc(message, wParam, lParam); +} + +bool CWindow2::OnCommand(WPARAM wParam, LPARAM lParam, LRESULT &result) +{ + return OnCommand(HIWORD(wParam), LOWORD(wParam), lParam, result); +} + +bool CWindow2::OnCommand(int /* code */, int /* itemID */, LPARAM /* lParam */, LRESULT & /* result */) +{ + return false; + // return DefProc(message, wParam, lParam); + /* + if (code == BN_CLICKED) + return OnButtonClicked(itemID, (HWND)lParam); + */ +} + +/* +bool CDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +{ + switch (buttonID) + { + case IDOK: + OnOK(); + break; + case IDCANCEL: + OnCancel(); + break; + case IDHELP: + OnHelp(); + break; + default: + return false; + } + return true; +} + +*/ + +}} diff --git a/pool/shard007/C++/0093826_Camera.cpp b/pool/shard007/C++/0093826_Camera.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4bbfc9f0213ca5a958d9f9b2ce53aaba27cb5f6c --- /dev/null +++ b/pool/shard007/C++/0093826_Camera.cpp @@ -0,0 +1,164 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +// Part of Injectable Generic Camera System +// Copyright(c) 2017, Frans Bouma +// All rights reserved. +// https://github.com/FransBouma/InjectableGenericCameraSystem +// +// 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. +// +// 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 "stdafx.h" +#include "Camera.h" +#include "Defaults.h" +#include "GameConstants.h" + +using namespace DirectX; + +namespace IGCS +{ + Camera::Camera() : _yaw(0), _pitch(0), _roll(0), _movementSpeed(DEFAULT_MOVEMENT_SPEED), + _rotationSpeed(DEFAULT_ROTATION_SPEED), _movementOccurred(false), _lookDirectionInverter(1.0f), + _direction(XMFLOAT3(0.0f, 0.0f, 0.0f)) + { + } + + + Camera::~Camera(void) + { + } + + + XMVECTOR Camera::calculateLookQuaternion() + { + // for the camera 3x3 matrix, it uses X right, Z up and Y into the screen. + XMVECTOR xQ = XMQuaternionRotationNormal(XMVectorSet(1.0f, 0.0f, 0.0f, 1.0f), _pitch); + XMVECTOR yQ = XMQuaternionRotationNormal(XMVectorSet(0.0f, 1.0f, 0.0f, 1.0f), -_yaw); + XMVECTOR zQ = XMQuaternionRotationNormal(XMVectorSet(0.0f, 0.0f, 1.0f, 1.0f), -_roll); // z out of the screen. + + XMVECTOR tmpQ = XMQuaternionMultiply(xQ, yQ); + XMVECTOR qToReturn = XMQuaternionMultiply(zQ, tmpQ); + XMQuaternionNormalize(qToReturn); + return qToReturn; + } + + + void Camera::resetMovement() + { + _movementOccurred = false; + _direction.x = 0.0f; + _direction.y = 0.0f; + _direction.z = 0.0f; + } + + + void Camera::resetAngles() + { + setPitch(INITIAL_PITCH_RADIANS); + setRoll(INITIAL_ROLL_RADIANS); + setYaw(INITIAL_YAW_RADIANS); + } + + + XMFLOAT3 Camera::calculateNewCoords(const XMFLOAT3 currentCoords, const XMVECTOR lookQ) + { + XMFLOAT3 toReturn; + toReturn.x = currentCoords.x; + toReturn.y = currentCoords.y; + toReturn.z = currentCoords.z; + if (_movementOccurred) + { + // for coordinates, it uses X right, Y up, Z out of the screen. + XMVECTOR directionAsQ = XMVectorSet(_direction.x, _direction.y, _direction.z, 0.0f); + XMVECTOR newDirection = XMVector3Rotate(directionAsQ, lookQ); + toReturn.x += XMVectorGetX(newDirection); + toReturn.y += XMVectorGetY(newDirection); + toReturn.z += XMVectorGetZ(newDirection); + //toReturn.z += _direction.z; + } + return toReturn; + } + + + void Camera::moveForward(float amount) + { + _direction.z -= (_movementSpeed * amount); // z out of the screen + _movementOccurred = true; + } + + void Camera::moveRight(float amount) + { + _direction.x += (_movementSpeed * amount); // x is right + _movementOccurred = true; + } + + void Camera::moveUp(float amount) + { + _direction.y += (_movementSpeed * amount * DEFAULT_UP_MOVEMENT_MULTIPLIER); // y is up + _movementOccurred = true; + } + + void Camera::yaw(float amount) + { + _yaw += (_rotationSpeed * amount); + _yaw = clampAngle(_yaw); + } + + void Camera::pitch(float amount) + { + _pitch += (_rotationSpeed * amount * _lookDirectionInverter); + _pitch = clampAngle(_pitch); + } + + void Camera::roll(float amount) + { + _roll += (_rotationSpeed * amount); + _roll = clampAngle(_roll); + } + + void Camera::setPitch(float angle) + { + _pitch = clampAngle(angle); + } + + void Camera::setYaw(float angle) + { + _yaw = clampAngle(angle); + } + + void Camera::setRoll(float angle) + { + _roll = clampAngle(angle); + } + + // Keep the angle in the range 0 to 360 (2*PI) + float Camera::clampAngle(float angle) const + { + while (angle > XM_2PI) + { + angle -= XM_2PI; + } + while (angle < 0) + { + angle += XM_2PI; + } + return angle; + } +} \ No newline at end of file diff --git a/pool/shard007/C++/0093829_loggingDialog.cpp b/pool/shard007/C++/0093829_loggingDialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..247b0f22b3cc386713266016efdb2d45c8d5687a --- /dev/null +++ b/pool/shard007/C++/0093829_loggingDialog.cpp @@ -0,0 +1,199 @@ +#include "ui_loggingDialog.h" +#include "pers.h" +#include "helpers.h" +#include "file.h" +#include "loggingDialog.h" + +#include <QDialog> +#include <QtGui> + +#define LOG_STK_THR 100 +#define LOG_STK_AIL 101 +#define LOG_STK_ELE 102 +#define LOG_STK_RUD 103 + +#define LOG_BTRX 125 +#define LOG_LAT 126 +#define LOG_LONG 127 + +QString ExTelemItems[] = { + "Lat ", + "Long", + "BtRx", + "Stk-THR", + "Stk-AIL", + "Stk-ELE", + "Stk-RUD" +} ; + +#define NUM_TEL_ITEMS 79 + +loggingDialog::loggingDialog(QWidget *parent, struct t_loggingData *inData, struct t_radioData *rData ) : + QDialog(parent), + ui(new Ui::loggingDialog) +{ + uint32_t i ; + uint32_t mask ; + uint32_t offset ; + ui->setupUi(this) ; + this->setWindowTitle( tr("Logging") ) ; + pData = inData ; + lData = pData->logBits ; + lrData = rData ; + + populateSwitchCB(ui->LogSwitchCB, pData->lswitch, rData->type ) ; + i = pData->rate ; + if ( i == 2 ) + { + i = 0 ; + } + else + { + i += 1 ; + } + ui->LogRateCB->setCurrentIndex( i ) ; + ui->newFileCB->setChecked( pData->newFile ) ; + ui->timeoutDSB->setValue( (float)pData->timeout / 10.0 + 2.5 ) ; + + for ( i = 0 ; i < NUM_TEL_ITEMS + 7 ; i += 1 ) + { + uint32_t index = i ; + QListWidgetItem* item ; + QString str ; + + if ( i >= NUM_TEL_ITEMS ) + { + switch ( i ) + { + case NUM_TEL_ITEMS : + index = LOG_LAT ; + break ; + case NUM_TEL_ITEMS + 1 : + index = LOG_LONG ; + break ; + case NUM_TEL_ITEMS + 2 : + index = LOG_BTRX ; + break ; + case NUM_TEL_ITEMS + 3 : + case NUM_TEL_ITEMS + 4 : + case NUM_TEL_ITEMS + 5 : + case NUM_TEL_ITEMS + 6 : + index = LOG_STK_THR + i - (NUM_TEL_ITEMS+3) ; + break ; + } + +// index = LOG_STK_THR + k - (7+sizeof(LogLookup)) ; + str = ExTelemItems[i-NUM_TEL_ITEMS] ; + + } + else + { + str = getTelemString( i + 1 ) ; + } + + offset = index >> 5 ; + mask = 1 << (index & 0x1F) ; + + item = new QListWidgetItem( str, ui->listWidget ) ; + if ( ( i != 45 ) && ( i != 46 ) ) + { + item->setFlags(item->flags() | Qt::ItemIsUserCheckable); // set checkable flag + item->setCheckState(lData[offset] & mask ? Qt::Unchecked : Qt::Checked ) ; // AND initialize check state + } + ui->listWidget->addItem( item) ; + +// cb[i] = new QCheckBox(this) ; + +// cb[i]->setLayoutDirection(Qt::RightToLeft) ; +// cb[i]->setText( getTelemString( i + 1) ) ; +// ui->listWidget->addItem( cb[i] ) ; +// ui->tableWidget->setCellWidget( i, 0, cb[i] ) ; + } + connect( ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); +} + +loggingDialog::~loggingDialog() +{ + delete ui; +} + +void loggingDialog::accept() +{ + uint32_t i ; + uint32_t mask ; + uint32_t offset ; + + for ( i = 0 ; i < NUM_TEL_ITEMS + 7 ; i += 1 ) + { + uint32_t index = i ; + QListWidgetItem* item = ui->listWidget->item( i ) ; + if ( i >= NUM_TEL_ITEMS ) + { + switch ( i ) + { + case NUM_TEL_ITEMS : + index = LOG_LAT ; + break ; + case NUM_TEL_ITEMS + 1 : + index = LOG_LONG ; + break ; + case NUM_TEL_ITEMS + 2 : + index = LOG_BTRX ; + break ; + case NUM_TEL_ITEMS + 3 : + case NUM_TEL_ITEMS + 4 : + case NUM_TEL_ITEMS + 5 : + case NUM_TEL_ITEMS + 6 : + index = LOG_STK_THR + i - (NUM_TEL_ITEMS+3) ; + break ; + } + } + offset = index >> 5 ; + mask = 1 << (index & 0x1F) ; + if ( item->checkState() == Qt::Checked ) + { + lData[offset] &= ~mask ; + } + else + { + lData[offset] |= mask ; + } + } + + pData->lswitch = getSwitchCbValue( ui->LogSwitchCB, lrData->type ) ; + i = ui->LogRateCB->currentIndex() ; + if ( i == 0 ) + { + i = 2 ; + } + else + { + i -= 1 ; + } + pData->rate = i ; + pData->newFile = ui->newFileCB->isChecked() ? 1 : 0 ; + pData->timeout = ( ui->timeoutDSB->value() - 2.45 ) * 10 ; + done(1) ; +} + +void loggingDialog::on_setButton_clicked() +{ + uint32_t i ; + for ( i = 0 ; i < NUM_TEL_ITEMS + 7 ; i += 1 ) + { + QListWidgetItem* item = ui->listWidget->item( i ) ; + item->setCheckState( Qt::Checked ) ; + } +} + +void loggingDialog::on_clearButton_clicked() +{ + uint32_t i ; + for ( i = 0 ; i < NUM_TEL_ITEMS + 7 ; i += 1 ) + { + QListWidgetItem* item = ui->listWidget->item( i ) ; + item->setCheckState( Qt::Unchecked ) ; + } +} + + diff --git a/pool/shard007/C++/0093833_ucoder_ini.cpp b/pool/shard007/C++/0093833_ucoder_ini.cpp new file mode 100644 index 0000000000000000000000000000000000000000..541dc6f9e26ead5d09743069b8b7bf21957fd49b --- /dev/null +++ b/pool/shard007/C++/0093833_ucoder_ini.cpp @@ -0,0 +1,193 @@ +/* + * UniversalContainer library. + * Copyright Jason Denton, 2008,2010. + * Made available under the new BSD license, as described in LICENSE + * + * Send comments and bug reports to jason.denton@gmail.com + * http://www.greatpanic.com/code.html + */ + +#include <stdio.h> +#include <string> +#include <uc/string_util.h> +#include <uc/ucontainer.h> +#include <uc/buffer.h> + +using namespace std; + +/* + These routines handle both encoding a uc as an ini file, and as a + web form. The difference is that in a web form we must urlencode + the key and value pairs, but not the = symbol. The actual work is + done for both by one pair of routines that check a flag, but the + public interface hides this behind explict named wrappers. + */ + +namespace JAD { + + string urlencode(const string& data) + { + int ftype = 0; + static const char* format[] = {"%c","%%%02X"}; + char hold; + string enc; + char tmp[4]; + + for (size_t i = 0; i < data.length(); i++) { + ftype = 0; + hold = data[i]; + if (data[i] == ' ') hold = '+'; + else if (data[i] == '\n') hold = '&'; + else if (data[i] < ',' || data[i] > 'z' || + (data[i] > '9' && data[i] < 'A') || + (data[i] > 'Z' && data[i] < '_') || + (data[i] > '_' && data[i] < 'a')) + ftype = 1; + sprintf(tmp,format[ftype],hold); + enc.append(tmp); + } + + return enc; + } + + string urldecode(const string& data) + { + char hold; + unsigned tmp; + string dec; + const char* cstr = data.c_str(); + + for (size_t i = 0; i < data.length(); i++) { + if (cstr[i] == '%') { + sscanf(cstr+i+1,"%02X",&tmp); + hold = (char) tmp; + i+=2; + } + else if (data[i] == '+') hold = ' '; + else if (data[i] == '&') hold = '\n'; + else hold = data[i]; + dec.push_back(hold); + } + return dec; + } + + UniversalContainer uc_decode_ini(Buffer* buffer, bool form) + { + UniversalContainer uc; + vector<string> parts; + string split = "\n"; + + string line(buffer->data,buffer->length); //read all data + buffer->rpos = buffer->length; + if (form) split = "&"; + vector<string> pairs = string_pieces(line,split); + for (size_t i = 0; i < pairs.size(); i++) { + if (!pairs[i].length()) continue; + parts = string_split(pairs[i],"="); + if (!parts.size()) { + uc.string_interpret(string_chomp(pairs[i])); + continue; + } + if (form) { + parts[0] = urldecode(string_chomp(parts[0])); + parts[1] = urldecode(string_chomp(parts[1])); + } + else { + parts[0] = string_chomp(parts[0]); + parts[1] = string_chomp(parts[1]); + } + uc[parts[0]].string_interpret(parts[1]); + } + return uc; + } + + UniversalContainer uc_decode_form(Buffer* buffer) + { + return uc_decode_ini(buffer,true); + } + + UniversalContainer uc_decode_ini(Buffer* buffer) + { + return uc_decode_ini(buffer,false); + } + + void uc_encode_ini(const UniversalContainer& uc, Buffer* buffer, + string prefix, bool form) + { + UniversalMap::iterator miter; + UniversalMap::iterator mend; + UniversalArray::iterator viter; + UniversalArray::iterator vend; + UniversalContainerType type = uc.get_type(); + + string pfix; + string tmp; + int pos = 0; + char buf[32]; + + switch(type) { + case uc_Map : + pfix = prefix; + if (pfix.length() > 0) pfix.push_back('.'); + mend = uc.map_end(); + for(miter = uc.map_begin(); miter != mend; miter++) { + if (miter->first[0] == '#') continue; //skip metadata + tmp = pfix; + tmp.append(miter->first); + uc_encode_ini(miter->second,buffer,tmp,form); + } + break; + case uc_Array : + pfix = prefix; + if (pfix.length() > 0) pfix.push_back('.'); + vend = uc.vector_end(); + for(viter = uc.vector_begin(); viter != vend; viter++,pos++) { + sprintf(buf,"%d",pos); + tmp = pfix; + tmp.append(buf); + uc_encode_ini(*viter,buffer,tmp,form); + } + break; + case uc_Integer : + case uc_Real : + case uc_Character : + case uc_Boolean : + case uc_Null : + case uc_String : + case uc_WString : + tmp.clear(); + if (prefix.length() != 0) { + tmp.append(prefix); + if (form) tmp = urlencode(tmp); + buffer->put_data(tmp.c_str(),tmp.length()); + buffer->put('='); + } + if (form) tmp = urlencode(uc); + else tmp = static_cast<string>(uc); + buffer->put_data(tmp.c_str(),tmp.length()); + if (form) buffer->put('&'); + else buffer->put('\n'); + break; //if success, stop, else drop through and throw. + default : + throw ucexception(uce_Serialization_Error); + } + } + + Buffer* uc_encode_ini(const UniversalContainer& uc) + { + Buffer* buffer = new Buffer; + string prefix; + uc_encode_ini(uc, buffer, prefix, false); + return buffer; + } + + Buffer* uc_encode_form(const UniversalContainer& uc) + { + Buffer* buffer = new Buffer; + string prefix; + uc_encode_ini(uc, buffer, prefix, true); + buffer->length--; //chop off the trailing &, what a hack + return buffer; + } + +} //end namespace diff --git a/pool/shard007/C++/0093846_locator_test.cpp b/pool/shard007/C++/0093846_locator_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..698fb8159bbc1ad645614b3d71491a83cd56e824 --- /dev/null +++ b/pool/shard007/C++/0093846_locator_test.cpp @@ -0,0 +1,171 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of Qt Creator. +** +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://www.qt.io/licensing. For further information +** use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 or version 3 as published by the Free +** Software Foundation and appearing in the file LICENSE.LGPLv21 and +** LICENSE.LGPLv3 included in the packaging of this file. Please review the +** following information to ensure the GNU Lesser General Public License +** requirements will be met: https://www.gnu.org/licenses/lgpl.html and +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +****************************************************************************/ + + +#include "../coreplugin.h" + +#include "basefilefilter.h" +#include "locatorfiltertest.h" + +#include <coreplugin/testdatadir.h> +#include <utils/fileutils.h> + +#include <QDir> +#include <QTextStream> +#include <QtTest> + +using namespace Core::Tests; + +namespace { + +QTC_DECLARE_MYTESTDATADIR("../../../../tests/locators/") + +class MyBaseFileFilter : public Core::BaseFileFilter +{ +public: + MyBaseFileFilter(const QStringList &theFiles) + { + files().clear(); + files().append(theFiles); + BaseFileFilter::generateFileNames(); + } + + void refresh(QFutureInterface<void> &) {} +}; + +inline QString _(const QByteArray &ba) { return QString::fromLatin1(ba, ba.size()); } + +class ReferenceData +{ +public: + ReferenceData() {} + ReferenceData(const QString &searchText, const ResultDataList &results) + : searchText(searchText), results(results) {} + + QString searchText; + ResultDataList results; +}; + +} // anonymous namespace + +Q_DECLARE_METATYPE(ReferenceData) +Q_DECLARE_METATYPE(QList<ReferenceData>) + +void Core::Internal::CorePlugin::test_basefilefilter() +{ + QFETCH(QStringList, testFiles); + QFETCH(QList<ReferenceData>, referenceDataList); + + MyBaseFileFilter filter(testFiles); + BasicLocatorFilterTest test(&filter); + + foreach (const ReferenceData &reference, referenceDataList) { + const QList<LocatorFilterEntry> filterEntries = test.matchesFor(reference.searchText); + const ResultDataList results = ResultData::fromFilterEntryList(filterEntries); +// QTextStream(stdout) << "----" << endl; +// ResultData::printFilterEntries(results); + QCOMPARE(results, reference.results); + } +} + +void Core::Internal::CorePlugin::test_basefilefilter_data() +{ + QTest::addColumn<QStringList>("testFiles"); + QTest::addColumn<QList<ReferenceData> >("referenceDataList"); + + const QChar pathSeparator = QDir::separator(); + const MyTestDataDir testDir(QLatin1String("testdata_basic")); + const QStringList testFiles = QStringList() + << QDir::fromNativeSeparators(testDir.file(QLatin1String("file.cpp"))) + << QDir::fromNativeSeparators(testDir.file(QLatin1String("main.cpp"))) + << QDir::fromNativeSeparators(testDir.file(QLatin1String("subdir/main.cpp"))); + QStringList testFilesShort; + foreach (const QString &file, testFiles) + testFilesShort << Utils::FileUtils::shortNativePath(Utils::FileName::fromString(file)); + + QTest::newRow("BaseFileFilter-EmptyInput") + << testFiles + << (QList<ReferenceData>() + << ReferenceData( + QString(), + (QList<ResultData>() + << ResultData(_("file.cpp"), testFilesShort.at(0)) + << ResultData(_("main.cpp"), testFilesShort.at(1)) + << ResultData(_("main.cpp"), testFilesShort.at(2)))) + ); + + QTest::newRow("BaseFileFilter-InputIsFileName") + << testFiles + << (QList<ReferenceData>() + << ReferenceData( + _("main.cpp"), + (QList<ResultData>() + << ResultData(_("main.cpp"), testFilesShort.at(1)) + << ResultData(_("main.cpp"), testFilesShort.at(2)))) + ); + + QTest::newRow("BaseFileFilter-InputIsFilePath") + << testFiles + << (QList<ReferenceData>() + << ReferenceData( + QString(_("subdir") + pathSeparator + _("main.cpp")), + (QList<ResultData>() + << ResultData(_("main.cpp"), testFilesShort.at(2)))) + ); + + QTest::newRow("BaseFileFilter-InputIsDirIsPath") + << testFiles + << (QList<ReferenceData>() + << ReferenceData( _("subdir"), QList<ResultData>()) + << ReferenceData( + QString(_("subdir") + pathSeparator + _("main.cpp")), + (QList<ResultData>() + << ResultData(_("main.cpp"), testFilesShort.at(2)))) + ); + + QTest::newRow("BaseFileFilter-InputIsFileNameFilePathFileName") + << testFiles + << (QList<ReferenceData>() + << ReferenceData( + _("main.cpp"), + (QList<ResultData>() + << ResultData(_("main.cpp"), testFilesShort.at(1)) + << ResultData(_("main.cpp"), testFilesShort.at(2)))) + << ReferenceData( + QString(_("subdir") + pathSeparator + _("main.cpp")), + (QList<ResultData>() + << ResultData(_("main.cpp"), testFilesShort.at(2)))) + << ReferenceData( + _("main.cpp"), + (QList<ResultData>() + << ResultData(_("main.cpp"), testFilesShort.at(1)) + << ResultData(_("main.cpp"), testFilesShort.at(2)))) + ); +} diff --git a/pool/shard007/C++/0093847_Conic_Weight_c.cpp b/pool/shard007/C++/0093847_Conic_Weight_c.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dce8e5ddd20634aaa6720d9cd51eb9604e599094 --- /dev/null +++ b/pool/shard007/C++/0093847_Conic_Weight_c.cpp @@ -0,0 +1,26 @@ +// Copyright 2019 Google LLC. +// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. +#include "tools/fiddle/examples.h" +// HASH=6fb11419e99297fe2fe666c296117fb9 +REG_FIDDLE(Conic_Weight_c, 256, 256, true, 0) { +void draw(SkCanvas* canvas) { + const char* verbNames[] = { "move", "line", "quad", "conic", "cubic", "close", "done" }; + const int pointCount[] = { 1 , 2 , 3 , 3 , 4 , 1 , 0 }; + SkPath path; + path.conicTo(20, 0, 20, 20, SK_ScalarInfinity); + SkPath::Iter iter(path, false); + SkPath::Verb verb; + do { + SkPoint points[4]; + verb = iter.next(points); + SkDebugf("%s ", verbNames[(int) verb]); + for (int i = 0; i < pointCount[(int) verb]; ++i) { + SkDebugf("{%g, %g}, ", points[i].fX, points[i].fY); + } + if (SkPath::kConic_Verb == verb) { + SkDebugf("weight = %g", iter.conicWeight()); + } + SkDebugf("\n"); + } while (SkPath::kDone_Verb != verb); +} +} // END FIDDLE diff --git a/pool/shard007/C++/0093851_PCTypeMap.cpp b/pool/shard007/C++/0093851_PCTypeMap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d553c96ee69d95dc19808b56f8007cd6f515bcb9 --- /dev/null +++ b/pool/shard007/C++/0093851_PCTypeMap.cpp @@ -0,0 +1,82 @@ +/****************************************************************************/ +/// @file PCTypeMap.cpp +/// @author Daniel Krajzewicz +/// @date Mon, 05 Dec 2005 +/// @version $Id: PCTypeMap.cpp 11671 2012-01-07 20:14:30Z behrisch $ +/// +// A storage for type mappings +/****************************************************************************/ +// SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/ +// Copyright (C) 2001-2012 DLR (http://www.dlr.de/) and contributors +/****************************************************************************/ +// +// This file is part of SUMO. +// SUMO is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +/****************************************************************************/ + + +// =========================================================================== +// included modules +// =========================================================================== +#ifdef _MSC_VER +#include <windows_config.h> +#else +#include <config.h> +#endif + +#include <string> +#include <map> +#include "PCTypeMap.h" + +#ifdef CHECK_MEMORY_LEAKS +#include <foreign/nvwa/debug_new.h> +#endif // CHECK_MEMORY_LEAKS + + +// =========================================================================== +// method definitions +// =========================================================================== +PCTypeMap::PCTypeMap() {} + + +PCTypeMap::~PCTypeMap() {} + + +bool +PCTypeMap::add(const std::string& id, const std::string& newid, + const std::string& color, const std::string& prefix, + int layer, bool discard, bool allowFill) { + if (has(id)) { + return false; + } + TypeDef td; + td.id = newid; + td.color = color; + td.layer = layer; + td.discard = discard; + td.allowFill = allowFill; + td.prefix = prefix; + myTypes[id] = td; + return true; +} + + +const PCTypeMap::TypeDef& +PCTypeMap::get(const std::string& id) { + return myTypes.find(id)->second; +} + + +bool +PCTypeMap::has(const std::string& id) { + return myTypes.find(id) != myTypes.end(); +} + + + +/****************************************************************************/ + diff --git a/pool/shard007/C++/0093856_CWE590_Free_Memory_Not_on_Heap__delete_struct_alloca_63a.cpp b/pool/shard007/C++/0093856_CWE590_Free_Memory_Not_on_Heap__delete_struct_alloca_63a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dcc7169e46c53fdeb413492c0bd242953805e3ca --- /dev/null +++ b/pool/shard007/C++/0093856_CWE590_Free_Memory_Not_on_Heap__delete_struct_alloca_63a.cpp @@ -0,0 +1,99 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE590_Free_Memory_Not_on_Heap__delete_struct_alloca_63a.cpp +Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete.pointer.label.xml +Template File: sources-sink-63a.tmpl.cpp +*/ +/* + * @description + * CWE: 590 Free Memory Not on Heap + * BadSource: alloca Data buffer is allocated on the stack with alloca() + * GoodSource: Allocate memory on the heap + * Sinks: + * BadSink : Print then free data + * Flow Variant: 63 Data flow: pointer to data passed from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include <wchar.h> + +namespace CWE590_Free_Memory_Not_on_Heap__delete_struct_alloca_63 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink(twoIntsStruct * * dataPtr); + +void bad() +{ + twoIntsStruct * data; + data = NULL; /* Initialize data */ + { + /* FLAW: data is allocated on the stack and deallocated in the BadSink */ + twoIntsStruct * dataBuffer = (twoIntsStruct *)ALLOCA(sizeof(twoIntsStruct)); + dataBuffer->intOne = 1; + dataBuffer->intTwo = 1; + data = dataBuffer; + } + badSink(&data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(twoIntsStruct * * data); + +static void goodG2B() +{ + twoIntsStruct * data; + data = NULL; /* Initialize data */ + { + /* FIX: data is allocated on the heap and deallocated in the BadSink */ + twoIntsStruct * dataBuffer = new twoIntsStruct; + dataBuffer->intOne = 1; + dataBuffer->intTwo = 1; + data = dataBuffer; + } + goodG2BSink(&data); +} + +void good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +using namespace CWE590_Free_Memory_Not_on_Heap__delete_struct_alloca_63; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard007/C++/0093861_imgroupchatmodelitem.cpp b/pool/shard007/C++/0093861_imgroupchatmodelitem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eededd0cf175ad53ff5615f069a987d32d3eba17 --- /dev/null +++ b/pool/shard007/C++/0093861_imgroupchatmodelitem.cpp @@ -0,0 +1,158 @@ +/* + * Copyright 2011 Intel Corporation. + * + * This program is licensed under the terms and conditions of the + * Apache License, version 2.0. The full text of the Apache License is at + * http://www.apache.org/licenses/LICENSE-2.0 + */ + +#include "imgroupchatmodelitem.h" + +#include "imaccountsmodel.h" + +#include <TelepathyQt4Yell/Models/AccountsModel> +#include <TelepathyQt/AvatarData> +#include <TelepathyQt/ReceivedMessage> + + +IMGroupChatModelItem::IMGroupChatModelItem(const QString &accountId, const Tp::TextChannelPtr &channel) : + mAccountId(accountId), + mTextChannel(channel) +{ + connect(mTextChannel.data(), + SIGNAL(groupMembersChanged(Tp::Contacts,Tp::Contacts,Tp::Contacts,Tp::Contacts,Tp::Channel::GroupMemberChangeDetails)), + SLOT(onChanged())); + connect(mTextChannel.data(), + SIGNAL(groupMembersChanged(Tp::Contacts,Tp::Contacts,Tp::Contacts,Tp::Contacts,Tp::Channel::GroupMemberChangeDetails)), + SLOT(onGroupMembersChanged())); + connect(mTextChannel.data(), + SIGNAL(messageReceived(Tp::ReceivedMessage)), + SLOT(onChanged())); + connect(mTextChannel.data(), + SIGNAL(groupFlagsChanged(Tp::ChannelGroupFlags,Tp::ChannelGroupFlags,Tp::ChannelGroupFlags)), + SLOT(onChanged())); + connect(mTextChannel.data(), + SIGNAL(groupSelfContactChanged()), + SLOT(onChanged())); + connect(mTextChannel.data(), + SIGNAL(groupHandleOwnersChanged(Tp::HandleOwnerMap,Tp::UIntList,Tp::UIntList)), + SLOT(onChanged())); + connect(mTextChannel.data(), + SIGNAL(chatStateChanged(Tp::ContactPtr,Tp::ChannelChatState)), + SLOT(onChanged())); + connect(mTextChannel.data(), + SIGNAL(propertyChanged(QString)), + SLOT(onChanged())); + connect(mTextChannel.data(), + SIGNAL(messageReceived(Tp::ReceivedMessage)), + SLOT(onChanged())); +} + +QVariant IMGroupChatModelItem::data(int role) const +{ + switch(role) + { + case Tpy::AccountsModel::ItemRole: + return QVariant::fromValue( + const_cast<QObject *>( + static_cast<const QObject *>(this))); + case Tpy::AccountsModel::IdRole: { + return mTextChannel->objectPath(); + } + case Qt::DisplayRole: + case Tpy::AccountsModel::AliasRole: { + QString alias; + int contactsCount = mTextChannel->groupContacts().count(); + if(mTextChannel->groupContacts().contains(mTextChannel->groupSelfContact())) { + --contactsCount; + } + alias = tr("%1 chatting").arg(QString(contactsCount)); + return alias; + } + case IMAccountsModel::PresenceTypesListRole: { + QList<QVariant> presenceList; + foreach(Tp::ContactPtr contact, mTextChannel->groupContacts()) { + if(contact != mTextChannel->groupSelfContact()) { + presenceList.append(QVariant(contact->presence().type())); + } + } + return QVariant(presenceList); + } + case Tpy::AccountsModel::PresenceTypeRole: + return QVariant(Tp::ConnectionPresenceTypeAvailable); + case Tpy::AccountsModel::AvatarRole: { + return QVariant(QLatin1String("MULTIPLE")); + } + case IMAccountsModel::AvatarsListRole: { + QStringList avatars; + foreach(Tp::ContactPtr contact, mTextChannel->groupContacts()) { + if(contact != mTextChannel->groupSelfContact()) { + avatars.append(contact->avatarData().fileName); + } + } + return QVariant(avatars); + } + case IMAccountsModel::PendingMessagesRole: { + return QVariant(mTextChannel->messageQueue().count()); + } + case IMAccountsModel::IsGroupChatRole: + return QVariant(mTextChannel->isConference()); + case Tpy::AccountsModel::PresenceMessageRole: + return QVariant(QString()); + case Tpy::AccountsModel::PresenceStatusRole: + return Tp::ConnectionPresenceTypeAvailable; + case Tpy::AccountsModel::TextChatCapabilityRole: + return true; + case Tpy::AccountsModel::MediaCallCapabilityRole: + return false; + case Tpy::AccountsModel::AudioCallCapabilityRole: + return false; + case Tpy::AccountsModel::VideoCallCapabilityRole: + return false; + case Tpy::AccountsModel::VideoCallWithAudioCapabilityRole: + return false; + case Tpy::AccountsModel::UpgradeCallCapabilityRole: + return false; + case IMAccountsModel::ChatOpenedRole: + return true; + case IMAccountsModel::MissedAudioCallsRole: + return 0; + case IMAccountsModel::MissedVideoCallsRole: + return 0; + case Tpy::AccountsModel::FileTransferCapabilityRole: + return false; + default: + break; + } + + return QVariant(); +} + +void IMGroupChatModelItem::onChanged() +{ + emit changed(this); +} + +void IMGroupChatModelItem::onGroupMembersChanged() +{ + foreach(Tp::ContactPtr contact, mTextChannel->groupContacts().toList()) { + connect(contact.data(), SIGNAL(avatarDataChanged(Tp::AvatarData)), + SLOT(onChanged())); + connect(contact.data(), SIGNAL(aliasChanged(QString)), + SLOT(onChanged())); + connect(contact.data(), SIGNAL(presenceChanged(Tp::Presence)), + SLOT(onChanged())); + connect(contact.data(), SIGNAL(avatarTokenChanged(QString)), + SLOT(onChanged())); + } +} + +Tp::TextChannelPtr IMGroupChatModelItem::channel() const +{ + return mTextChannel; +} + +QString IMGroupChatModelItem::accountId() const +{ + return mAccountId; +} diff --git a/pool/shard007/C++/0093862_editmod.cpp b/pool/shard007/C++/0093862_editmod.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c3364d854569c52d1d9eabbe774bf9d2a69b5f58 --- /dev/null +++ b/pool/shard007/C++/0093862_editmod.cpp @@ -0,0 +1,158 @@ +/************************************************/ +/* Module editor: Dialog box for editing module */ +/* properties and characteristics */ +/************************************************/ + +#include <fctsys.h> +#include <class_drawpanel.h> +#include <confirm.h> +#include <pcbnew.h> +#include <wxPcbStruct.h> +#include <module_editor_frame.h> +#include <trigo.h> +#include <3d_viewer.h> + +#include <class_module.h> +#include <class_pad.h> +#include <class_edge_mod.h> + +#include <dialog_edit_module_for_BoardEditor.h> + + +/* + * Show module property dialog. + */ +void PCB_EDIT_FRAME::InstallModuleOptionsFrame( MODULE* Module, wxDC* DC ) +{ + if( Module == NULL ) + return; + + DIALOG_MODULE_BOARD_EDITOR* dialog = new DIALOG_MODULE_BOARD_EDITOR( this, Module, DC ); + + int retvalue = dialog->ShowModal(); /* retvalue = + * -1 if abort, + * 0 if exchange module, + * 1 for normal edition + * and 2 for a goto editor command + */ + dialog->Destroy(); + + if( retvalue == 2 ) + { + if( m_ModuleEditFrame == NULL ) + { + m_ModuleEditFrame = new FOOTPRINT_EDIT_FRAME( this, + _( "Module Editor" ), + wxPoint( -1, -1 ), + wxSize( 600, 400 ) ); + } + + m_ModuleEditFrame->Load_Module_From_BOARD( Module ); + SetCurItem( NULL ); + + m_ModuleEditFrame->Show( true ); + m_ModuleEditFrame->Iconize( false ); + } +} + + +/* + * Move the footprint anchor position to the current cursor position. + */ +void FOOTPRINT_EDIT_FRAME::Place_Ancre( MODULE* aModule ) +{ + wxPoint moveVector; + + if( aModule == NULL ) + return; + + moveVector = aModule->m_Pos - GetScreen()->GetCrossHairPosition(); + + aModule->m_Pos = GetScreen()->GetCrossHairPosition(); + + /* Update the relative coordinates: + * The coordinates are relative to the anchor point. + * Calculate deltaX and deltaY from the anchor. */ + RotatePoint( &moveVector, -aModule->m_Orient ); + + // Update the pad coordinates. + for( D_PAD* pad = (D_PAD*) aModule->m_Pads; pad; pad = pad->Next() ) + { + pad->SetPos0( pad->GetPos0() + moveVector ); + } + + // Update the draw element coordinates. + for( EDA_ITEM* item = aModule->m_Drawings; item; item = item->Next() ) + { + switch( item->Type() ) + { + case PCB_MODULE_EDGE_T: + #undef STRUCT + #define STRUCT ( (EDGE_MODULE*) item ) + STRUCT->m_Start0 += moveVector; + STRUCT->m_End0 += moveVector; + break; + + case PCB_MODULE_TEXT_T: + #undef STRUCT + #define STRUCT ( (TEXTE_MODULE*) item ) + STRUCT->SetPos0( STRUCT->GetPos0() + moveVector ); + break; + + default: + break; + } + } + + aModule->CalculateBoundingBox(); +} + + +void FOOTPRINT_EDIT_FRAME::RemoveStruct( EDA_ITEM* Item ) +{ + if( Item == NULL ) + return; + + switch( Item->Type() ) + { + case PCB_PAD_T: + DeletePad( (D_PAD*) Item, false ); + break; + + case PCB_MODULE_TEXT_T: + { + TEXTE_MODULE* text = (TEXTE_MODULE*) Item; + + if( text->GetType() == TEXT_is_REFERENCE ) + { + DisplayError( this, _( "Text is REFERENCE!" ) ); + break; + } + + if( text->GetType() == TEXT_is_VALUE ) + { + DisplayError( this, _( "Text is VALUE!" ) ); + break; + } + + DeleteTextModule( text ); + } + break; + + case PCB_MODULE_EDGE_T: + Delete_Edge_Module( (EDGE_MODULE*) Item ); + m_canvas->Refresh(); + break; + + case PCB_MODULE_T: + break; + + default: + { + wxString Line; + Line.Printf( wxT( " Remove: draw item type %d unknown." ), Item->Type() ); + DisplayError( this, Line ); + } + break; + } +} diff --git a/pool/shard007/C++/0093868_boss_azgalor.cpp b/pool/shard007/C++/0093868_boss_azgalor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..27cb70e0f6abf2db82db5b68e11aa5c4287ede76 --- /dev/null +++ b/pool/shard007/C++/0093868_boss_azgalor.cpp @@ -0,0 +1,284 @@ +/* + + + * Copyright (C) 2005-2014 MaNGOS <http://getmangos.com/> + * Copyright (C) 2006-2014 ScriptDev2 <https://github.com/scriptdev2/scriptdev2/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 3 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "ScriptMgr.h" +#include "ScriptedCreature.h" +#include "hyjal.h" +#include "hyjal_trash.h" + +enum Spells +{ + SPELL_RAIN_OF_FIRE = 31340, + SPELL_DOOM = 31347, + SPELL_HOWL_OF_AZGALOR = 31344, + SPELL_CLEAVE = 31345, + SPELL_BERSERK = 26662, + + SPELL_THRASH = 12787, + SPELL_CRIPPLE = 31406, + SPELL_WARSTOMP = 31408, +}; + +enum Texts +{ + SAY_ONDEATH = 0, + SAY_ONSLAY = 1, + SAY_DOOM = 2, // Not used? + SAY_ONAGGRO = 3, +}; + +class boss_azgalor : public CreatureScript +{ +public: + boss_azgalor() : CreatureScript("boss_azgalor") { } + + CreatureAI* GetAI(Creature* creature) const OVERRIDE + { + return new boss_azgalorAI(creature); + } + + struct boss_azgalorAI : public hyjal_trashAI + { + boss_azgalorAI(Creature* creature) : hyjal_trashAI(creature) + { + instance = creature->GetInstanceScript(); + go = false; + } + + uint32 RainTimer; + uint32 DoomTimer; + uint32 HowlTimer; + uint32 CleaveTimer; + uint32 EnrageTimer; + bool enraged; + + bool go; + + void Reset() OVERRIDE + { + damageTaken = 0; + RainTimer = 20000; + DoomTimer = 50000; + HowlTimer = 30000; + CleaveTimer = 10000; + EnrageTimer = 600000; + enraged = false; + + if (instance && IsEvent) + instance->SetData(DATA_AZGALOREVENT, NOT_STARTED); + } + + void EnterCombat(Unit* /*who*/) OVERRIDE + { + if (instance && IsEvent) + instance->SetData(DATA_AZGALOREVENT, IN_PROGRESS); + Talk(SAY_ONAGGRO); + } + + void KilledUnit(Unit* /*victim*/) OVERRIDE + { + Talk(SAY_ONSLAY); + } + + void WaypointReached(uint32 waypointId) OVERRIDE + { + if (waypointId == 7 && instance) + { + Unit* target = Unit::GetUnit(*me, instance->GetData64(DATA_THRALL)); + if (target && target->IsAlive()) + me->AddThreat(target, 0.0f); + } + } + + void JustDied(Unit* killer) OVERRIDE + { + hyjal_trashAI::JustDied(killer); + if (instance && IsEvent) + instance->SetData(DATA_AZGALOREVENT, DONE); + Talk(SAY_ONDEATH); + } + + void UpdateAI(uint32 diff) OVERRIDE + { + if (IsEvent) + { + //Must update npc_escortAI + npc_escortAI::UpdateAI(diff); + if (!go) + { + go = true; + if (instance) + { + AddWaypoint(0, 5492.91f, -2404.61f, 1462.63f); + AddWaypoint(1, 5531.76f, -2460.87f, 1469.55f); + AddWaypoint(2, 5554.58f, -2514.66f, 1476.12f); + AddWaypoint(3, 5554.16f, -2567.23f, 1479.90f); + AddWaypoint(4, 5540.67f, -2625.99f, 1480.89f); + AddWaypoint(5, 5508.16f, -2659.2f, 1480.15f); + AddWaypoint(6, 5489.62f, -2704.05f, 1482.18f); + AddWaypoint(7, 5457.04f, -2726.26f, 1485.10f); + Start(false, true); + SetDespawnAtEnd(false); + } + } + } + + //Return since we have no target + if (!UpdateVictim()) + return; + + if (RainTimer <= diff) + { + DoCast(SelectTarget(SELECT_TARGET_RANDOM, 0, 30, true), SPELL_RAIN_OF_FIRE); + RainTimer = 20000+rand()%15000; + } else RainTimer -= diff; + + if (DoomTimer <= diff) + { + DoCast(SelectTarget(SELECT_TARGET_RANDOM, 1, 100, true), SPELL_DOOM);//never on tank + DoomTimer = 45000+rand()%5000; + } else DoomTimer -= diff; + + if (HowlTimer <= diff) + { + DoCast(me, SPELL_HOWL_OF_AZGALOR); + HowlTimer = 30000; + } else HowlTimer -= diff; + + if (CleaveTimer <= diff) + { + DoCastVictim(SPELL_CLEAVE); + CleaveTimer = 10000+rand()%5000; + } else CleaveTimer -= diff; + + if (EnrageTimer < diff && !enraged) + { + me->InterruptNonMeleeSpells(false); + DoCast(me, SPELL_BERSERK, true); + enraged = true; + EnrageTimer = 600000; + } else EnrageTimer -= diff; + + DoMeleeAttackIfReady(); + } + }; + +}; + +class npc_lesser_doomguard : public CreatureScript +{ +public: + npc_lesser_doomguard() : CreatureScript("npc_lesser_doomguard") { } + + CreatureAI* GetAI(Creature* creature) const OVERRIDE + { + return new npc_lesser_doomguardAI(creature); + } + + struct npc_lesser_doomguardAI : public hyjal_trashAI + { + npc_lesser_doomguardAI(Creature* creature) : hyjal_trashAI(creature) + { + instance = creature->GetInstanceScript(); + if (instance) + AzgalorGUID = instance->GetData64(DATA_AZGALOR); + } + + uint32 CrippleTimer; + uint32 WarstompTimer; + uint32 CheckTimer; + uint64 AzgalorGUID; + InstanceScript* instance; + + void Reset() OVERRIDE + { + CrippleTimer = 50000; + WarstompTimer = 10000; + DoCast(me, SPELL_THRASH); + CheckTimer = 5000; + } + + void EnterCombat(Unit* /*who*/) OVERRIDE + { + } + + void KilledUnit(Unit* /*victim*/) OVERRIDE + { + } + + void WaypointReached(uint32 /*waypointId*/) OVERRIDE + { + } + + void MoveInLineOfSight(Unit* who) OVERRIDE + + { + if (me->IsWithinDist(who, 50) && !me->IsInCombat() && me->IsValidAttackTarget(who)) + AttackStart(who); + } + + void JustDied(Unit* /*killer*/) OVERRIDE + { + } + + void UpdateAI(uint32 diff) OVERRIDE + { + if (CheckTimer <= diff) + { + if (AzgalorGUID) + { + Creature* boss = Unit::GetCreature((*me), AzgalorGUID); + if (!boss || (boss && boss->isDead())) + { + me->setDeathState(JUST_DIED); + me->RemoveCorpse(); + return; + } + } + CheckTimer = 5000; + } else CheckTimer -= diff; + + //Return since we have no target + if (!UpdateVictim()) + return; + + if (WarstompTimer <= diff) + { + DoCast(me, SPELL_WARSTOMP); + WarstompTimer = 10000+rand()%5000; + } else WarstompTimer -= diff; + + if (CrippleTimer <= diff) + { + DoCast(SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true), SPELL_CRIPPLE); + CrippleTimer = 25000+rand()%5000; + } else CrippleTimer -= diff; + + DoMeleeAttackIfReady(); + } + }; + +}; + +void AddSC_boss_azgalor() +{ + new boss_azgalor(); + new npc_lesser_doomguard(); +} diff --git a/pool/shard007/C++/0093871_ColorPicker.cpp b/pool/shard007/C++/0093871_ColorPicker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..89334c903af91116d9aa9f7ba023fce62aa6bd33 --- /dev/null +++ b/pool/shard007/C++/0093871_ColorPicker.cpp @@ -0,0 +1,59 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "ColorPicker.h" + +class CTCD{ +public: + TColorDialog* cdColor; +public: + CTCD(){ + cdColor = xr_new<TColorDialog>((TComponent*)0); + cdColor->Options = TColorDialogOptions()<<cdFullOpen; + } + ~CTCD(){ + xr_delete(cdColor); + } +}; +static CTCD TCD; + +extern "C" DLL_API bool FSColorPickerExecute(u32* currentColor, LPDWORD originalColor, const int initialExpansionState); +bool SelectColor(u32* currentcolor, bool bDefaultPicker){ + VERIFY(currentcolor); + if (bDefaultPicker){ + TCD.cdColor->Color = TColor(rgb2bgr(*currentcolor)); + if (TCD.cdColor->Execute()){ + *currentcolor = bgr2rgb(TCD.cdColor->Color); + return true; + } + return false; + }else{ + u32 clr=*currentcolor; + if (FSColorPickerExecute(&clr, 0, 0)){ + *currentcolor = clr; + return true; + } + return false; + } +} + +bool SelectColorWin(u32* currentcolor, bool bDefaultPicker){ + VERIFY(currentcolor); + if (bDefaultPicker){ + TCD.cdColor->Color = TColor(*currentcolor); + if (TCD.cdColor->Execute()){ + *currentcolor = TCD.cdColor->Color; + return true; + } + return false; + }else{ + u32 cur = bgr2rgb(*currentcolor); + if (FSColorPickerExecute(&cur, 0, 0)){ + *currentcolor = rgb2bgr(cur); + return true; + } + return false; + } +} + diff --git a/pool/shard007/C++/0093873_least_unsquared_deviation_position_estimator_test.cc b/pool/shard007/C++/0093873_least_unsquared_deviation_position_estimator_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..8823378f616e06adac6f31d874b4e19ced619bd8 --- /dev/null +++ b/pool/shard007/C++/0093873_least_unsquared_deviation_position_estimator_test.cc @@ -0,0 +1,239 @@ +// Copyright (C) 2014 The Regents of the University of California (Regents). +// 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 Regents or University of California 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 HOLDERS 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. +// +// Please contact the author of this library if you have any questions. +// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu) + +#include <ceres/ceres.h> +#include <ceres/rotation.h> +#include <Eigen/Dense> +#include <Eigen/Geometry> +#include <algorithm> +#include <string> +#include <unordered_map> +#include <utility> +#include <vector> + +#include "gtest/gtest.h" +#include "theia/math/util.h" +#include "theia/sfm/camera/camera.h" +#include "theia/sfm/global_pose_estimation/least_unsquared_deviation_position_estimator.h" +#include "theia/sfm/global_pose_estimation/pairwise_translation_and_scale_error.h" +#include "theia/sfm/reconstruction.h" +#include "theia/sfm/track.h" +#include "theia/sfm/transformation/align_point_clouds.h" +#include "theia/sfm/types.h" +#include "theia/util/map_util.h" +#include "theia/util/stringprintf.h" + +namespace theia { + +using Eigen::Vector3d; + +namespace { + +Vector3d RelativeRotationFromTwoRotations(const Vector3d& rotation1, + const Vector3d& rotation2, + const double noise) { + const Eigen::Matrix3d noisy_rotation = + Eigen::AngleAxisd(DegToRad(noise), Vector3d::Random().normalized()) + .toRotationMatrix(); + + Eigen::Matrix3d rotation_matrix1, rotation_matrix2; + ceres::AngleAxisToRotationMatrix(rotation1.data(), rotation_matrix1.data()); + ceres::AngleAxisToRotationMatrix(rotation2.data(), rotation_matrix2.data()); + + const Eigen::AngleAxisd relative_rotation( + noisy_rotation * rotation_matrix2 * rotation_matrix1.transpose()); + return relative_rotation.angle() * relative_rotation.axis(); +} + +Vector3d RelativeTranslationFromTwoPositions(const Vector3d& position1, + const Vector3d& position2, + const Vector3d& rotation1, + const double noise) { + const Eigen::AngleAxisd noisy_translation(DegToRad(noise), + Vector3d::Random().normalized()); + Eigen::Matrix3d rotation_matrix1; + ceres::AngleAxisToRotationMatrix(rotation1.data(), rotation_matrix1.data()); + const Vector3d relative_translation = + rotation_matrix1 * (position2 - position1).normalized(); + return noisy_translation * relative_translation; +} + +// Aligns positions to the ground truth positions via a similarity +// transformation. +void AlignPositions(const std::unordered_map<ViewId, Vector3d>& gt_positions, + std::unordered_map<ViewId, Vector3d>* positions) { + // Collect all positions into a vector. + std::vector<Vector3d> gt_pos, pos; + for (const auto& gt_position : gt_positions) { + gt_pos.push_back(gt_position.second); + const Vector3d& position = FindOrDie(*positions, gt_position.first); + pos.push_back(position); + } + + Eigen::Matrix3d rotation; + Vector3d translation; + double scale; + AlignPointCloudsUmeyama(pos, gt_pos, &rotation, &translation, &scale); + + // Apply the similarity transformation. + for (auto& position : *positions) { + position.second = scale * (rotation * position.second) + translation; + } +} + +} // namespace + +class EstimatePositionsLeastUnsquaredDeviationTest : public ::testing::Test { + public: + void TestLeastUnsquaredDeviationPositionEstimator( + const int num_views, + const int num_view_pairs, + const double pose_noise, + const double position_tolerance) { + // Set up the scene. + SetupScene(num_views); + GetTwoViewInfos(num_view_pairs, pose_noise); + + // Estimate the positions. + LeastUnsquaredDeviationPositionEstimator position_estimator(options_); + std::unordered_map<ViewId, Vector3d> estimated_positions; + EXPECT_TRUE(position_estimator.EstimatePositions(view_pairs_, + orientations_, + &estimated_positions)); + EXPECT_EQ(estimated_positions.size(), positions_.size()); + + // Align the positions and measure the error. + AlignPositions(positions_, &estimated_positions); + for (const auto& position : positions_) { + const Vector3d& estimated_position = + FindOrDie(estimated_positions, position.first); + const double position_error = + (position.second - estimated_position).norm(); + EXPECT_LT(position_error, position_tolerance) + << "\ng.t. position = " << position.second.transpose() + << "\nestimated position = " << estimated_position.transpose(); + } + } + + protected: + void SetUp() { + srand(1234); + } + + void SetupScene(const int num_views) { + // Create random views. + for (int i = 0; i < num_views; i++) { + // Create a random pose. + orientations_[i] = 0.2 * Vector3d::Random(); + positions_[i] = 10.0 * Vector3d::Random(); + } + } + + void GetTwoViewInfos(const int num_view_pairs, const double pose_noise) { + // Create a single connected component. + std::vector<ViewId> view_ids; + view_ids.push_back(0); + for (int i = 1; i < positions_.size(); i++) { + const ViewIdPair view_id_pair(i - 1, i); + view_pairs_[view_id_pair] = CreateTwoViewInfo(view_id_pair, pose_noise); + view_ids.push_back(i); + } + + while (view_pairs_.size() < num_view_pairs) { + std::random_shuffle(view_ids.begin(), view_ids.end()); + const ViewIdPair view_id_pair = + (view_ids[0] < view_ids[1]) ? ViewIdPair(view_ids[0], view_ids[1]) + : ViewIdPair(view_ids[1], view_ids[0]); + if (ContainsKey(view_pairs_, view_id_pair)) { + continue; + } + + view_pairs_[view_id_pair] = CreateTwoViewInfo(view_id_pair, pose_noise); + } + } + + TwoViewInfo CreateTwoViewInfo(const ViewIdPair& view_id_pair, + const double pose_noise) { + CHECK_LT(view_id_pair.first, view_id_pair.second); + TwoViewInfo info; + info.focal_length_1 = 800.0; + info.focal_length_2 = 800.0; + + // These objects will add noise to the relative pose. + const Eigen::Vector2d noise = pose_noise * Eigen::Vector2d::Random(); + + // Determine the relative rotation and add noise. + info.rotation_2 = RelativeRotationFromTwoRotations( + FindOrDie(orientations_, view_id_pair.first), + FindOrDie(orientations_, view_id_pair.second), + noise(0)); + + // Determine the relative position and add noise. + info.position_2 = RelativeTranslationFromTwoPositions( + FindOrDie(positions_, view_id_pair.first), + FindOrDie(positions_, view_id_pair.second), + FindOrDie(orientations_, view_id_pair.first), + noise(1)); + + return info; + } + + LeastUnsquaredDeviationPositionEstimator::Options options_; + std::unordered_map<ViewId, Vector3d> positions_; + std::unordered_map<ViewId, Vector3d> orientations_; + std::unordered_map<ViewIdPair, TwoViewInfo> view_pairs_; +}; + +TEST_F(EstimatePositionsLeastUnsquaredDeviationTest, SmallTestNoNoise) { + static const double kTolerance = 1e-4; + static const int kNumViews = 4; + static const int kNumViewPairs = 6; + TestLeastUnsquaredDeviationPositionEstimator(kNumViews, + kNumViewPairs, + 0.0, + kTolerance); +} + +TEST_F(EstimatePositionsLeastUnsquaredDeviationTest, SmallTestWithNoise) { + static const double kTolerance = 0.1; + static const int kNumViews = 4; + static const int kNumViewPairs = 6; + static const double kPoseNoiseDegrees = 1.0; + TestLeastUnsquaredDeviationPositionEstimator(kNumViews, + kNumViewPairs, + kPoseNoiseDegrees, + kTolerance); +} + +} // namespace theia diff --git a/pool/shard007/C++/0093877_tvlist.cpp b/pool/shard007/C++/0093877_tvlist.cpp new file mode 100644 index 0000000000000000000000000000000000000000..db302a2dc589dd7ac9b27f2e5306474c519a9635 --- /dev/null +++ b/pool/shard007/C++/0093877_tvlist.cpp @@ -0,0 +1,107 @@ +/* smplayer, GUI front-end for mplayer. + Copyright (C) 2006-2014 Ricardo Villalba <rvm@users.sourceforge.net> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include "tvlist.h" +#include "favoriteeditor.h" +#include "images.h" + +#include <QFile> +#include <QDir> +#include <QTextStream> + +TVList::TVList(bool check_channels_conf, Services services, QString filename, QWidget * parent) + : Favorites(filename,parent) +{ +#ifndef Q_OS_WIN + if (check_channels_conf) { + /* f_list.clear(); */ + parse_channels_conf(services); + updateMenu(); + } +#endif +} + +TVList::~TVList() { +} + +Favorites * TVList::createNewObject(QString filename, QWidget * parent) { + return new TVList(false, TV, filename, parent); +} + +#ifndef Q_OS_WIN +void TVList::parse_channels_conf(Services services) { + qDebug("TVList::parse_channels_conf"); + + QString file = QDir::homePath() + "/.mplayer/channels.conf.ter"; + + if (!QFile::exists(file)) { + qDebug("VList::parse_channels_conf: %s doesn't exist", file.toUtf8().constData()); + file = QDir::homePath() + "/.mplayer/channels.conf"; + } + + QFile f( file ); + if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) { + qDebug("TVList::parse_channels_conf: can't open %s", file.toUtf8().constData()); + return; + } + + QTextStream in(&f); + while (!in.atEnd()) { + QString line = in.readLine(); + qDebug("TVList::parse_channels_conf: '%s'", line.toUtf8().constData()); + QString channel = line.section(':', 0, 0); + QString video_pid = line.section(':', 10, 10); + QString audio_pid = line.section(':', 11, 11); + bool is_radio = (video_pid == "0" && audio_pid != "0"); + bool is_data = (video_pid == "0" && audio_pid == "0"); + bool is_tv = (!is_radio && !is_data); + if (!channel.isEmpty()) { + qDebug("TVList::parse_channels_conf: channel: '%s' video_pid: %s audio_pid: %s", channel.toUtf8().constData(),video_pid.toUtf8().constData(),audio_pid.toUtf8().constData()); + QString channel_id = "dvb://"+channel; + if (findFile(channel_id) == -1) { + if ( (services.testFlag(TVList::TV) && is_tv) || + (services.testFlag(TVList::Radio) && is_radio) || + (services.testFlag(TVList::Data) && is_data) ) + { + f_list.append( Favorite(channel, channel_id) ); + } + } + } + } +} +#endif + +void TVList::edit() { + qDebug("TVList::edit"); + + FavoriteEditor e(parent_widget); + + e.setWindowTitle( tr("Channel editor") ); + e.setCaption( tr("TV/Radio list") ); + e.setDialogIcon( Images::icon("open_tv") ); + + e.setData(f_list); + e.setStorePath( QFileInfo(_filename).absolutePath() ); + + if (e.exec() == QDialog::Accepted) { + f_list = e.data(); + updateMenu(); + } +} + +#include "moc_tvlist.cpp" diff --git a/pool/shard007/C++/0093879_mock_motion_event.cc b/pool/shard007/C++/0093879_mock_motion_event.cc new file mode 100644 index 0000000000000000000000000000000000000000..f3de1ddceee8408c8d96a0a43824e0537316f7f0 --- /dev/null +++ b/pool/shard007/C++/0093879_mock_motion_event.cc @@ -0,0 +1,177 @@ +// 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 "ui/events/test/mock_motion_event.h" + +#include "base/logging.h" + +using base::TimeTicks; + +namespace ui { +namespace test { +namespace { + +PointerProperties CreatePointer() { + PointerProperties pointer; + pointer.touch_major = MockMotionEvent::TOUCH_MAJOR; + return pointer; +} + +PointerProperties CreatePointer(float x, float y, int id) { + PointerProperties pointer(x, y); + pointer.touch_major = MockMotionEvent::TOUCH_MAJOR; + pointer.id = id; + return pointer; +} + + +} // namespace + +MockMotionEvent::MockMotionEvent() + : MotionEventGeneric(ACTION_CANCEL, base::TimeTicks(), CreatePointer()) { +} + +MockMotionEvent::MockMotionEvent(Action action) + : MotionEventGeneric(action, base::TimeTicks(), CreatePointer()) { +} + +MockMotionEvent::MockMotionEvent(Action action, + TimeTicks time, + float x0, + float y0) + : MotionEventGeneric(action, time, CreatePointer(x0, y0, 0)) { +} + +MockMotionEvent::MockMotionEvent(Action action, + TimeTicks time, + float x0, + float y0, + float x1, + float y1) + : MotionEventGeneric(action, time, CreatePointer(x0, y0, 0)) { + PushPointer(x1, y1); + if (action == ACTION_POINTER_UP || action == ACTION_POINTER_DOWN) + set_action_index(1); +} + +MockMotionEvent::MockMotionEvent(Action action, + TimeTicks time, + float x0, + float y0, + float x1, + float y1, + float x2, + float y2) + : MotionEventGeneric(action, time, CreatePointer(x0, y0, 0)) { + PushPointer(x1, y1); + PushPointer(x2, y2); + if (action == ACTION_POINTER_UP || action == ACTION_POINTER_DOWN) + set_action_index(2); +} + +MockMotionEvent::MockMotionEvent(Action action, + base::TimeTicks time, + const std::vector<gfx::PointF>& positions) { + set_action(action); + set_event_time(time); + if (action == ACTION_POINTER_UP || action == ACTION_POINTER_DOWN) + set_action_index(static_cast<int>(positions.size()) - 1); + for (size_t i = 0; i < positions.size(); ++i) + PushPointer(positions[i].x(), positions[i].y()); +} + +MockMotionEvent::MockMotionEvent(const MockMotionEvent& other) + : MotionEventGeneric(other) { +} + +MockMotionEvent::~MockMotionEvent() {} + +scoped_ptr<MotionEvent> MockMotionEvent::Clone() const { + return scoped_ptr<MotionEvent>(new MockMotionEvent(*this)); +} + +scoped_ptr<MotionEvent> MockMotionEvent::Cancel() const { + scoped_ptr<MockMotionEvent> event(new MockMotionEvent(*this)); + event->set_action(MotionEvent::ACTION_CANCEL); + return event.Pass(); +} + +void MockMotionEvent::PressPoint(float x, float y) { + ResolvePointers(); + PushPointer(x, y); + if (GetPointerCount() > 1) { + set_action_index(static_cast<int>(GetPointerCount()) - 1); + set_action(ACTION_POINTER_DOWN); + } else { + set_action(ACTION_DOWN); + } +} + +void MockMotionEvent::MovePoint(size_t index, float x, float y) { + ResolvePointers(); + DCHECK_LT(index, GetPointerCount()); + PointerProperties& p = pointer(index); + float dx = x - p.x; + float dy = x - p.y; + p.x = x; + p.y = y; + p.raw_x += dx; + p.raw_y += dy; + set_action(ACTION_MOVE); +} + +void MockMotionEvent::ReleasePoint() { + ResolvePointers(); + DCHECK_GT(GetPointerCount(), 0U); + if (GetPointerCount() > 1) { + set_action_index(static_cast<int>(GetPointerCount()) - 1); + set_action(ACTION_POINTER_UP); + } else { + set_action(ACTION_UP); + } +} + +void MockMotionEvent::CancelPoint() { + ResolvePointers(); + DCHECK_GT(GetPointerCount(), 0U); + set_action(ACTION_CANCEL); +} + +void MockMotionEvent::SetTouchMajor(float new_touch_major) { + for (size_t i = 0; i < GetPointerCount(); ++i) + pointer(i).touch_major = new_touch_major; +} + +void MockMotionEvent::SetRawOffset(float raw_offset_x, float raw_offset_y) { + for (size_t i = 0; i < GetPointerCount(); ++i) { + pointer(i).raw_x = pointer(i).x + raw_offset_x; + pointer(i).raw_y = pointer(i).y + raw_offset_y; + } +} + +void MockMotionEvent::SetToolType(size_t pointer_index, ToolType tool_type) { + DCHECK_LT(pointer_index, GetPointerCount()); + pointer(pointer_index).tool_type = tool_type; +} + +void MockMotionEvent::PushPointer(float x, float y) { + MotionEventGeneric::PushPointer( + CreatePointer(x, y, static_cast<int>(GetPointerCount()))); +} + +void MockMotionEvent::ResolvePointers() { + set_action_index(-1); + switch (GetAction()) { + case ACTION_UP: + case ACTION_POINTER_UP: + case ACTION_CANCEL: + PopPointer(); + return; + default: + break; + } +} + +} // namespace test +} // namespace ui diff --git a/pool/shard007/C++/0093886_sync_file_system_test_util.cc b/pool/shard007/C++/0093886_sync_file_system_test_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..1f0c2144dc6bac46ec2f65e312ec247f2fc9b422 --- /dev/null +++ b/pool/shard007/C++/0093886_sync_file_system_test_util.cc @@ -0,0 +1,64 @@ +// Copyright (c) 2012 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 "chrome/browser/sync_file_system/sync_file_system_test_util.h" + +#include "base/bind.h" +#include "base/message_loop/message_loop_proxy.h" +#include "base/run_loop.h" +#include "base/single_thread_task_runner.h" +#include "base/threading/thread.h" +#include "content/public/test/test_browser_thread.h" +#include "content/public/test/test_browser_thread_bundle.h" +#include "webkit/browser/fileapi/syncable/sync_status_code.h" + +using content::BrowserThread; +using content::TestBrowserThread; + +namespace sync_file_system { + +template <typename R> +void AssignAndQuit(base::RunLoop* run_loop, R* result_out, R result) { + DCHECK(result_out); + DCHECK(run_loop); + *result_out = result; + run_loop->Quit(); +} + +template <typename R> base::Callback<void(R)> +AssignAndQuitCallback(base::RunLoop* run_loop, R* result) { + return base::Bind(&AssignAndQuit<R>, run_loop, base::Unretained(result)); +} + +// Instantiate versions we know callers will need. +template base::Callback<void(SyncStatusCode)> +AssignAndQuitCallback(base::RunLoop*, SyncStatusCode*); + +MultiThreadTestHelper::MultiThreadTestHelper() + : thread_bundle_(new content::TestBrowserThreadBundle( + content::TestBrowserThreadBundle::REAL_FILE_THREAD | + content::TestBrowserThreadBundle::REAL_IO_THREAD)) { +} + +MultiThreadTestHelper::~MultiThreadTestHelper() {} + +void MultiThreadTestHelper::SetUp() { + ui_task_runner_ = + BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI); + file_task_runner_ = + BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE); + io_task_runner_ = + BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO); +} + +void MultiThreadTestHelper::TearDown() { + // Make sure we give some more time to finish tasks on the FILE thread + // before stopping IO/FILE threads. + base::RunLoop run_loop; + file_task_runner_->PostTaskAndReply( + FROM_HERE, base::Bind(&base::DoNothing), run_loop.QuitClosure()); + run_loop.Run(); +} + +} // namespace sync_file_system diff --git a/pool/shard007/C++/0093887_shenandoahConcurrentThread.cpp b/pool/shard007/C++/0093887_shenandoahConcurrentThread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..01210deddb72621fec7cf5c3fe2061425a79527e --- /dev/null +++ b/pool/shard007/C++/0093887_shenandoahConcurrentThread.cpp @@ -0,0 +1,247 @@ +/* +Copyright 2014 Red Hat, Inc. and/or its affiliates. + */ + +#include "gc_implementation/shenandoah/shenandoahConcurrentThread.hpp" +#include "gc_implementation/shenandoah/shenandoahHeap.hpp" +#include "gc_implementation/shenandoah/vm_operations_shenandoah.hpp" +#include "memory/iterator.hpp" +#include "memory/universe.hpp" +#include "runtime/vmThread.hpp" + +SurrogateLockerThread* ShenandoahConcurrentThread::_slt = NULL; + +ShenandoahConcurrentThread::ShenandoahConcurrentThread() : + ConcurrentGCThread(), + _epoch(0), + _concurrent_mark_started(false), + _concurrent_mark_in_progress(false), + _waiting_for_jni_critical(false), + _do_full_gc(false), + _concurrent_mark_aborted(false) +{ + create_and_start(); +} + +ShenandoahConcurrentThread::~ShenandoahConcurrentThread() { + // This is here so that super is called. +} + +void ShenandoahConcurrentThread::notify_jni_critical() { + + assert(_waiting_for_jni_critical, "must be waiting for jni critical notification"); + + // tty->print_cr("doing GC after JNI critical"); + + ShenandoahHeap* heap = ShenandoahHeap::heap(); + + if (_do_full_gc) { + if (heap->concurrent_mark_in_progress()) { + // If we get here, we've been sent into jni-critical-wait at the end of marking, + // and in the meantime got a full-gc scheduled. Clean up the marking stuff, and + // do full-gc. + heap->reset_mark_bitmap(); + heap->stop_concurrent_marking(); + + cm_abort(); + + VM_ShenandoahFullGC full_gc; + VMThread::execute(&full_gc); + + MonitorLockerEx ml(ShenandoahFullGC_lock); + _do_full_gc = false; + ml.notify_all(); + } else { + VM_ShenandoahFullGC full_gc; + VMThread::execute(&full_gc); + } + } else { + VM_ShenandoahStartEvacuation start_evacuation; + VMThread::execute(&start_evacuation); + + } + MonitorLockerEx ml(ShenandoahJNICritical_lock, true); + _waiting_for_jni_critical = false; + ml.notify_all(); +} + +void ShenandoahConcurrentThread::run() { + initialize_in_thread(); + + wait_for_universe_init(); + + // Wait until we have the surrogate locker thread in place. + { + MutexLockerEx x(CGC_lock, true); + while(_slt == NULL && !_should_terminate) { + CGC_lock->wait(true, 200); + } + } + + ShenandoahHeap* heap = ShenandoahHeap::heap(); + + while (!_should_terminate) { + if (_do_full_gc) { + { + MonitorLockerEx ml(ShenandoahJNICritical_lock, true); + if (_full_gc_cause == GCCause::_allocation_failure) { + heap->shenandoahPolicy()->record_allocation_failure_gc(); + } else { + heap->shenandoahPolicy()->record_user_requested_gc(); + } + VM_ShenandoahFullGC full_gc; + VMThread::execute(&full_gc); + while (_waiting_for_jni_critical) { + ml.wait(true); + } + } + MonitorLockerEx ml(ShenandoahFullGC_lock); + _do_full_gc = false; + ml.notify_all(); + } else if (heap->shenandoahPolicy()->should_start_concurrent_mark(heap->used(), + heap->capacity())) + { + + if (ShenandoahGCVerbose) + tty->print("Capacity = "SIZE_FORMAT" Used = "SIZE_FORMAT" doing initMark\n", heap->capacity(), heap->used()); + + if (ShenandoahGCVerbose) tty->print("Starting a mark"); + + VM_ShenandoahInitMark initMark; + VMThread::execute(&initMark); + + if (ShenandoahConcurrentMarking) { + ShenandoahHeap::heap()->concurrentMark()->mark_from_roots(! ShenandoahUpdateRefsEarly); + + VM_ShenandoahFinishMark finishMark; + VMThread::execute(&finishMark); + + } + + { + MonitorLockerEx ml(ShenandoahJNICritical_lock, true); + while (_waiting_for_jni_critical) { + ml.wait(true); + } + } + + if (cm_has_aborted()) { + clear_cm_aborted(); + assert(heap->is_bitmap_clear(), "need to continue with clear mark bitmap"); + assert(! heap->concurrent_mark_in_progress(), "concurrent mark must have terminated"); + continue; + } + if (! _should_terminate) { + // If we're not concurrently evacuating, evacuation is done + // from VM_ShenandoahFinishMark within the VMThread above. + if (ShenandoahConcurrentEvacuation) { + VM_ShenandoahEvacuation evacuation; + evacuation.doit(); + } + } + + if (ShenandoahUpdateRefsEarly) { + if (ShenandoahConcurrentUpdateRefs) { + VM_ShenandoahUpdateRefs update_refs; + VMThread::execute(&update_refs); + heap->update_references(); + } + } else { + VM_ShenandoahFinishEvacuation finish_evac; + VMThread::execute(&finish_evac); + } + + } else { + Thread::current()->_ParkEvent->park(10) ; + // yield(); + } + } +} + +void ShenandoahConcurrentThread::do_full_gc(GCCause::Cause cause) { + + assert(Thread::current()->is_Java_thread(), "expect Java thread here"); + + MonitorLockerEx ml(ShenandoahFullGC_lock); + _do_full_gc = true; + _full_gc_cause = cause; + while (_do_full_gc) { + ml.wait(); + } + assert(_do_full_gc == false, "expect full GC to have completed"); +} + +void ShenandoahConcurrentThread::schedule_full_gc() { + _do_full_gc = true; +} + +void ShenandoahConcurrentThread::print() const { + print_on(tty); +} + +void ShenandoahConcurrentThread::print_on(outputStream* st) const { + st->print("Shenandoah Concurrent Thread"); + Thread::print_on(st); + st->cr(); +} + +void ShenandoahConcurrentThread::sleepBeforeNextCycle() { + assert(false, "Wake up in the GC thread that never sleeps :-)"); +} + +void ShenandoahConcurrentThread::set_cm_started() { + assert(!_concurrent_mark_in_progress, "cycle in progress"); + _concurrent_mark_started = true; +} + +void ShenandoahConcurrentThread::clear_cm_started() { + assert(_concurrent_mark_in_progress, "must be starting a cycle"); + _concurrent_mark_started = false; +} + +bool ShenandoahConcurrentThread::cm_started() { + return _concurrent_mark_started; +} + +void ShenandoahConcurrentThread::set_cm_in_progress() { + assert(_concurrent_mark_started, "must be starting a cycle"); + _concurrent_mark_in_progress = true; +} + +void ShenandoahConcurrentThread::clear_cm_in_progress() { + assert(!_concurrent_mark_started, "must not be starting a new cycle"); + _concurrent_mark_in_progress = false; +} + +bool ShenandoahConcurrentThread::cm_in_progress() { + return _concurrent_mark_in_progress; +} + +void ShenandoahConcurrentThread::start() { + create_and_start(); +} + +void ShenandoahConcurrentThread::yield() { + _sts.yield(); +} + +void ShenandoahConcurrentThread::safepoint_synchronize() { + assert(UseShenandoahGC, "just checking"); + _sts.synchronize(); +} + +void ShenandoahConcurrentThread::safepoint_desynchronize() { + assert(UseShenandoahGC, "just checking"); + _sts.desynchronize(); +} + +void ShenandoahConcurrentThread::makeSurrogateLockerThread(TRAPS) { + assert(UseShenandoahGC, "SLT thread needed only for concurrent GC"); + assert(THREAD->is_Java_thread(), "must be a Java thread"); + assert(_slt == NULL, "SLT already created"); + _slt = SurrogateLockerThread::make(THREAD); +} + +void ShenandoahConcurrentThread::shutdown() { + _should_terminate = true; +} diff --git a/pool/shard007/C++/0093894_task_queue_manager_perftest.cc b/pool/shard007/C++/0093894_task_queue_manager_perftest.cc new file mode 100644 index 0000000000000000000000000000000000000000..e056872e7e5c0a7ba2b8603a84929cfef31c48c7 --- /dev/null +++ b/pool/shard007/C++/0093894_task_queue_manager_perftest.cc @@ -0,0 +1,175 @@ +// 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. + +#include "content/child/scheduler/task_queue_manager.h" + +#include "base/bind.h" +#include "base/threading/thread.h" +#include "content/child/scheduler/scheduler_message_loop_delegate.h" +#include "content/child/scheduler/task_queue_selector.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "testing/perf/perf_test.h" + +namespace content { + +namespace { + +class SelectorForTest : public TaskQueueSelector { + public: + SelectorForTest() {} + + void RegisterWorkQueues( + const std::vector<const base::TaskQueue*>& work_queues) override { + work_queues_ = work_queues; + } + + bool SelectWorkQueueToService(size_t* out_queue_index) override { + // Choose the oldest task, if any. + bool found_one = false; + for (size_t i = 0; i < work_queues_.size(); i++) { + if (work_queues_[i]->empty()) + continue; + // Note: the < comparison is correct due to the fact that the PendingTask + // operator inverts its comparison operation in order to work well in a + // heap based priority queue. + if (!found_one || + work_queues_[*out_queue_index]->front() < work_queues_[i]->front()) + *out_queue_index = i; + found_one = true; + } + CHECK(found_one); + return found_one; + } + + void SetTaskQueueSelectorObserver(Observer* observer) override {} + + void AsValueInto(base::trace_event::TracedValue* state) const override {} + + private: + std::vector<const base::TaskQueue*> work_queues_; + + DISALLOW_COPY_AND_ASSIGN(SelectorForTest); +}; + +} // namespace + +class TaskQueueManagerPerfTest : public testing::Test { + public: + TaskQueueManagerPerfTest() + : num_queues_(0), + max_tasks_in_flight_(0), + num_tasks_in_flight_(0), + num_tasks_to_post_(0), + num_tasks_to_run_(0) {} + + void Initialize(size_t num_queues) { + num_queues_ = num_queues; + message_loop_.reset(new base::MessageLoop()); + selector_ = make_scoped_ptr(new SelectorForTest); + manager_ = make_scoped_ptr(new TaskQueueManager( + num_queues, SchedulerMessageLoopDelegate::Create(message_loop_.get()), + selector_.get(), "fake.category")); + } + + void TestDelayedTask() { + if (--num_tasks_to_run_ == 0) { + message_loop_->Quit(); + } + + num_tasks_in_flight_--; + // NOTE there are only up to max_tasks_in_flight_ pending delayed tasks at + // any one time. Thanks to the lower_num_tasks_to_post going to zero if + // there are a lot of tasks in flight, the total number of task in flight at + // any one time is very variable. + unsigned int lower_num_tasks_to_post = + num_tasks_in_flight_ < (max_tasks_in_flight_ / 2) ? 1 : 0; + unsigned int max_tasks_to_post = + num_tasks_to_post_ % 2 ? lower_num_tasks_to_post : 10; + for (unsigned int i = 0; + i < max_tasks_to_post && num_tasks_in_flight_ < max_tasks_in_flight_ && + num_tasks_to_post_ > 0; + i++) { + // Choose a queue weighted towards queue 0. + unsigned int queue = num_tasks_to_post_ % (num_queues_ + 1); + if (queue == num_queues_) { + queue = 0; + } + // Simulate a mix of short and longer delays. + unsigned int delay = + num_tasks_to_post_ % 2 ? 1 : (10 + num_tasks_to_post_ % 10); + scoped_refptr<base::SingleThreadTaskRunner> runner = + manager_->TaskRunnerForQueue(queue); + runner->PostDelayedTask( + FROM_HERE, base::Bind(&TaskQueueManagerPerfTest::TestDelayedTask, + base::Unretained(this)), + base::TimeDelta::FromMicroseconds(delay)); + num_tasks_in_flight_++; + num_tasks_to_post_--; + } + } + + void ResetAndCallTestDelayedTask(unsigned int num_tasks_to_run) { + num_tasks_in_flight_ = 1; + num_tasks_to_post_ = num_tasks_to_run; + num_tasks_to_run_ = num_tasks_to_run; + TestDelayedTask(); + } + + void Benchmark(const std::string& trace, const base::Closure& test_task) { + base::TimeTicks start = base::TimeTicks::Now(); + base::TimeTicks now; + unsigned long long num_iterations = 0; + do { + test_task.Run(); + message_loop_->Run(); + now = base::TimeTicks::Now(); + num_iterations++; + } while (now - start < base::TimeDelta::FromSeconds(5)); + perf_test::PrintResult( + "task", "", trace, + (now - start).InMicroseconds() / static_cast<double>(num_iterations), + "us/run", true); + } + + size_t num_queues_; + unsigned int max_tasks_in_flight_; + unsigned int num_tasks_in_flight_; + unsigned int num_tasks_to_post_; + unsigned int num_tasks_to_run_; + scoped_ptr<SelectorForTest> selector_; + scoped_ptr<TaskQueueManager> manager_; + scoped_ptr<base::MessageLoop> message_loop_; +}; + +TEST_F(TaskQueueManagerPerfTest, RunTenThousandDelayedTasks_OneQueue) { + Initialize(1u); + + max_tasks_in_flight_ = 200; + Benchmark("run 10000 delayed tasks with one queue", + base::Bind(&TaskQueueManagerPerfTest::ResetAndCallTestDelayedTask, + base::Unretained(this), 10000)); +} + +TEST_F(TaskQueueManagerPerfTest, RunTenThousandDelayedTasks_FourQueues) { + Initialize(4u); + + max_tasks_in_flight_ = 200; + Benchmark("run 10000 delayed tasks with four queues", + base::Bind(&TaskQueueManagerPerfTest::ResetAndCallTestDelayedTask, + base::Unretained(this), 10000)); +} + +TEST_F(TaskQueueManagerPerfTest, RunTenThousandDelayedTasks_EightQueues) { + Initialize(8u); + + max_tasks_in_flight_ = 200; + Benchmark("run 10000 delayed tasks with eight queues", + base::Bind(&TaskQueueManagerPerfTest::ResetAndCallTestDelayedTask, + base::Unretained(this), 10000)); +} + +// TODO(alexclarke): Add additional tests with different mixes of non-delayed vs +// delayed tasks. + +} // namespace content diff --git a/pool/shard007/C++/0093898_protocol-stack.cpp b/pool/shard007/C++/0093898_protocol-stack.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2c02e7bfa6881a93d12fb7b64c501f878207d6e5 --- /dev/null +++ b/pool/shard007/C++/0093898_protocol-stack.cpp @@ -0,0 +1,127 @@ +/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2010,2011,2012 TELEMATICS LAB, Politecnico di Bari + * + * This file is part of LTE-Sim + * + * LTE-Sim is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 3 as + * published by the Free Software Foundation; + * + * LTE-Sim is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with LTE-Sim; if not, see <http://www.gnu.org/licenses/>. + * + * Author: Giuseppe Piro <g.piro@poliba.it> + */ + + +#include "protocol-stack.h" +#include "../device/NetworkNode.h" + +ProtocolStack::ProtocolStack() +{ + m_nas = NULL; + m_rrc = NULL; + m_mac = NULL; + m_pdcp = NULL; +} + +ProtocolStack::ProtocolStack(NetworkNode* device) +{ + m_rrc = new RrcEntity (); + m_rrc->SetDevice (device); + + m_pdcp = new PdcpEntity (); + + m_nas = new NasEntity (); + m_nas->SetDevice (device); + + if (device->GetNodeType() == NetworkNode::TYPE_ENODEB) + { + m_mac = new EnbMacEntity (); + m_mac->SetDevice(device); + } + else if (device->GetNodeType() == NetworkNode::TYPE_BUS) + { + m_mac = new BusMacEntity (); + m_mac->SetDevice(device); + } + else if (device->GetNodeType() == NetworkNode::TYPE_HOME_BASE_STATION) + { + m_mac = new HenbMacEntity (); + m_mac->SetDevice(device); + } + + else if (device->GetNodeType() == NetworkNode::TYPE_UE) + { + m_mac = new UeMacEntity (); + m_mac->SetDevice(device); + } + else + { + //ADD other devices + m_mac = NULL; + } + +} + +ProtocolStack::~ProtocolStack() +{ + delete m_rrc; + delete m_mac; + delete m_nas; + delete m_pdcp; +} + +RrcEntity* +ProtocolStack::GetRrcEntity (void) +{ + return m_rrc; +} + +MacEntity* +ProtocolStack::GetMacEntity (void) +{ + return m_mac; +} + +NasEntity* +ProtocolStack::GetNasEntity (void) +{ + return m_nas; +} + +PdcpEntity* +ProtocolStack::GetPdcpEntity (void) +{ + return m_pdcp; +} + +void +ProtocolStack::SetNasEntity (NasEntity* e) +{ + m_nas = e; +} + +void +ProtocolStack::SetRrcEntity (RrcEntity* e) +{ + m_rrc = e; +} + +void +ProtocolStack::SetMacEntity (MacEntity* e) +{ + m_mac = e; +} + +void +ProtocolStack::SetPdcpEntity (PdcpEntity* e) +{ + m_pdcp = e; +} diff --git a/pool/shard007/C++/0093901_toption.cc b/pool/shard007/C++/0093901_toption.cc new file mode 100644 index 0000000000000000000000000000000000000000..ad8da7079ef8f50c4ff56eca8f1523389da58b2b --- /dev/null +++ b/pool/shard007/C++/0093901_toption.cc @@ -0,0 +1,98 @@ +#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */ + +#define OFTEST_OFSTD_ONLY +#include "dcmtk/ofstd/oftest.h" +#include "dcmtk/ofstd/ofoption.h" + +struct test{test(int,bool){}bool doit(){return OFTrue;}}; + +STD_NAMESPACE istream& operator>>( STD_NAMESPACE istream& in, const test& ) { in.setstate(STD_NAMESPACE istream::failbit); return in; } + +OFTEST(ofstd_optional) +{ + OFCHECK( OFoptional_traits<int>::is_default_constructible::value ); + OFCHECK( !OFoptional_traits<test>::is_default_constructible::value ); + + OFoptional<int> o0( 3 ), o1, o2( OFnullopt ); + + OFCHECK( o0 && *o0 == 3 ); + + OFCHECK( !o1 && !o2 ); + + OFswap( o0, o1 ); + + OFCHECK( !o0 && o1 && *o1 == 3 ); + + o2 = 7; + + o1.swap( o2 ); + + OFCHECK( o1 && o2 ); + OFCHECK( *o1 == 7 && *o2 == 3 ); + OFCHECK( o0 < o2 && o2 <= o1 ); + OFCHECK( o2 != o1 ); + o1 = o2; + OFCHECK( o1 == o2 ); + OFCHECK( o0 == OFnullopt ); + OFCHECK( OFnullopt == o0 ); + OFCHECK( o2 == 3 ); + OFCHECK( 3 == o2 ); + OFCHECK( o1 >= 1 ); + OFCHECK( 1 <= o1 ); + + OFStringStream s( "42" ); + o1 = OFnullopt; + OFCHECK( !o1 ); + OFCHECK( !( s >> o1 ).fail() ); + OFCHECK( o1 && *o1 == 42 ); + s.clear(); + s.str(""); + OFCHECK( s.str().empty() ); + s << o1; + OFCHECK( s.str() == "42" ); + o1 = OFnullopt; + s.clear(); + s.str(""); + s << o1; + OFCHECK( s.str() == "nullopt" ); + s.clear(); + s.str("23"); + s >> o1; + OFCHECK( o1 && *o1 == 23 ); + +#ifdef DCMTK_USE_CXX11_STL + OFoptional<test> o3( 2, OFFalse ); +#else // C++11 + OFoptional<test> o3( test( 2, OFFalse ) ); +#endif // NOT C++11 + OFCHECK( o3 && o3->doit() ); + + s.clear(); + s.str( "test" ); + // if everything works, this sets the failbit + OFCHECK( (s >> o3).fail() ); + + o3 = OFnullopt; + OFCHECK( !o3 ); + + s.clear(); + OFCHECK( !(s >> o3).fail() ); // no fail, since no-call + OFCHECK( !o3 ); + +#ifdef DCMTK_USE_CXX11_STL + o3.emplace( 0, OFFalse ); +#else // C++11 + o3 = test( 0, OFFalse ); +#endif // NOT C++11 + + OFCHECK( o3 && o3->doit() ); + + int i = 8; + OFoptional<int&> o4; + + OFCHECK( !o4 ); + o4 = i; + OFCHECK( o4 ); + *o4 = 19; + OFCHECK( i == 19 ); +} diff --git a/pool/shard007/C++/0093909_ScrollbarThemeNonMacCommon.cpp b/pool/shard007/C++/0093909_ScrollbarThemeNonMacCommon.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0e53c351a8dbfd144ed68289a7b87ad11117170f --- /dev/null +++ b/pool/shard007/C++/0093909_ScrollbarThemeNonMacCommon.cpp @@ -0,0 +1,132 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * Copyright (C) 2008, 2009 Google Inc. + * + * 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. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 "config.h" +#include "platform/scroll/ScrollbarThemeNonMacCommon.h" + +#include "platform/PlatformMouseEvent.h" +#include "platform/graphics/GraphicsContextStateSaver.h" +#include "platform/graphics/paint/DrawingRecorder.h" +#include "platform/scroll/ScrollableArea.h" +#include "platform/scroll/ScrollbarThemeClient.h" + +namespace blink { + +bool ScrollbarThemeNonMacCommon::hasThumb(ScrollbarThemeClient* scrollbar) +{ + // This method is just called as a paint-time optimization to see if + // painting the thumb can be skipped. We don't have to be exact here. + return thumbLength(scrollbar) > 0; +} + +IntRect ScrollbarThemeNonMacCommon::backButtonRect(ScrollbarThemeClient* scrollbar, ScrollbarPart part, bool) +{ + // Windows and Linux just have single arrows. + if (part == BackButtonEndPart) + return IntRect(); + + IntSize size = buttonSize(scrollbar); + return IntRect(scrollbar->x(), scrollbar->y(), size.width(), size.height()); +} + +IntRect ScrollbarThemeNonMacCommon::forwardButtonRect(ScrollbarThemeClient* scrollbar, ScrollbarPart part, bool) +{ + // Windows and Linux just have single arrows. + if (part == ForwardButtonStartPart) + return IntRect(); + + IntSize size = buttonSize(scrollbar); + int x, y; + if (scrollbar->orientation() == HorizontalScrollbar) { + x = scrollbar->x() + scrollbar->width() - size.width(); + y = scrollbar->y(); + } else { + x = scrollbar->x(); + y = scrollbar->y() + scrollbar->height() - size.height(); + } + return IntRect(x, y, size.width(), size.height()); +} + +IntRect ScrollbarThemeNonMacCommon::trackRect(ScrollbarThemeClient* scrollbar, bool) +{ + IntSize bs = buttonSize(scrollbar); + int thickness = scrollbarThickness(scrollbar->controlSize()); + if (scrollbar->orientation() == HorizontalScrollbar) { + // Once the scrollbar becomes smaller than the size of the + // two buttons with a 1 pixel gap, the track disappears. + if (scrollbar->width() <= 2 * bs.width() + 1) + return IntRect(); + return IntRect(scrollbar->x() + bs.width(), scrollbar->y(), scrollbar->width() - 2 * bs.width(), thickness); + } + if (scrollbar->height() <= 2 * bs.height() + 1) + return IntRect(); + return IntRect(scrollbar->x(), scrollbar->y() + bs.height(), thickness, scrollbar->height() - 2 * bs.height()); +} + +void ScrollbarThemeNonMacCommon::paintTrackBackground(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect) +{ + // Just assume a forward track part. We only paint the track as a single piece when there is no thumb. + if (!hasThumb(scrollbar)) + paintTrackPiece(context, scrollbar, rect, ForwardTrackPart); +} + +void ScrollbarThemeNonMacCommon::paintTickmarks(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect) +{ + if (scrollbar->orientation() != VerticalScrollbar) + return; + + if (rect.height() <= 0 || rect.width() <= 0) + return; + + // Get the tickmarks for the frameview. + Vector<IntRect> tickmarks; + scrollbar->getTickmarks(tickmarks); + if (!tickmarks.size()) + return; + + if (DrawingRecorder::useCachedDrawingIfPossible(*context, *scrollbar, DisplayItem::ScrollbarTickmarks)) + return; + + DrawingRecorder recorder(*context, *scrollbar, DisplayItem::ScrollbarTickmarks, rect); + GraphicsContextStateSaver stateSaver(*context); + context->setShouldAntialias(false); + + for (Vector<IntRect>::const_iterator i = tickmarks.begin(); i != tickmarks.end(); ++i) { + // Calculate how far down (in %) the tick-mark should appear. + const float percent = static_cast<float>(i->y()) / scrollbar->totalSize(); + + // Calculate how far down (in pixels) the tick-mark should appear. + const int yPos = rect.y() + (rect.height() * percent); + + FloatRect tickRect(rect.x(), yPos, rect.width(), 3); + context->fillRect(tickRect, Color(0xCC, 0xAA, 0x00, 0xFF)); + + FloatRect tickStroke(rect.x(), yPos + 1, rect.width(), 1); + context->fillRect(tickStroke, Color(0xFF, 0xDD, 0x00, 0xFF)); + } +} + +} // namespace blink diff --git a/pool/shard007/C++/0093916_truncate.cc b/pool/shard007/C++/0093916_truncate.cc new file mode 100644 index 0000000000000000000000000000000000000000..f670cb3cc3b8e86673196dccaabb7095317c214f --- /dev/null +++ b/pool/shard007/C++/0093916_truncate.cc @@ -0,0 +1,63 @@ +// 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 "chrome/browser/chromeos/file_system_provider/operations/truncate.h" + +#include <string> + +#include "chrome/common/extensions/api/file_system_provider.h" +#include "chrome/common/extensions/api/file_system_provider_internal.h" + +namespace chromeos { +namespace file_system_provider { +namespace operations { + +Truncate::Truncate(extensions::EventRouter* event_router, + const ProvidedFileSystemInfo& file_system_info, + const base::FilePath& file_path, + int64_t length, + const storage::AsyncFileUtil::StatusCallback& callback) + : Operation(event_router, file_system_info), + file_path_(file_path), + length_(length), + callback_(callback) {} + +Truncate::~Truncate() { +} + +bool Truncate::Execute(int request_id) { + using extensions::api::file_system_provider::TruncateRequestedOptions; + + if (!file_system_info_.writable()) + return false; + + TruncateRequestedOptions options; + options.file_system_id = file_system_info_.file_system_id(); + options.request_id = request_id; + options.file_path = file_path_.AsUTF8Unsafe(); + options.length = length_; + + return SendEvent( + request_id, + extensions::events::FILE_SYSTEM_PROVIDER_ON_TRUNCATE_REQUESTED, + extensions::api::file_system_provider::OnTruncateRequested::kEventName, + extensions::api::file_system_provider::OnTruncateRequested::Create( + options)); +} + +void Truncate::OnSuccess(int /* request_id */, + std::unique_ptr<RequestValue> /* result */, + bool has_more) { + callback_.Run(base::File::FILE_OK); +} + +void Truncate::OnError(int /* request_id */, + std::unique_ptr<RequestValue> /* result */, + base::File::Error error) { + callback_.Run(error); +} + +} // namespace operations +} // namespace file_system_provider +} // namespace chromeos diff --git a/pool/shard007/C++/0093918_managed_policies.cpp b/pool/shard007/C++/0093918_managed_policies.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0f4f82a12b499fc6d0349fce3c4a9cdf8a1e62c0 --- /dev/null +++ b/pool/shard007/C++/0093918_managed_policies.cpp @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2014, 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. + * + */ + +#include <osquery/core.h> +#include <osquery/logger.h> +#include <osquery/filesystem.h> +#include <osquery/tables.h> + +#include "osquery/core/conversions.h" + +namespace pt = boost::property_tree; +namespace fs = boost::filesystem; + +namespace osquery { +namespace tables { + +const std::string kManagedPoliciesCache = "/Library/Managed Preferences"; + +void genPolicy(const std::string& path, + const std::string& username, + QueryData& results) { + Row r; + r["username"] = fs::path(username).stem().string(); + r["domain"] = fs::path(path).stem().string(); + if (r.at("domain") == "complete") { + // There is a special meta list that aggregates the user/system policy. + return; + } + + r["manual"] = "0"; + pt::ptree tree; + if (!osquery::parsePlist(path, tree).ok()) { + return; + } + + // Iterate through the list of plist keys. + std::map<std::string, std::string> settings; + for (const auto& item : tree) { + auto key = std::string(item.first.data()); + auto value = std::string(item.second.data()); + if (key == "_manualProfile") { + r["manual"] = "1"; + } else if (key == "PayloadUUID") { + r["uuid"] = std::move(value); + } else { + // If the key is not a meta uuid/managed then it is a policy name. + settings[key] = value; + } + } + + // Iterate through the gathered policies names. + for (const auto& setting : settings) { + r["name"] = setting.first; + r["value"] = setting.second; + results.push_back(r); + } +} + +QueryData genManagedPolicies(QueryContext& context) { + QueryData results; + + // All the managed preference policies in the root of the cache apply to + // all users on this device. + std::vector<std::string> policies; + osquery::listFilesInDirectory(kManagedPoliciesCache, policies); + for (const auto& policy : policies) { + genPolicy(policy, "", results); + } + + // Each folder should apply to a set of policies for a specific user. + std::vector<std::string> usernames; + osquery::listDirectoriesInDirectory(kManagedPoliciesCache, usernames); + for (const auto& username : usernames) { + policies.clear(); + osquery::listFilesInDirectory(username, policies); + for (const auto& policy : policies) { + genPolicy(policy, username, results); + } + } + + return results; +} +} +} \ No newline at end of file diff --git a/pool/shard007/C++/0093927_GLSLShader.cpp b/pool/shard007/C++/0093927_GLSLShader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..70666c3569c1d80a92824e98d0b4a3ac95b6b665 --- /dev/null +++ b/pool/shard007/C++/0093927_GLSLShader.cpp @@ -0,0 +1,105 @@ +#include "GLSLShader.h" +#include <string> +#include <fstream> +#include <sstream> +#include <iostream> + +GLSLShader::GLSLShader() +{ + +} + +GLSLShader::GLSLShader(const char* vertF, const char* fragF) +{ + std::string vertCode; + std::string fragCode; + std::ifstream vertFile; + std::ifstream fragFile; + + vertFile.exceptions(std::ifstream::badbit); + fragFile.exceptions(std::ifstream::badbit); + + try + { + vertFile.open(vertF); + fragFile.open(fragF); + + std::stringstream vertStream, fragStream; + vertStream << vertFile.rdbuf(); + fragStream << fragFile.rdbuf(); + + vertFile.close(); + fragFile.close(); + + vertCode = vertStream.str(); + fragCode = fragStream.str(); + } + catch (std::ifstream::failure e) + { + std::cerr << "PNE_PGL_ERR::CANNOT_READ_SHADER" << std::endl; + } + + const char* vShader = vertCode.c_str(); + const char* fShader = fragCode.c_str(); + + GLuint vertex, fragment; + GLint success; + GLchar infoLog[512]; + + vertex = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(vertex, 1, &vShader, NULL); + glCompileShader(vertex); + glGetShaderiv(vertex, GL_COMPILE_STATUS, &success); + if (!success) + { + glGetShaderInfoLog(vertex, 512, NULL, infoLog); + errorString = infoLog; + std::cerr << "Failed to compile GLSL vertex shader. \nError Code: PNE_PGL_ERR::FAILED_GL_VERT_SHADER_COMPILATION | Details:\n" << infoLog << std::endl; + } + + fragment = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(fragment, 1, &fShader, NULL); + glCompileShader(fragment); + + glGetShaderiv(fragment, GL_COMPILE_STATUS, &success); + if (!success) + { + glGetShaderInfoLog(fragment, 512, NULL, infoLog); + errorString = infoLog; + std::cerr << "Failed to compile GLSL fragment shader. \nError Code: PNE_PGL_ERR::FAILED_GL_FRAG_SHADER_COMPILATION | Details:\n" << infoLog << std::endl; + } + + this->_program = glCreateProgram(); + glAttachShader(this->_program, vertex); + glAttachShader(this->_program, fragment); + glLinkProgram(this->_program); + glGetProgramiv(this->_program, GL_LINK_STATUS, &success); + if (!success) + { + glGetProgramInfoLog(this->_program, 512, NULL, infoLog); + errorString = infoLog; + std::cout << "Failed to link GLSL shaders. \nError Code: PNE_PGL_ERR::FAILED_GL_SHADER_LINK | Details:\n" << infoLog << std::endl; + } + glDeleteShader(vertex); + glDeleteShader(fragment); +} + +GLuint GLSLShader::GetProgram() +{ + return _program; +} + +char* GLSLShader::GetErrorString() +{ + return errorString; +} + +void GLSLShader::SetProgram(GLuint program) +{ + this->_program = program; +} + +void GLSLShader::load() +{ + glUseProgram(_program); +} diff --git a/pool/shard007/C++/0093931_Monitor_Point_Registry.cpp b/pool/shard007/C++/0093931_Monitor_Point_Registry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e0650eea018f896860db08520d914d0f39478884 --- /dev/null +++ b/pool/shard007/C++/0093931_Monitor_Point_Registry.cpp @@ -0,0 +1,173 @@ +// $Id: Monitor_Point_Registry.cpp 2622 2015-08-13 18:30:00Z mitza $ + +#include "ace/Monitor_Point_Registry.h" + +#if defined (ACE_HAS_MONITOR_FRAMEWORK) && (ACE_HAS_MONITOR_FRAMEWORK == 1) + +#include "ace/Monitor_Base.h" +#include "ace/Guard_T.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +namespace ACE +{ + namespace Monitor_Control + { + Monitor_Point_Registry* + Monitor_Point_Registry::instance (void) + { + return + ACE_Singleton<Monitor_Point_Registry, ACE_SYNCH_MUTEX>::instance (); + } + + Monitor_Point_Registry::Monitor_Point_Registry (void) + : constraint_id_ (0) + { + } + + bool + Monitor_Point_Registry::add (Monitor_Base* type) + { + if (type == 0) + { + ACELIB_ERROR_RETURN ((LM_ERROR, + "registry add: null type\n"), + false); + } + + int status = 0; + + { + ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, guard, this->mutex_, false); + + type->add_ref (); + + status = this->map_.bind (type->name (), type); + + /// Temporary debugging code. +// ACELIB_DEBUG ((LM_DEBUG, "adding %s\n", type->name ())); + } + + if (status == -1) + { + ACELIB_ERROR_RETURN ((LM_ERROR, + "registry add: map bind failed\n"), + false); + } + + return (status == 0); + } + + bool + Monitor_Point_Registry::remove (const char* name) + { + if (name == 0) + { + ACELIB_ERROR_RETURN ((LM_ERROR, + "registry remove: null name\n"), + false); + } + + int status = 0; + Map::data_type mp = 0; + + { + ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, guard, this->mutex_, false); + + ACE_CString name_str (name, 0, false); + status = this->map_.unbind (name_str, mp); + + /// Temporary debugging code. +// ACELIB_DEBUG ((LM_DEBUG, "removing %s\n", name_str.c_str ())); + } + + if (status == -1) + { +// (JP) There is a problem with this failing on a single ACE_Message_Queue +// monitor per process. I think it is the message queue associated +// with the default reactor, maybe because at that low level, ACE +// is using malloc with placement, then free, which may bypass the +// normal destructors. In any case, it happens only at shutdown +// and there seems to be no memory leak. +// ACELIB_ERROR_RETURN ((LM_ERROR, +// "registry remove: unbind failed for %s\n", +// name), +// false); + } + else + { + mp->remove_ref (); + } + + return (status == 0); + } + + Monitor_Control_Types::NameList + Monitor_Point_Registry::names (void) + { + Monitor_Control_Types::NameList name_holder_; + + { + ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, guard, this->mutex_, 0); + + for (Map::CONST_ITERATOR i (this->map_); !i.done (); i.advance ()) + { + name_holder_.push_back (i->key ()); + } + } + + return name_holder_; + } + + Monitor_Base* + Monitor_Point_Registry::get (const ACE_CString& name) const + { + Map::data_type mp = 0; + + { + ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, guard, this->mutex_, 0); + + this->map_.find (name, mp); + } + + if (mp != 0) + { + mp->add_ref (); + } + + return mp; + } + + long + Monitor_Point_Registry::constraint_id (void) + { + long retval = 0; + + { + ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, guard, this->mutex_, -1); + + retval = this->constraint_id_++; + } + + return retval; + } + + void + Monitor_Point_Registry::cleanup (void) + { + for (Map::ITERATOR i = this->map_.begin (); + i != this->map_.end (); + i.advance ()) + { + Map::ENTRY* entry = 0; + i.next (entry); + entry->int_id_->remove_ref (); + } + } + } +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_MONITOR_FRAMEWORK==1 */ + diff --git a/pool/shard007/C++/0093934_font_fallback_unittest.cc b/pool/shard007/C++/0093934_font_fallback_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..2d60121c657f1cd9ae0ffe2203ee6d95bdee03b4 --- /dev/null +++ b/pool/shard007/C++/0093934_font_fallback_unittest.cc @@ -0,0 +1,275 @@ +// Copyright 2019 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 "ui/gfx/font_fallback_win.h" + +#include <tuple> + +#include "base/stl_util.h" +#include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" +#include "base/test/task_environment.h" +#include "build/build_config.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/icu/source/common/unicode/uchar.h" +#include "third_party/icu/source/common/unicode/uscript.h" +#include "third_party/icu/source/common/unicode/utf16.h" +#include "third_party/skia/include/core/SkTypeface.h" +#include "ui/gfx/platform_font.h" +#include "ui/gfx/test/font_fallback_test_data.h" + +#if defined(OS_WIN) +#include "base/win/windows_version.h" +#endif + +namespace gfx { + +namespace { + +// Options to parameterized unittests. +struct FallbackFontTestOption { + bool ignore_get_fallback_failure = false; + bool skip_code_point_validation = false; + bool skip_fallback_fonts_validation = false; +}; + +const FallbackFontTestOption default_fallback_option = {false, false, false}; +// Options for tests that does not validate the GetFallbackFont(...) parameters. +const FallbackFontTestOption untested_fallback_option = {true, true, true}; + +struct BaseFontTestOption { + const char* family_name = nullptr; + int delta = 0; + int style = 0; + Font::Weight weight = Font::Weight::NORMAL; +}; + +constexpr BaseFontTestOption default_base_font; +constexpr BaseFontTestOption styled_font = {nullptr, 1, Font::FontStyle::ITALIC, + Font::Weight::BOLD}; +constexpr BaseFontTestOption sans_font = {"sans", 2}; + +using FallbackFontTestParamInfo = std:: + tuple<FallbackFontTestCase, FallbackFontTestOption, BaseFontTestOption>; + +class GetFallbackFontTest + : public ::testing::TestWithParam<FallbackFontTestParamInfo> { + public: + GetFallbackFontTest() = default; + + static std::string ParamInfoToString( + ::testing::TestParamInfo<FallbackFontTestParamInfo> param_info) { + const FallbackFontTestCase& test_case = std::get<0>(param_info.param); + const BaseFontTestOption& base_font_option = std::get<2>(param_info.param); + + std::string font_option; + if (base_font_option.family_name) + font_option += std::string("F") + base_font_option.family_name; + if (base_font_option.delta || base_font_option.style || + base_font_option.style) { + font_option += + base::StringPrintf("_d%ds%dw%d", base_font_option.delta, + base_font_option.style, base_font_option.weight); + } + + std::string language_tag = test_case.language_tag; + base::RemoveChars(language_tag, "-", &language_tag); + return std::string("S") + uscript_getName(test_case.script) + "L" + + language_tag + font_option; + } + + void SetUp() override { + std::tie(test_case_, test_option_, base_font_option_) = GetParam(); + } + + protected: + bool GetFallbackFont(const Font& font, + const std::string& language_tag, + Font* result) { + return gfx::GetFallbackFont(font, language_tag, test_case_.text, result); + } + + bool EnsuresScriptSupportCodePoints(const base::string16& text, + UScriptCode script, + const std::string& script_name) { + size_t i = 0; + while (i < text.length()) { + UChar32 code_point; + U16_NEXT(text.c_str(), i, text.size(), code_point); + if (!uscript_hasScript(code_point, script)) { + // Retrieve the appropriate script + UErrorCode script_error; + UScriptCode codepoint_script = + uscript_getScript(code_point, &script_error); + + ADD_FAILURE() << "CodePoint U+" << std::hex << code_point + << " is not part of the script '" << script_name + << "'. Script '" << uscript_getName(codepoint_script) + << "' detected."; + return false; + } + } + return true; + } + + bool DoesFontSupportCodePoints(Font font, const base::string16& text) { + sk_sp<SkTypeface> skia_face = font.platform_font()->GetNativeSkTypeface(); + if (!skia_face) { + ADD_FAILURE() << "Cannot create typeface for '" << font.GetFontName() + << "'."; + return false; + } + + size_t i = 0; + const SkGlyphID kUnsupportedGlyph = 0; + while (i < text.length()) { + UChar32 code_point; + U16_NEXT(text.c_str(), i, text.size(), code_point); + SkGlyphID glyph_id = skia_face->unicharToGlyph(code_point); + if (glyph_id == kUnsupportedGlyph) + return false; + } + return true; + } + + FallbackFontTestCase test_case_; + FallbackFontTestOption test_option_; + BaseFontTestOption base_font_option_; + std::string script_name_; + + private: + // Needed to bypass DCHECK in GetFallbackFont. + base::test::TaskEnvironment task_environment_{ + base::test::TaskEnvironment::MainThreadType::UI}; + + DISALLOW_COPY_AND_ASSIGN(GetFallbackFontTest); +}; + +} // namespace + +// This test ensures the font fallback work correctly. It will ensures that +// 1) The script supports the text +// 2) The input font does not already support the text +// 3) The call to GetFallbackFont() succeed +// 4) The fallback font has a glyph for every character of the text +// +// The previous checks can be activated or deactivated through the class +// FallbackFontTestOption (e.g. test_option_). +TEST_P(GetFallbackFontTest, GetFallbackFont) { + // Default system font. + Font base_font; + // Apply font options to the base font. + if (base_font_option_.family_name) + base_font = Font(base_font_option_.family_name, base_font.GetFontSize()); + if (base_font_option_.delta != 0 || base_font_option_.style != 0 || + base_font_option_.weight != gfx::Font::Weight::NORMAL) { + base_font = + base_font.Derive(base_font_option_.delta, base_font_option_.style, + base_font_option_.weight); + } + +#if defined(OS_WIN) + // Skip testing this call to GetFallbackFont on older windows versions. Some + // fonts only got introduced on windows 10 and the test will fail on previous + // versions. + const bool is_win10 = base::win::GetVersion() >= base::win::Version::WIN10; + if (test_case_.is_win10 && !is_win10) + return; +#endif + + // Retrieve the name of the current script. + script_name_ = uscript_getName(test_case_.script); + + // Validate that tested characters are part of the script. + if (!test_option_.skip_code_point_validation && + !EnsuresScriptSupportCodePoints(test_case_.text, test_case_.script, + script_name_)) { + return; + } + + // The default font already support it, do not try to find a fallback font. + if (DoesFontSupportCodePoints(base_font, test_case_.text)) + return; + + // Retrieve the fallback font. + Font fallback_font; + bool result = + GetFallbackFont(base_font, test_case_.language_tag, &fallback_font); + if (!result) { + if (!test_option_.ignore_get_fallback_failure) + ADD_FAILURE() << "GetFallbackFont failed for '" << script_name_ << "'"; + return; + } + + // Ensure the fallback font is a part of the validation fallback fonts list. + if (!test_option_.skip_fallback_fonts_validation) { + bool valid = std::find(test_case_.fallback_fonts.begin(), + test_case_.fallback_fonts.end(), + fallback_font.GetFontName()) != + test_case_.fallback_fonts.end(); + if (!valid) { + ADD_FAILURE() << "GetFallbackFont failed for '" << script_name_ + << "' invalid fallback font: " + << fallback_font.GetFontName() + << " not among valid options: " + << base::JoinString(test_case_.fallback_fonts, ", "); + return; + } + } + + // Ensure that glyphs exists in the fallback font. + if (!DoesFontSupportCodePoints(fallback_font, test_case_.text)) { + ADD_FAILURE() << "Font '" << fallback_font.GetFontName() + << "' does not matched every CodePoints."; + return; + } +} + +// Produces a font test case for every script. +std::vector<FallbackFontTestCase> GetSampleFontTestCases() { + std::vector<FallbackFontTestCase> result; + + const unsigned int script_max = u_getIntPropertyMaxValue(UCHAR_SCRIPT) + 1; + for (unsigned int i = 0; i < script_max; i++) { + const UScriptCode script = static_cast<UScriptCode>(i); + + // Make a sample text to test the script. + UChar text[8]; + UErrorCode errorCode = U_ZERO_ERROR; + int text_length = + uscript_getSampleString(script, text, base::size(text), &errorCode); + if (text_length <= 0 || errorCode != U_ZERO_ERROR) + continue; + + FallbackFontTestCase test_case(script, "", text, {}); + result.push_back(test_case); + } + return result; +} + +// Ensures that the default fallback font gives known results. The test +// is validating that a known fallback font is given for a given text and font. +INSTANTIATE_TEST_SUITE_P( + KnownExpectedFonts, + GetFallbackFontTest, + testing::Combine( + testing::ValuesIn(kGetFontFallbackTests), + testing::Values(default_fallback_option), + testing::Values(default_base_font, styled_font, sans_font)), + GetFallbackFontTest::ParamInfoToString); + +// Ensures that font fallback functions are working properly for any string +// (strings from any script). The test doesn't enforce the functions to +// give a fallback font. The accepted behaviors are: +// 1) The fallback function failed and doesn't provide a fallback. +// 2) The fallback function succeeded and the font supports every glyphs. +INSTANTIATE_TEST_SUITE_P( + Glyphs, + GetFallbackFontTest, + testing::Combine(testing::ValuesIn(GetSampleFontTestCases()), + testing::Values(untested_fallback_option), + testing::Values(default_base_font)), + GetFallbackFontTest::ParamInfoToString); + +} // namespace gfx diff --git a/pool/shard007/C++/0093937_SkImageRef_ashmem.cpp b/pool/shard007/C++/0093937_SkImageRef_ashmem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..269199faf849a5427bdb2398e0d45a2fe4521a34 --- /dev/null +++ b/pool/shard007/C++/0093937_SkImageRef_ashmem.cpp @@ -0,0 +1,233 @@ +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include "SkImageRef_ashmem.h" +#include "SkImageDecoder.h" +#include "SkFlattenableBuffers.h" +#include "SkThread.h" + +#include "android/ashmem.h" + +#include <sys/mman.h> +#include <unistd.h> + +//#define TRACE_ASH_PURGE // just trace purges + +#ifdef DUMP_IMAGEREF_LIFECYCLE + #define DUMP_ASHMEM_LIFECYCLE +#else +// #define DUMP_ASHMEM_LIFECYCLE +#endif + +// ashmem likes lengths on page boundaries +static size_t roundToPageSize(size_t size) { + const size_t mask = getpagesize() - 1; + size_t newsize = (size + mask) & ~mask; +// SkDebugf("---- oldsize %d newsize %d\n", size, newsize); + return newsize; +} + +SkImageRef_ashmem::SkImageRef_ashmem(const SkImageInfo& info, + SkStreamRewindable* stream, + int sampleSize) + : SkImageRef(info, stream, sampleSize) +{ + fRec.fFD = -1; + fRec.fAddr = NULL; + fRec.fSize = 0; + fRec.fPinned = false; + + fCT = NULL; +} + +SkImageRef_ashmem::~SkImageRef_ashmem() { + SkSafeUnref(fCT); + this->closeFD(); +} + +void SkImageRef_ashmem::closeFD() { + if (-1 != fRec.fFD) { +#ifdef DUMP_ASHMEM_LIFECYCLE + SkDebugf("=== ashmem close %d\n", fRec.fFD); +#endif + SkASSERT(fRec.fAddr); + SkASSERT(fRec.fSize); + munmap(fRec.fAddr, fRec.fSize); + close(fRec.fFD); + fRec.fFD = -1; + } +} + +/////////////////////////////////////////////////////////////////////////////// + +class AshmemAllocator : public SkBitmap::Allocator { +public: + AshmemAllocator(SkAshmemRec* rec, const char name[]) + : fRec(rec), fName(name) {} + + virtual bool allocPixelRef(SkBitmap* bm, SkColorTable* ct) { + const size_t size = roundToPageSize(bm->getSize()); + int fd = fRec->fFD; + void* addr = fRec->fAddr; + + SkASSERT(!fRec->fPinned); + + if (-1 == fd) { + SkASSERT(NULL == addr); + SkASSERT(0 == fRec->fSize); + + fd = ashmem_create_region(fName, size); +#ifdef DUMP_ASHMEM_LIFECYCLE + SkDebugf("=== ashmem_create_region %s size=%d fd=%d\n", fName, size, fd); +#endif + if (-1 == fd) { + SkDebugf("------- imageref_ashmem create failed <%s> %d\n", + fName, size); + return false; + } + + int err = ashmem_set_prot_region(fd, PROT_READ | PROT_WRITE); + if (err) { + SkDebugf("------ ashmem_set_prot_region(%d) failed %d\n", + fd, err); + close(fd); + return false; + } + + addr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); + if (-1 == (long)addr) { + SkDebugf("---------- mmap failed for imageref_ashmem size=%d\n", + size); + close(fd); + return false; + } + + fRec->fFD = fd; + fRec->fAddr = addr; + fRec->fSize = size; + } else { + SkASSERT(addr); + SkASSERT(size == fRec->fSize); + (void)ashmem_pin_region(fd, 0, 0); + } + + bm->setPixels(addr, ct); + fRec->fPinned = true; + return true; + } + +private: + // we just point to our caller's memory, these are not copies + SkAshmemRec* fRec; + const char* fName; +}; + +bool SkImageRef_ashmem::onDecode(SkImageDecoder* codec, SkStreamRewindable* stream, + SkBitmap* bitmap, SkBitmap::Config config, + SkImageDecoder::Mode mode) { + + if (SkImageDecoder::kDecodeBounds_Mode == mode) { + return this->INHERITED::onDecode(codec, stream, bitmap, config, mode); + } + + // Ashmem memory is guaranteed to be initialized to 0. + codec->setSkipWritingZeroes(true); + + AshmemAllocator alloc(&fRec, this->getURI()); + + codec->setAllocator(&alloc); + bool success = this->INHERITED::onDecode(codec, stream, bitmap, config, + mode); + // remove the allocator, since its on the stack + codec->setAllocator(NULL); + + if (success) { + // remember the colortable (if any) + SkRefCnt_SafeAssign(fCT, bitmap->getColorTable()); + return true; + } else { + if (fRec.fPinned) { + ashmem_unpin_region(fRec.fFD, 0, 0); + fRec.fPinned = false; + } + this->closeFD(); + return false; + } +} + +void* SkImageRef_ashmem::onLockPixels(SkColorTable** ct) { + SkASSERT(fBitmap.getPixels() == NULL); + SkASSERT(fBitmap.getColorTable() == NULL); + + // fast case: check if we can just pin and get the cached data + if (-1 != fRec.fFD) { + SkASSERT(fRec.fAddr); + SkASSERT(!fRec.fPinned); + int pin = ashmem_pin_region(fRec.fFD, 0, 0); + + if (ASHMEM_NOT_PURGED == pin) { // yea, fast case! + fBitmap.setPixels(fRec.fAddr, fCT); + fRec.fPinned = true; + } else if (ASHMEM_WAS_PURGED == pin) { + ashmem_unpin_region(fRec.fFD, 0, 0); + // let go of our colortable if we lost the pixels. Well get it back + // again when we re-decode + if (fCT) { + fCT->unref(); + fCT = NULL; + } +#if defined(DUMP_ASHMEM_LIFECYCLE) || defined(TRACE_ASH_PURGE) + SkDebugf("===== ashmem purged %d\n", fBitmap.getSize()); +#endif + } else { + SkDebugf("===== ashmem pin_region(%d) returned %d\n", fRec.fFD, pin); + // return null result for failure + if (ct) { + *ct = NULL; + } + return NULL; + } + } else { + // no FD, will create an ashmem region in allocator + } + + return this->INHERITED::onLockPixels(ct); +} + +void SkImageRef_ashmem::onUnlockPixels() { + this->INHERITED::onUnlockPixels(); + + if (-1 != fRec.fFD) { + SkASSERT(fRec.fAddr); + SkASSERT(fRec.fPinned); + + ashmem_unpin_region(fRec.fFD, 0, 0); + fRec.fPinned = false; + } + + // we clear this with or without an error, since we've either closed or + // unpinned the region + fBitmap.setPixels(NULL, NULL); +} + +void SkImageRef_ashmem::flatten(SkFlattenableWriteBuffer& buffer) const { + this->INHERITED::flatten(buffer); + buffer.writeString(getURI()); +} + +SkImageRef_ashmem::SkImageRef_ashmem(SkFlattenableReadBuffer& buffer) + : INHERITED(buffer) { + fRec.fFD = -1; + fRec.fAddr = NULL; + fRec.fSize = 0; + fRec.fPinned = false; + fCT = NULL; + + SkString uri; + buffer.readString(&uri); + this->setURI(uri); +} diff --git a/pool/shard007/C++/0093939_intel_cpu_topology.cc b/pool/shard007/C++/0093939_intel_cpu_topology.cc new file mode 100644 index 0000000000000000000000000000000000000000..a403ada128b7109ce3fd230468beb37839dda417 --- /dev/null +++ b/pool/shard007/C++/0093939_intel_cpu_topology.cc @@ -0,0 +1,106 @@ +/* + * Copyright 2020 Google LLC + * + * 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 "ecclesia/magent/lib/event_logger/intel_cpu_topology.h" + +#include <string> +#include <vector> + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/numbers.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/str_format.h" +#include "absl/strings/str_split.h" +#include "absl/strings/string_view.h" +#include "ecclesia/lib/logging/globals.h" +#include "ecclesia/lib/logging/logging.h" + +namespace ecclesia { + +namespace { +const IntelCpuTopology::Options &GetDefaultOptions() { + static const IntelCpuTopology::Options *const options = + new IntelCpuTopology::Options(); + return *options; +} + +} // namespace + +IntelCpuTopology::IntelCpuTopology() + : apifs_(GetDefaultOptions().apifs_path), + lpu_to_package_id_(GetCpuTopology()) {} + +IntelCpuTopology::IntelCpuTopology(const Options &options) + : apifs_(options.apifs_path), lpu_to_package_id_(GetCpuTopology()) {} + +// Since CPU topology is static, we will read it when the object being +// constructed, cache it in vector lpu_to_package_id_. +std::vector<int> IntelCpuTopology::GetCpuTopology() { + std::string online; + std::vector<int> ret; + + if (!ReadApifsFile<std::string>("online", &online).ok()) { + ErrorLog() << "Failed to find number of CPUs."; + return ret; + } + std::vector<absl::string_view> range = absl::StrSplit(online, '-'); + + if (range.size() != 2) { + ErrorLog() << "Invalid CPU id range: " << online << '.'; + return ret; + } + + int from, to; + if (!absl::SimpleAtoi(range[0], &from) || from != 0) { + ErrorLog() << "Invalid CPU id range, from: ", range[0]; + return ret; + } + + if (!absl::SimpleAtoi(range[1], &to) || to <= 0) { + ErrorLog() << "Invalid CPU id range, to: ", range[1]; + return ret; + } + + // "from" is always 0 + ret.resize(to - from + 1, -1); + for (int i = from; i <= to; i++) { + ReadApifsFile<int>(absl::StrCat("cpu", i, "/topology/physical_package_id"), + &ret[i]) + .IgnoreError(); + } + + return ret; +} + +absl::StatusOr<int> IntelCpuTopology::GetSocketIdForLpu(int lpu) const { + if (lpu >= (lpu_to_package_id_).size()) { + return absl::NotFoundError(absl::StrFormat("lpu %d is out of range", lpu)); + } + return lpu_to_package_id_[lpu]; +} + +std::vector<int> IntelCpuTopology::GetLpusForSocketId(int socket_id) const { + std::vector<int> lpus; + for (int i = 0; i < lpu_to_package_id_.size(); i++) { + if (lpu_to_package_id_[i] == socket_id) { + lpus.push_back(i); + } + } + return lpus; +} + +} // namespace ecclesia diff --git a/pool/shard007/C++/0093940_profile_buffer_test.cc b/pool/shard007/C++/0093940_profile_buffer_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..1750c18252b1920d46e5731ed93bedb759949fe2 --- /dev/null +++ b/pool/shard007/C++/0093940_profile_buffer_test.cc @@ -0,0 +1,143 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#include "tensorflow/lite/profiling/profile_buffer.h" + +#include <algorithm> +#include <cstdint> +#include <string> +#include <vector> + +#include <gmock/gmock.h> +#include <gtest/gtest.h> + +namespace tflite { +namespace profiling { + +namespace { + +std::vector<const ProfileEvent*> GetProfileEvents(const ProfileBuffer& buffer) { + std::vector<const ProfileEvent*> events; + for (size_t i = 0; i < buffer.Size(); i++) { + events.push_back(buffer.At(i)); + } + return events; +} + +TEST(ProfileBufferTest, Empty) { + ProfileBuffer buffer(/*max_size*/ 0, /*enabled*/ true); + EXPECT_EQ(0, buffer.Size()); +} + +TEST(ProfileBufferTest, AddEvent) { + ProfileBuffer buffer(/*max_size*/ 10, /*enabled*/ true); + EXPECT_EQ(0, buffer.Size()); + auto event_handle = + buffer.BeginEvent("hello", ProfileEvent::EventType::DEFAULT, + /*event_metadata1*/ 42, /*event_metadata2*/ 0); + + EXPECT_GE(event_handle, 0); + EXPECT_EQ(1, buffer.Size()); + + auto event = GetProfileEvents(buffer)[0]; + EXPECT_EQ(event->tag, "hello"); + EXPECT_GT(event->begin_timestamp_us, 0); + EXPECT_EQ(event->event_type, ProfileEvent::EventType::DEFAULT); + EXPECT_EQ(event->event_metadata, 42); + + buffer.EndEvent(event_handle); + EXPECT_EQ(1, buffer.Size()); + EXPECT_GE(event->end_timestamp_us, event->begin_timestamp_us); +} + +TEST(ProfileBufferTest, EndEventWithMetadata) { + ProfileBuffer buffer(/*max_size*/ 10, /*enabled*/ true); + EXPECT_EQ(0, buffer.Size()); + auto event_handle = + buffer.BeginEvent("hello", ProfileEvent::EventType::DEFAULT, + /*event_metadata1*/ 42, /*event_metadata2*/ 0); + const int64_t kEventMetadata1 = 18; + const int64_t kEventMetadata2 = 36; + buffer.EndEvent(event_handle, &kEventMetadata1, &kEventMetadata2); + + EXPECT_GE(event_handle, 0); + EXPECT_EQ(1, buffer.Size()); + auto event = GetProfileEvents(buffer)[0]; + EXPECT_EQ(event->tag, "hello"); + EXPECT_GT(event->begin_timestamp_us, 0); + EXPECT_EQ(event->event_type, ProfileEvent::EventType::DEFAULT); + EXPECT_EQ(event->event_metadata, kEventMetadata1); + EXPECT_EQ(event->extra_event_metadata, kEventMetadata2); + EXPECT_EQ(1, buffer.Size()); + EXPECT_GE(event->end_timestamp_us, event->begin_timestamp_us); +} + +TEST(ProfileBufferTest, OverFlow) { + const int max_size = 4; + ProfileBuffer buffer{max_size, true}; + std::vector<std::string> eventNames = {"first", "second", "third", "fourth"}; + for (int i = 0; i < 2 * max_size; i++) { + buffer.BeginEvent(eventNames[i % 4].c_str(), + ProfileEvent::EventType::DEFAULT, i, 0); + size_t expected_size = std::min(i + 1, max_size); + EXPECT_EQ(expected_size, buffer.Size()); + } + EXPECT_EQ(max_size, buffer.Size()); + for (size_t j = 0; j < buffer.Size(); ++j) { + auto event = buffer.At(j); + EXPECT_EQ(eventNames[j % 4], event->tag); + EXPECT_EQ(ProfileEvent::EventType::DEFAULT, event->event_type); + EXPECT_EQ(j, event->event_metadata); + } +} + +TEST(ProfileBufferTest, DynamicIncrease) { + const int max_initial_size = 4; + ProfileBuffer buffer{max_initial_size, true, + true /*allow_dynamic_buffer_increase*/}; + std::vector<std::string> eventNames = {"first", "second", "third", "fourth"}; + for (int i = 0; i < 2 * max_initial_size; i++) { + buffer.BeginEvent(eventNames[i % 4].c_str(), + ProfileEvent::EventType::DEFAULT, i, 0); + const size_t expected_size = i + 1; + EXPECT_EQ(expected_size, buffer.Size()); + } + EXPECT_EQ(2 * max_initial_size, buffer.Size()); + for (size_t j = 0; j < buffer.Size(); ++j) { + auto event = buffer.At(j); + EXPECT_EQ(eventNames[j % 4], event->tag); + EXPECT_EQ(ProfileEvent::EventType::DEFAULT, event->event_type); + EXPECT_EQ(j, event->event_metadata); + } +} + +TEST(ProfileBufferTest, Enable) { + ProfileBuffer buffer(/*max_size*/ 10, /*enabled*/ false); + EXPECT_EQ(0, buffer.Size()); + auto event_handle = + buffer.BeginEvent("hello", ProfileEvent::EventType::DEFAULT, + /*event_metadata1*/ 42, /*event_metadata2*/ 0); + EXPECT_EQ(kInvalidEventHandle, event_handle); + EXPECT_EQ(0, buffer.Size()); + buffer.SetEnabled(true); + event_handle = + buffer.BeginEvent("hello", ProfileEvent::EventType::DEFAULT, + /*event_metadata1*/ 42, /*event_metadata2*/ 0); + EXPECT_GE(event_handle, 0); + EXPECT_EQ(1, buffer.Size()); +} + +} // namespace +} // namespace profiling +} // namespace tflite diff --git a/pool/shard007/C++/0093942_ai_work_guard.cpp b/pool/shard007/C++/0093942_ai_work_guard.cpp new file mode 100644 index 0000000000000000000000000000000000000000..832600f2a58267a7ce6af1909b7bd8dab0693314 --- /dev/null +++ b/pool/shard007/C++/0093942_ai_work_guard.cpp @@ -0,0 +1,113 @@ +#include "stdafx.h" +#include "jobs_board.hpp" +#include "../../../global_assets/game_designations.hpp" +#include "../../helpers/weapons_helper.hpp" +#include "../../../bengine/geometry.hpp" +#include "ai_work_template.hpp" + +namespace systems { + namespace ai_guard { + + using namespace bengine; + using namespace jobs_board; + using namespace weapons; + + namespace jobs_board { + void evaluate_guarding(job_board_t &board, entity_t &e, position_t &pos, job_evaluator_base_t *jt) { + if (designations->guard_points.empty()) return; // Nothing to guard + if (shooting_range(e, pos)<1) return; // No gun + for (const auto &g : designations->guard_points) { + if (!g.first) { + board[static_cast<int>(distance3d(pos.x, pos.y, pos.z, g.second.x, g.second.y, g.second.z))] = jt; + } + } + } + } + + static bool first_run = true; + + void run(const double &duration_ms) { + if (first_run) { + first_run = false; + register_job_offer<ai_tag_work_guarding>(jobs_board::evaluate_guarding); + } + + ai_work_template<ai_tag_work_guarding> work; + + work.do_ai("Guard Duty", [&work](entity_t &e, ai_tag_work_guarding &g, ai_tag_my_turn_t &t, position_t &pos) { + if (g.step == ai_tag_work_guarding::GOTO_POST) { + if (!g.has_post) { + //std::cout << "Selecting a post\n"; + // Select post and claim it + float distance = std::numeric_limits<float>().max(); + std::size_t i = 0; + std::size_t idx = std::numeric_limits<std::size_t>().max(); + for (auto &gp : designations->guard_points) { + if (!gp.first) { + float d = distance3d(pos.x, pos.y, pos.z, gp.second.x, gp.second.y, gp.second.z); + if (d < distance) { + distance = d; + idx = i; + } + else { + //std::cout << "Guardpost already claimed\n"; + } + } + ++i; + } + + //std::cout << "Picked: " << idx << "\n"; + + if (idx == std::numeric_limits<std::size_t>().max()) { + work.cancel_work_tag(e); + } + else { + g.guard_post = designations->guard_points[idx].second; + designations->guard_points[idx].first = true; + g.has_post = true; + } + return; + } + + if (!g.current_path) { + // Determine a path - bail out if none + g.current_path = find_path(pos, g.guard_post); + if (!g.current_path->success) { + work.cancel_work_tag(e); + for (auto &gp : designations->guard_points) { + if (gp.second == g.guard_post) gp.first = false; + } + } + //std::cout << "Found a path\n"; + return; + } + else { + work.follow_path(g, pos, e, [&g, &e, &work]() { + // Cancel + g.current_path.reset(); + work.cancel_work_tag(e); + for (auto &gp : designations->guard_points) { + if (gp.second == g.guard_post) gp.first = false; + } + return; + }, [&g]() { + // Arrived + g.current_path.reset(); + g.step = ai_tag_work_guarding::guard_steps::GUARD; + return; + }); + } + } + else if (g.step == ai_tag_work_guarding::guard_steps::GUARD) { + // Do we still have ammo? If not, stop guarding. + if (shooting_range(e, pos) == 0) { + work.cancel_work_tag(e); + for (auto &gp : designations->guard_points) { + if (gp.second == g.guard_post) gp.first = false; + } + } + } + }); + } + } +} \ No newline at end of file diff --git a/pool/shard007/C++/0093944_mc146818.cc b/pool/shard007/C++/0093944_mc146818.cc new file mode 100644 index 0000000000000000000000000000000000000000..16ed58e463bb635bf8bf790be4856eb9e0033e83 --- /dev/null +++ b/pool/shard007/C++/0093944_mc146818.cc @@ -0,0 +1,282 @@ +/* + * Copyright (c) 2004-2005 The Regents of The University of Michigan + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer; + * redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution; + * neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Authors: Ali Saidi + * Andrew Schultz + * Miguel Serrano + */ + +#include <sys/time.h> +#include <time.h> + +#include <string> + +#include "base/bitfield.hh" +#include "base/time.hh" +#include "base/trace.hh" +#include "dev/mc146818.hh" +#include "dev/rtcreg.h" + +using namespace std; + +static uint8_t +bcdize(uint8_t val) +{ + uint8_t result; + result = val % 10; + result += (val / 10) << 4; + return result; +} + +static uint8_t +unbcdize(uint8_t val) +{ + uint8_t result; + result = val & 0xf; + result += (val >> 4) * 10; + return result; +} + +void +MC146818::setTime(const struct tm time) +{ + curTime = time; + year = time.tm_year; + // Unix is 0-11 for month, data seet says start at 1 + mon = time.tm_mon + 1; + mday = time.tm_mday; + hour = time.tm_hour; + min = time.tm_min; + sec = time.tm_sec; + + // Datasheet says 1 is sunday + wday = time.tm_wday + 1; + + if (!(stat_regB & RTCB_BIN)) { + // The datasheet says that the year field can be either BCD or + // years since 1900. Linux seems to be happy with years since + // 1900. + year = bcdize(year % 100); + mon = bcdize(mon); + mday = bcdize(mday); + hour = bcdize(hour); + min = bcdize(min); + sec = bcdize(sec); + } +} + +MC146818::MC146818(EventManager *em, const string &n, const struct tm time, + bool bcd, Tick frequency) + : EventManager(em), _name(n), event(this, frequency), tickEvent(this) +{ + memset(clock_data, 0, sizeof(clock_data)); + stat_regA = RTCA_32768HZ | RTCA_1024HZ; + stat_regB = RTCB_PRDC_IE | RTCB_24HR; + if (!bcd) + stat_regB |= RTCB_BIN; + + setTime(time); + DPRINTFN("Real-time clock set to %s", asctime(&time)); +} + +MC146818::~MC146818() +{ + deschedule(tickEvent); + deschedule(event); +} + +void +MC146818::writeData(const uint8_t addr, const uint8_t data) +{ + if (addr < RTC_STAT_REGA) { + clock_data[addr] = data; + curTime.tm_sec = unbcdize(sec); + curTime.tm_min = unbcdize(min); + curTime.tm_hour = unbcdize(hour); + curTime.tm_mday = unbcdize(mday); + curTime.tm_mon = unbcdize(mon) - 1; + curTime.tm_year = ((unbcdize(year) + 50) % 100) + 1950; + curTime.tm_wday = unbcdize(wday) - 1; + } else { + switch (addr) { + case RTC_STAT_REGA: + // The "update in progress" bit is read only. + if ((data & ~RTCA_UIP) != (RTCA_32768HZ | RTCA_1024HZ)) + panic("Unimplemented RTC register A value write!\n"); + replaceBits(stat_regA, data, 6, 0); + break; + case RTC_STAT_REGB: + if ((data & ~(RTCB_PRDC_IE | RTCB_SQWE)) != RTCB_24HR) + panic("Write to RTC reg B bits that are not implemented!\n"); + + if (data & RTCB_PRDC_IE) { + if (!event.scheduled()) + event.scheduleIntr(); + } else { + if (event.scheduled()) + deschedule(event); + } + stat_regB = data; + break; + case RTC_STAT_REGC: + case RTC_STAT_REGD: + panic("RTC status registers C and D are not implemented.\n"); + break; + } + } +} + +uint8_t +MC146818::readData(uint8_t addr) +{ + if (addr < RTC_STAT_REGA) + return clock_data[addr]; + else { + switch (addr) { + case RTC_STAT_REGA: + // toggle UIP bit for linux + stat_regA ^= RTCA_UIP; + return stat_regA; + break; + case RTC_STAT_REGB: + return stat_regB; + break; + case RTC_STAT_REGC: + case RTC_STAT_REGD: + return 0x00; + break; + default: + panic("Shouldn't be here"); + } + } +} + +static time_t +mkutctime(struct tm *time) +{ + time_t ret; + char *tz; + + tz = getenv("TZ"); + setenv("TZ", "", 1); + tzset(); + ret = mktime(time); + if (tz) + setenv("TZ", tz, 1); + else + unsetenv("TZ"); + tzset(); + return ret; +} + +void +MC146818::tickClock() +{ + if (stat_regB & RTCB_NO_UPDT) + return; + time_t calTime = mkutctime(&curTime); + calTime++; + setTime(*gmtime(&calTime)); +} + +void +MC146818::serialize(const string &base, ostream &os) +{ + arrayParamOut(os, base + ".clock_data", clock_data, sizeof(clock_data)); + paramOut(os, base + ".stat_regA", stat_regA); + paramOut(os, base + ".stat_regB", stat_regB); + + // + // save the timer tick and rtc clock tick values to correctly reschedule + // them during unserialize + // + Tick rtcTimerInterruptTickOffset = event.when() - curTick; + SERIALIZE_SCALAR(rtcTimerInterruptTickOffset); + Tick rtcClockTickOffset = event.when() - curTick; + SERIALIZE_SCALAR(rtcClockTickOffset); +} + +void +MC146818::unserialize(const string &base, Checkpoint *cp, + const string §ion) +{ + arrayParamIn(cp, section, base + ".clock_data", clock_data, + sizeof(clock_data)); + paramIn(cp, section, base + ".stat_regA", stat_regA); + paramIn(cp, section, base + ".stat_regB", stat_regB); + + // + // properly schedule the timer and rtc clock events + // + Tick rtcTimerInterruptTickOffset; + UNSERIALIZE_SCALAR(rtcTimerInterruptTickOffset); + reschedule(event, curTick + rtcTimerInterruptTickOffset); + Tick rtcClockTickOffset; + UNSERIALIZE_SCALAR(rtcClockTickOffset); + reschedule(tickEvent, curTick + rtcClockTickOffset); +} + +MC146818::RTCEvent::RTCEvent(MC146818 * _parent, Tick i) + : parent(_parent), interval(i) +{ + DPRINTF(MC146818, "RTC Event Initilizing\n"); + parent->schedule(this, curTick + interval); +} + +void +MC146818::RTCEvent::scheduleIntr() +{ + parent->schedule(this, curTick + interval); +} + +void +MC146818::RTCEvent::process() +{ + DPRINTF(MC146818, "RTC Timer Interrupt\n"); + parent->schedule(this, curTick + interval); + parent->handleEvent(); +} + +const char * +MC146818::RTCEvent::description() const +{ + return "RTC interrupt"; +} + +void +MC146818::RTCTickEvent::process() +{ + DPRINTF(MC146818, "RTC clock tick\n"); + parent->schedule(this, curTick + SimClock::Int::s); + parent->tickClock(); +} + +const char * +MC146818::RTCTickEvent::description() const +{ + return "RTC clock tick"; +} diff --git a/pool/shard007/C++/0093948_savegame2tga.cpp b/pool/shard007/C++/0093948_savegame2tga.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c2f0a63172c882962d95a94a47ee6128b0ea069 --- /dev/null +++ b/pool/shard007/C++/0093948_savegame2tga.cpp @@ -0,0 +1,141 @@ +/* $Id: savegame.cpp,v 1.3 2006/06/16 02:17:53 ingo Exp ingo $ +** ___ ___ _____ _ ___ +** | \| __|_ _|__ ___| | _ ) _____ __ +** | |) | _| | |/ _ \/ _ \ | _ \/ _ \ \ / +** |___/|_| |_|\___/\___/_|___/\___/_\_\ +** +** DFToolBox - Copyright (C) 2006 Ingo Ruhnke <grumbel@gmail.com> +** +** This program is free software; you can redistribute it and/or +** modify it under the terms of the GNU General Public License +** as published by the Free Software Foundation; either version 2 +** of the License, or (at your option) any later version. +** +** This program is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have received a copy of the GNU General Public License +** along with this program; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +** 02111-1307, USA. +*/ + +#include <string.h> +#include <fstream> +#include <iostream> +#include <vector> +#include <stdexcept> + +#include "config.hpp" +#include "shark3d.hpp" +#include "system.hpp" +#include "tga.hpp" + +std::string file_basename(const std::string& name) +{ + std::string::size_type pos1 = name.find_last_of('\\'); + std::string::size_type pos2 = name.find_last_of('/'); + std::string::size_type dotpos = name.find_last_of('.'); + std::string::size_type namestart; + + if (pos1 == std::string::npos && pos2 == std::string::npos) + namestart = 0; + else if (pos1 == std::string::npos) + namestart = pos2 + 1; + else + namestart = pos1 + 1; + + if (dotpos == std::string::npos || dotpos <= namestart || namestart > name.size()) + throw std::runtime_error("Error: Not a valid .sav pathname: " + name); + + return name.substr(namestart, dotpos - namestart); +} + +int main(int argc, char** argv) +{ + try { + Config config; + + if (argc < 2) + { + std::cout << "This program will extract the screenshot from a Dreamfall savegame file." << std::endl; + std::cout << "Usage: " << argv[0] << " SAVEFILE" << std::endl; + } + else if (argc > 2 && strcmp(argv[1], "--build") == 0) + { + if (argc == 4) + { + std::ifstream in_txt(argv[2]); + Shark3D* shark3d = Shark3D::parse_text(in_txt); + in_txt.close(); + + std::ifstream in_tga(argv[3], std::ios::binary); + TGA tga(in_tga); + in_tga.close(); + + // Write + if (config.use_stdout) + { + shark3d->write_binary(std::cout); + std::cout.write(tga.get_data(), tga.get_size()); + } + else + { + std::string outfile = get_exe_path() + "saves/" + file_basename(argv[2]) + ".sav"; + std::cout << "Building save and writing to " << outfile << std::endl; + std::ofstream out(outfile.c_str(), std::ios::binary); + shark3d->write_binary(out); + out.write(tga.get_data(), tga.get_size()); + out.close(); + } + } + else + { + std::cout << "Usage: " << argv[0] << " --build TXTFILE TGAFILE" << std::endl; + } + } + else + { + create_dir(get_exe_path() + "saves/"); + + for(int i = 1; i < argc; ++i) + { + std::vector<char> buffer(256*256*4); + std::ifstream in(argv[i], std::ios::binary); + if (!in) + { + throw std::runtime_error(std::string("Couldn't open: ") + argv[i]); + } + else + { + { + std::string outfile = get_exe_path() + "saves/" + file_basename(argv[i]) + ".txt"; + std::cout << "Writing data to: " << outfile << std::endl; + std::ofstream out(outfile.c_str()); + Shark3D::parse_binary(in)->write_text(out); + } + + { + // Extract screenshot + in.seekg(-(256*256*4), std::ios::end); + in.read(&*buffer.begin(), 256*256*4); + in.close(); + + std::string outfile = get_exe_path() + "saves/" + file_basename(argv[i]) + ".tga"; + std::cout << "Writing screenshot to: " << outfile << std::endl; + std::ofstream out(outfile.c_str(), std::ios::binary); + TGA tga(256,256, buffer); + tga.write(out); + out.close(); + } + } + } + } + } catch(std::exception& err) { + std::cerr << err.what() << std::endl; + } +} + +/* EOF */ diff --git a/pool/shard007/C++/0093950_workqueue.cpp b/pool/shard007/C++/0093950_workqueue.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1c5179439f1ccec008fd54f29e0ea4f18a7fe0df --- /dev/null +++ b/pool/shard007/C++/0093950_workqueue.cpp @@ -0,0 +1,200 @@ +/****************************************************************************** + * Icinga 2 * + * Copyright (C) 2012-2014 Icinga Development Team (http://www.icinga.org) * + * * + * This program is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2 * + * of the License, or (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the Free Software Foundation * + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * + ******************************************************************************/ + +#include "base/workqueue.h" +#include "base/utility.h" +#include "base/debug.h" +#include "base/logger_fwd.h" +#include "base/convert.h" +#include <boost/bind.hpp> +#include <boost/foreach.hpp> + +using namespace icinga; + +int WorkQueue::m_NextID = 1; + +WorkQueue::WorkQueue(size_t maxItems) + : m_ID(m_NextID++), m_MaxItems(maxItems), m_Stopped(false), + m_Processing(false), m_ExceptionCallback(WorkQueue::DefaultExceptionCallback) +{ + m_StatusTimer = make_shared<Timer>(); + m_StatusTimer->SetInterval(10); + m_StatusTimer->OnTimerExpired.connect(boost::bind(&WorkQueue::StatusTimerHandler, this)); + m_StatusTimer->Start(); +} + +WorkQueue::~WorkQueue(void) +{ + Join(true); +} + +/** + * Enqueues a work item. Work items are guaranteed to be executed in the order + * they were enqueued in except when allowInterleaved is true in which case + * the new work item might be run immediately if it's being enqueued from + * within the WorkQueue thread. + */ +void WorkQueue::Enqueue(const WorkCallback& callback, bool allowInterleaved) +{ + bool wq_thread = (boost::this_thread::get_id() == GetThreadId()); + + if (wq_thread && allowInterleaved) { + callback(); + + return; + } + + WorkItem item; + item.Callback = callback; + item.AllowInterleaved = allowInterleaved; + + boost::mutex::scoped_lock lock(m_Mutex); + + if (m_Thread.get_id() == boost::thread::id()) + m_Thread = boost::thread(boost::bind(&WorkQueue::WorkerThreadProc, this)); + + if (!wq_thread) { + while (m_Items.size() >= m_MaxItems) + m_CVFull.wait(lock); + } + + m_Items.push_back(item); + + if (m_Items.size() == 1) + m_CVEmpty.notify_all(); +} + +void WorkQueue::Join(bool stop) +{ + boost::mutex::scoped_lock lock(m_Mutex); + + while (m_Processing || !m_Items.empty()) + m_CVStarved.wait(lock); + + if (stop) { + m_Stopped = true; + m_CVEmpty.notify_all(); + lock.unlock(); + + if (m_Thread.joinable()) + m_Thread.join(); + } +} + +boost::thread::id WorkQueue::GetThreadId(void) const +{ + return m_Thread.get_id(); +} + +void WorkQueue::SetExceptionCallback(const ExceptionCallback& callback) +{ + boost::mutex::scoped_lock lock(m_Mutex); + + m_ExceptionCallback = callback; +} + +size_t WorkQueue::GetLength(void) +{ + boost::mutex::scoped_lock lock(m_Mutex); + + return m_Items.size(); +} + +void WorkQueue::DefaultExceptionCallback(boost::exception_ptr exp) +{ + throw; +} + +void WorkQueue::StatusTimerHandler(void) +{ + boost::mutex::scoped_lock lock(m_Mutex); + + Log(LogDebug, "base", "WQ #" + Convert::ToString(m_ID) + " items: " + Convert::ToString(m_Items.size())); +} + +void WorkQueue::WorkerThreadProc(void) +{ + std::ostringstream idbuf; + idbuf << "WQ #" << m_ID; + Utility::SetThreadName(idbuf.str()); + + boost::mutex::scoped_lock lock(m_Mutex); + + for (;;) { + while (m_Items.empty() && !m_Stopped) + m_CVEmpty.wait(lock); + + if (m_Stopped) + break; + + std::deque<WorkItem> items; + m_Items.swap(items); + + if (items.size() >= m_MaxItems) + m_CVFull.notify_all(); + + m_Processing = true; + + lock.unlock(); + + BOOST_FOREACH(WorkItem& wi, items) { + try { + wi.Callback(); + } + catch (const std::exception&) { + lock.lock(); + + ExceptionCallback callback = m_ExceptionCallback; + + lock.unlock(); + + callback(boost::current_exception()); + } + } + + lock.lock(); + + m_Processing = false; + + m_CVStarved.notify_all(); + } +} + +ParallelWorkQueue::ParallelWorkQueue(void) + : m_QueueCount(boost::thread::hardware_concurrency()), + m_Queues(new WorkQueue[m_QueueCount]), + m_Index(0) +{ } + +ParallelWorkQueue::~ParallelWorkQueue(void) +{ + delete[] m_Queues; +} + +void ParallelWorkQueue::Enqueue(const boost::function<void(void)>& callback) +{ + m_Index++; + m_Queues[m_Index % m_QueueCount].Enqueue(callback); +} + +void ParallelWorkQueue::Join(void) +{ + for (unsigned int i = 0; i < m_QueueCount; i++) + m_Queues[i].Join(); +} diff --git a/pool/shard007/C++/0093955_program.cpp b/pool/shard007/C++/0093955_program.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6112c0af51405536cee5cc5f949638b3308fcedf --- /dev/null +++ b/pool/shard007/C++/0093955_program.cpp @@ -0,0 +1,214 @@ +/* + * Copyright (C) 2010-2014 O01eg <o01eg@yandex.ru> + * + * This file is part of Genetic Function Programming. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is furnished to do + * so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include <fstream> +#include <iomanip> +#include "program.h" +#include "ioobject.h" + +using namespace VM; + +Program::Program(const Object &obj) + : m_CachedSave(obj) +{ + Object head = obj.GetHead(); + Heap::UInt num_adfs = head.GetValue(); + m_ADFs.resize(num_adfs, Object(obj.GetEnv())); + Object ptr = obj.GetTail(); + while(! ptr.IsNIL()) + { + if(! ptr.GetHead().GetHead().IsNIL()) + { + if(ptr.GetHead().GetHead().GetType() == ADF) + { + Heap::UInt num = ptr.GetHead().GetHead().GetValue(); + if(num < m_ADFs.size()) + { + m_ADFs[num] = ptr.GetHead().GetTail().GetHead(); + } + else + { + std::stringstream ss; + ss << obj; + THROW("ADF's num out of range in " + ss.str()); + } + } + else if((ptr.GetHead().GetHead().GetType() == LIST) && (! ptr.GetHead().GetHead().GetHead().IsNIL()) && (ptr.GetHead().GetHead().GetHead().GetType() == ADF)) + { + Heap::UInt num = ptr.GetHead().GetHead().GetHead().GetValue(); + if(num < m_ADFs.size()) + { + m_ADFs[num] = ptr.GetHead().GetTail().GetHead(); + } + else + { + std::stringstream ss; + ss << obj; + THROW("ADF's num out of range in " + ss.str()); + } + } + } + + ptr = ptr.GetTail(); + } +} + +Program::Program(Environment &env, const char *fn) + : m_CachedSave(env) +{ + std::ifstream f(fn); + Object obj(env); + f >> obj; + this->~Program(); + new (this) Program(obj); +} + +Object Program::InnerSave() const +{ + if(m_ADFs.size() == 0) + { + THROW("No ADFs in program"); + } + Environment &env = m_CachedSave.GetEnv(); + Object res(env); + signed long index; + for(index = m_ADFs.size() - 1; index >= 0; index --) + { + if(! m_ADFs[index].IsNIL()) + { + Object func_entry = Object(m_ADFs[index], Object(env)); + func_entry = Object(Object(env, ADF, index), std::move(func_entry)); + res = Object(std::move(func_entry), std::move(res)); + } + } + return Object(Object(env, INTEGER, m_ADFs.size()), std::move(res)); +} + +void Program::SetADF(size_t num, const Object& obj) +{ + m_CachedSave = Object(m_CachedSave.GetEnv()); // clean cache + if(m_ADFs.size() <= num) + { + m_ADFs.resize(num + 1, Object(m_CachedSave.GetEnv())); + } + m_ADFs[num] = obj; +} + +std::vector<unsigned int> Program::GetADFCallMap() const +{ + std::vector<unsigned int> adf_call_map(m_ADFs.size() * m_ADFs.size(), 0); + std::stack<VM::WeakObject> stack; + for(size_t adf_index = 0; adf_index < m_ADFs.size(); ++ adf_index) + { + stack.push(m_ADFs[adf_index]); + while(! stack.empty()) + { + WeakObject temp = stack.top(); + stack.pop(); + if(! temp.IsNIL()) + { + if(temp.GetType() == ADF) + { + if(temp.GetValue() < m_ADFs.size()) + { + ++ adf_call_map[adf_index * m_ADFs.size() + temp.GetValue()]; + } + else + { + std::stringstream ss; + ss << Save(); + THROW(FormatString("Bugly generated program " + ss.str())); + } + } + if(temp.GetType() == LIST) + { + stack.push(temp.GetHead()); + stack.push(temp.GetTail()); + } + } + } + } + + return adf_call_map; +} + +void Program::Minimize() +{ + std::vector<unsigned int> adf_call_map = GetADFCallMap(); + +#if 0 + // dump adf_calls + for(adf_index = 0; adf_index < m_ADFs.size(); adf_index ++) + { + std::cout << std::setw(2) << adf_index << ":"; + for(size_t j = 0; j < m_ADFs.size(); j++) + { + if(adf_calls[adf_index * m_ADFs.size() + j]) + { + std::cout << j << " "; + } + } + std::cout << std::endl; + } +#endif + + for(size_t adf_index = 1; adf_index < m_ADFs.size(); adf_index ++) + { + // check each function to calls from above ADF + bool called = false; + for(size_t adf_from_index = 0; adf_from_index < adf_index; ++ adf_from_index) + { + if(adf_call_map[adf_from_index * m_ADFs.size() + adf_index]) + { + called = true; + break; + } + } + if(! called) + { + // remove ADF + m_CachedSave = Object(m_CachedSave.GetEnv()); // clean cache + + m_ADFs[adf_index] = m_CachedSave; + for(size_t adf_to_index = adf_index; adf_to_index < m_ADFs.size(); ++ adf_to_index) + { + adf_call_map[adf_index * m_ADFs.size() + adf_to_index] = 0; + } + } + } +} + +size_t Program::GetSettedADFs() const +{ + size_t res = 0; + for(size_t adf_index = 0; adf_index < m_ADFs.size(); adf_index ++) + { + if(! m_ADFs[adf_index].IsNIL()) + { + res ++; + } + } + return res; +} + diff --git a/pool/shard007/C++/0093958_noui.cpp b/pool/shard007/C++/0093958_noui.cpp new file mode 100644 index 0000000000000000000000000000000000000000..910e6967d0b5989fc12bb1854329838d8c73eb1c --- /dev/null +++ b/pool/shard007/C++/0093958_noui.cpp @@ -0,0 +1,60 @@ +// Copyright (c) 2010 Satoshi Nakamoto +// Copyright (c) 2009-2017 The Bitcoin Core developers +// Copyright (c) 2015-2017 The Dash developers +// Copyright (c) 2015-2017 The Bitsend developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "noui.h" + +#include "ui_interface.h" +#include "util.h" + +#include <cstdio> +#include <stdint.h> +#include <string> + +static bool noui_ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) +{ + bool fSecure = style & CClientUIInterface::SECURE; + style &= ~CClientUIInterface::SECURE; + + std::string strCaption; + // Check for usage of predefined caption + switch (style) { + case CClientUIInterface::MSG_ERROR: + strCaption += _("Error"); + break; + case CClientUIInterface::MSG_WARNING: + strCaption += _("Warning"); + break; + case CClientUIInterface::MSG_INFORMATION: + strCaption += _("Information"); + break; + default: + strCaption += caption; // Use supplied caption (can be empty) + } + + if (!fSecure) + LogPrintf("%s: %s\n", strCaption, message); + fprintf(stderr, "%s: %s\n", strCaption.c_str(), message.c_str()); + return false; +} + +static bool noui_ThreadSafeQuestion(const std::string& /* ignored interactive message */, const std::string& message, const std::string& caption, unsigned int style) +{ + return noui_ThreadSafeMessageBox(message, caption, style); +} + +static void noui_InitMessage(const std::string& message) +{ + LogPrintf("init message: %s\n", message); +} + +void noui_connect() +{ + // Connect bitsendd signal handlers + uiInterface.ThreadSafeMessageBox.connect(noui_ThreadSafeMessageBox); + uiInterface.ThreadSafeQuestion.connect(noui_ThreadSafeQuestion); + uiInterface.InitMessage.connect(noui_InitMessage); +} diff --git a/pool/shard007/C++/0093960_language_options_handler.cc b/pool/shard007/C++/0093960_language_options_handler.cc new file mode 100644 index 0000000000000000000000000000000000000000..863ab1ba73ecd2e7cddfe9b18c7ad187839eccdc --- /dev/null +++ b/pool/shard007/C++/0093960_language_options_handler.cc @@ -0,0 +1,119 @@ +// Copyright (c) 2011 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 "chrome/browser/ui/webui/options/language_options_handler.h" + +#include <map> +#include <string> +#include <utility> +#include <vector> + +#include "base/basictypes.h" +#include "base/bind.h" +#include "base/command_line.h" +#include "base/i18n/rtl.h" +#include "base/utf_string_conversions.h" +#include "base/values.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/prefs/pref_service.h" +#include "chrome/browser/ui/browser_list.h" +#include "chrome/common/chrome_switches.h" +#include "chrome/common/pref_names.h" +#include "content/public/browser/user_metrics.h" +#include "content/public/browser/web_ui.h" +#include "grit/chromium_strings.h" +#include "grit/generated_resources.h" +#include "ui/base/l10n/l10n_util.h" + +using content::UserMetricsAction; + +LanguageOptionsHandler::LanguageOptionsHandler() { +} + +LanguageOptionsHandler::~LanguageOptionsHandler() { +} + +void LanguageOptionsHandler::GetLocalizedValues( + DictionaryValue* localized_strings) { + LanguageOptionsHandlerCommon::GetLocalizedValues(localized_strings); + + RegisterTitle(localized_strings, "languagePage", + IDS_OPTIONS_SETTINGS_LANGUAGES_DIALOG_TITLE); + localized_strings->SetString("restart_button", + l10n_util::GetStringUTF16( + IDS_OPTIONS_SETTINGS_LANGUAGES_RELAUNCH_BUTTON)); + localized_strings->Set("languageList", GetLanguageList()); +} + +void LanguageOptionsHandler::RegisterMessages() { + LanguageOptionsHandlerCommon::RegisterMessages(); + + web_ui()->RegisterMessageCallback("uiLanguageRestart", + base::Bind(&LanguageOptionsHandler::RestartCallback, + base::Unretained(this))); +} + +ListValue* LanguageOptionsHandler::GetLanguageList() { + // Collect the language codes from the supported accept-languages. + const std::string app_locale = g_browser_process->GetApplicationLocale(); + std::vector<std::string> language_codes; + l10n_util::GetAcceptLanguagesForLocale(app_locale, &language_codes); + + // Map of display name -> {language code, native_display_name}. + // In theory, we should be able to create a map that is sorted by + // display names using ICU comparator, but doing it is hard, thus we'll + // use an auxiliary vector to achieve the same result. + typedef std::pair<std::string, string16> LanguagePair; + typedef std::map<string16, LanguagePair> LanguageMap; + LanguageMap language_map; + // The auxiliary vector mentioned above. + std::vector<string16> display_names; + + // Build the list of display names, and build the language map. + for (size_t i = 0; i < language_codes.size(); ++i) { + string16 display_name = + l10n_util::GetDisplayNameForLocale(language_codes[i], app_locale, + false); + base::i18n::AdjustStringForLocaleDirection(&display_name); + string16 native_display_name = + l10n_util::GetDisplayNameForLocale(language_codes[i], language_codes[i], + false); + base::i18n::AdjustStringForLocaleDirection(&native_display_name); + display_names.push_back(display_name); + language_map[display_name] = + std::make_pair(language_codes[i], native_display_name); + } + DCHECK_EQ(display_names.size(), language_map.size()); + + // Sort display names using locale specific sorter. + l10n_util::SortStrings16(app_locale, &display_names); + + // Build the language list from the language map. + ListValue* language_list = new ListValue(); + for (size_t i = 0; i < display_names.size(); ++i) { + const LanguagePair& pair = language_map[display_names[i]]; + DictionaryValue* dictionary = new DictionaryValue(); + dictionary->SetString("code", pair.first); + dictionary->SetString("displayName", display_names[i]); + dictionary->SetString("nativeDisplayName", pair.second); + language_list->Append(dictionary); + } + + return language_list; +} + +string16 LanguageOptionsHandler::GetProductName() { + return l10n_util::GetStringUTF16(IDS_PRODUCT_NAME); +} + +void LanguageOptionsHandler::SetApplicationLocale( + const std::string& language_code) { + PrefService* pref_service = g_browser_process->local_state(); + pref_service->SetString(prefs::kApplicationLocale, language_code); +} + +void LanguageOptionsHandler::RestartCallback(const ListValue* args) { + content::RecordAction(UserMetricsAction("LanguageOptions_Restart")); + BrowserList::AttemptRestart(); +} diff --git a/pool/shard007/C++/0093961_steer_drive_controller_fail_test.cpp b/pool/shard007/C++/0093961_steer_drive_controller_fail_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..68733cd213967f1745a546dcfbc522f4d83d516c --- /dev/null +++ b/pool/shard007/C++/0093961_steer_drive_controller_fail_test.cpp @@ -0,0 +1,57 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2013, PAL Robotics S.L. +// +// 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 PAL Robotics, 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. +////////////////////////////////////////////////////////////////////////////// + +/// \author Paul Mathieu + +#include "../common/include/test_common.h" + +// TEST CASES +TEST_F(SteerDriveControllerTest, testWrongJointName) +{ + // the controller should never be alive + int secs = 0; + while(!isControllerAlive() && secs < 5) + { + ros::Duration(1.0).sleep(); + secs++; + } + // give up and assume controller load failure after 5 seconds + EXPECT_GE(secs, 5); +} + +int main(int argc, char** argv) +{ + testing::InitGoogleTest(&argc, argv); + ros::init(argc, argv, "steer_drive_controller_fail_test"); + + ros::AsyncSpinner spinner(1); + spinner.start(); + int ret = RUN_ALL_TESTS(); + spinner.stop(); + ros::shutdown(); + return ret; +} diff --git a/pool/shard007/C++/0093965_desktop_window_tree_host_platform_unittest.cc b/pool/shard007/C++/0093965_desktop_window_tree_host_platform_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..62e2a8fd5abe4ef68fb591cf9782715dd68ed518 --- /dev/null +++ b/pool/shard007/C++/0093965_desktop_window_tree_host_platform_unittest.cc @@ -0,0 +1,146 @@ +// Copyright 2018 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 "ui/views/widget/desktop_aura/desktop_window_tree_host_platform.h" + +#include <memory> +#include <utility> + +#include "base/run_loop.h" +#include "ui/views/test/views_test_base.h" +#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" +#include "ui/views/widget/widget_observer.h" + +namespace views { + +namespace { + +class TestWidgetObserver : public WidgetObserver { + public: + enum class Change { + kVisibility, + kDestroying, + }; + + explicit TestWidgetObserver(Widget* widget) : widget_(widget) { + DCHECK(widget_); + widget_->AddObserver(this); + } + ~TestWidgetObserver() override { + // This might have been destroyed by the widget destroying delegate call. + if (widget_) + widget_->RemoveObserver(this); + } + + // Waits for notification changes for the |change|. |old_value| must be + // provided to be sure that this is not called after the change has already + // happened - e.g. synchronous change. + void WaitForChange(Change change, bool old_value) { + switch (change) { + case Change::kVisibility: + if (old_value == visible_) + Wait(); + break; + case Change::kDestroying: + if (old_value == on_widget_destroying_) + Wait(); + break; + default: + NOTREACHED() << "unknown value"; + break; + } + } + + bool widget_destroying() const { return on_widget_destroying_; } + bool visible() const { return visible_; } + + private: + // views::WidgetObserver overrides: + void OnWidgetDestroying(Widget* widget) override { + DCHECK_EQ(widget_, widget); + widget_->RemoveObserver(this); + widget_ = nullptr; + on_widget_destroying_ = true; + StopWaiting(); + } + void OnWidgetVisibilityChanged(Widget* widget, bool visible) override { + DCHECK_EQ(widget_, widget); + visible_ = visible; + StopWaiting(); + } + + void Wait() { + ASSERT_FALSE(run_loop_); + run_loop_ = std::make_unique<base::RunLoop>(); + run_loop_->Run(); + run_loop_.reset(); + } + + void StopWaiting() { + if (!run_loop_) + return; + ASSERT_TRUE(run_loop_->running()); + run_loop_->Quit(); + } + + Widget* widget_; + std::unique_ptr<base::RunLoop> run_loop_; + bool on_widget_destroying_ = false; + bool visible_ = false; + + DISALLOW_COPY_AND_ASSIGN(TestWidgetObserver); +}; + +std::unique_ptr<Widget> CreateWidgetWithNativeWidget() { + std::unique_ptr<Widget> widget(new Widget); + Widget::InitParams params(Widget::InitParams::TYPE_WINDOW); + params.delegate = nullptr; + params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; + params.remove_standard_frame = true; + params.native_widget = new DesktopNativeWidgetAura(widget.get()); + params.bounds = gfx::Rect(100, 100, 100, 100); + widget->Init(std::move(params)); + return widget; +} + +} // namespace + +class DesktopWindowTreeHostPlatformTest : public ViewsTestBase { + public: + DesktopWindowTreeHostPlatformTest() {} + ~DesktopWindowTreeHostPlatformTest() override {} + + private: + DISALLOW_COPY_AND_ASSIGN(DesktopWindowTreeHostPlatformTest); +}; + +TEST_F(DesktopWindowTreeHostPlatformTest, CallOnNativeWidgetDestroying) { + std::unique_ptr<Widget> widget = CreateWidgetWithNativeWidget(); + + TestWidgetObserver observer(widget->native_widget_private()->GetWidget()); + widget->CloseNow(); + + observer.WaitForChange(TestWidgetObserver::Change::kDestroying, + false /* old_value */); + EXPECT_TRUE(observer.widget_destroying()); +} + +// Calling show/hide/show triggers changing visibility of the native widget. +TEST_F(DesktopWindowTreeHostPlatformTest, CallOnNativeWidgetVisibilityChanged) { + std::unique_ptr<Widget> widget = CreateWidgetWithNativeWidget(); + + TestWidgetObserver observer(widget->native_widget_private()->GetWidget()); + EXPECT_FALSE(observer.visible()); + + widget->Show(); + EXPECT_TRUE(observer.visible()); + + widget->Hide(); + EXPECT_FALSE(observer.visible()); + + widget->Show(); + EXPECT_TRUE(observer.visible()); +} + +} // namespace views diff --git a/pool/shard007/C++/0093967_Why_Did_the_Cow_Cross_the_Road_III.cpp b/pool/shard007/C++/0093967_Why_Did_the_Cow_Cross_the_Road_III.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ca57e92ddd09773b8d25b6828f1f84520801acc8 --- /dev/null +++ b/pool/shard007/C++/0093967_Why_Did_the_Cow_Cross_the_Road_III.cpp @@ -0,0 +1,50 @@ +// +// Created by 孙启龙 on 2017/7/28. +// + +#include<cstdio> +#include<cstring> +#include<algorithm> + +using namespace std; + +int n, t; +int sum[100010]; + +pair<int, int> edge[100005]; + +int lowbit(int x) { + return x & (-x); +} + +int s(int x) { + int ans = 0; + for (; x >= 1; x -= lowbit(x)) + ans += sum[x]; + return ans; +} + +void add(int x) { + for (; x <= 2 * n; x += lowbit(x)) + sum[x]++; +} + +int main() { + scanf("%d", &n); + for (int i = 1; i <= 2 * n; i++) { + scanf("%d", &t); + if (edge[t].first) + edge[t].second = i; + else + edge[t].first = i; + } + sort(edge + 1, edge + n + 1); + + int ans = 0; + for (int i = 1; i <= n; i++) { + add(edge[i].second + 1); + ans += s(edge[i].second) - s(edge[i].first); + } + printf("%d\n", ans); + return 0; +} \ No newline at end of file diff --git a/pool/shard007/C++/0093980_libc.cc b/pool/shard007/C++/0093980_libc.cc new file mode 100644 index 0000000000000000000000000000000000000000..f44a38882524fb395996de7402ec6e21bc0fe00e --- /dev/null +++ b/pool/shard007/C++/0093980_libc.cc @@ -0,0 +1,241 @@ +/* + * \brief VirtualBox runtime (RT) + * \author Norman Feske + * \date 2013-08-20 + */ + +/* + * Copyright (C) 2013 Genode Labs GmbH + * + * This file is distributed under the terms of the GNU General Public License + * version 2. + */ + +/* Genode includes */ +#include <base/printf.h> +#include <util/string.h> +#include <rtc_session/connection.h> + +/* libc includes */ +#include <stdlib.h> +#include <signal.h> +#include <sys/time.h> +#include <sys/mount.h> /* statfs */ +#include <unistd.h> +#include <errno.h> +#include <fcntl.h> /* open */ + + + +/* libc memory allocator */ +#include <libc_mem_alloc.h> + +/* VirtualBox includes */ +#include <iprt/mem.h> +#include <iprt/assert.h> + +static const bool verbose = false; + +using Genode::size_t; + +/* + * We cannot use the libc's version of malloc because it does not satisfies + * the alignment constraints asserted by 'Runtime/r3/alloc.cpp'. + */ + +extern "C" void *malloc(size_t size) +{ + return Libc::mem_alloc()->alloc(size, Genode::log2(RTMEM_ALIGNMENT)); +} + + +extern "C" void *calloc(size_t nmemb, size_t size) +{ + void *ret = malloc(nmemb*size); + Genode::memset(ret, 0, nmemb*size); + return ret; +} + + +extern "C" void free(void *ptr) +{ + Libc::mem_alloc()->free(ptr); +} + + +extern "C" void *realloc(void *ptr, Genode::size_t size) +{ + if (!ptr) + return malloc(size); + + if (!size) { + free(ptr); + return 0; + } + + /* determine size of old block content (without header) */ + unsigned long old_size = Libc::mem_alloc()->size_at(ptr); + + /* do not reallocate if new size is less than the current size */ + if (size <= old_size) + return ptr; + + /* allocate new block */ + void *new_addr = malloc(size); + + /* copy content from old block into new block */ + if (new_addr) + Genode::memcpy(new_addr, ptr, Genode::min(old_size, (unsigned long)size)); + + /* free old block */ + free(ptr); + + return new_addr; +} + + +extern "C" char *getenv(const char *name) +{ + /* + * Logging to the pseudo file '/log' is done via the libc plugin provided + * by 'logging.cc'. + */ + if (Genode::strcmp(name, "VBOX_LOG_DEST") == 0 || + Genode::strcmp(name, "VBOX_RELEASE_LOG_DEST") == 0) + return (char *)"file=log"; + + if (Genode::strcmp(name, "VBOX_LOG") == 0 || + Genode::strcmp(name, "VBOX_RELEASE_LOG") == 0) + return (char *)"+rem_dias.e.l.f" + "+rem_printf.e.l.f" +// "+rem_run.e.l.f" +// "+pgm.e.l.f" + "+pdm" +// "+cpum.e.l.f" +// "+dev_pcnet.e.l.f" +// "+dev_pic.e.l.f" +// "+dev_apic.e.l.f" + "+dev_vmm.e" +// "+usb_mouse.e.l.f" +// "+main.e.l.f" +// "+hgcm.e.l.f" +// "+shared_folders.e.l.f" +// "+drv_host_serial.e.l.f" +// "+dev_audio.e.l.f" + ; + + if (Genode::strcmp(name, "VBOX_LOG_FLAGS") == 0 || + Genode::strcmp(name, "VBOX_RELEASE_LOG_FLAGS") == 0) + return (char *)"thread"; + + PWRN("getenv called for non-existent variable \"%s\"", name); + return 0; +} + + +extern "C" int sigaction(int signum, const struct sigaction *act, + struct sigaction *oldact) +{ + /* + * Break infinite loop at 'VBox/Runtime/r3/init.cpp' :451 + */; + if (oldact) + oldact->sa_flags = SA_SIGINFO; + + return 0; +} + + +/* our libc provides a _nanosleep function */ +extern "C" int _nanosleep(const struct timespec *req, struct timespec *rem); +extern "C" int nanosleep(const struct timespec *req, struct timespec *rem) +{ + Assert(req); +/* + if (req) { // && req->tv_sec == 0 && req->tv_nsec <= 10 *1000000) { + char _name[64]; + Genode::Thread_base::myself()->name(_name, sizeof(_name)); + PERR("%zd:%ld s:ns rip %p '%s'", req->tv_sec, req->tv_nsec, + __builtin_return_address(0), _name); + } +*/ + return _nanosleep(req, rem); +} + + + +/* Some dummy implementation for LibC functions */ + +extern "C" pid_t getpid(void) +{ + if (verbose) + PINF("%s called - rip %p", __func__, __builtin_return_address(0)); + + return 1345; +} + +extern "C" int sigprocmask(int how, const sigset_t *set, sigset_t *oldset) +{ + if (verbose) + PINF("%s called - rip %p", __func__, __builtin_return_address(0)); + + return -1; +} + +extern "C" int _sigaction(int, const struct sigaction *, struct sigaction *) +{ + if (verbose) + PINF("%s called - rip %p", __func__, __builtin_return_address(0)); + + return -1; +} + +extern "C" int futimes(int fd, const struct timeval tv[2]) +{ + PINF("%s called - rip %p", __func__, __builtin_return_address(0)); + return 0; +} + +extern "C" int lutimes(const char *filename, const struct timeval tv[2]) +{ + PINF("%s called - file '%s' - rip %p", __func__, filename, + __builtin_return_address(0)); + return 0; +} + +extern "C" int _sigprocmask() +{ + if (verbose) + PINF("%s called - rip %p", __func__, __builtin_return_address(0)); + + return 0; +} + + + +/** + * Used by Shared Folders Guest additions + */ +extern "C" int _fstatfs(int libc_fd, struct statfs *buf); +extern "C" int statfs(const char *path, struct statfs *buf) +{ + int fd = open(path, 0); + + if (fd < 0) + return fd; + + int res = _fstatfs(fd, buf); + + close(fd); + + return res; +} + +extern "C" long pathconf(char const *path, int name) +{ + if (name == _PC_NAME_MAX) return 255; + + PERR("pathconf does not support config option %d", name); + errno = EINVAL; + return -1; +} diff --git a/pool/shard007/C++/0093981_0738-Monotone_Increasing_Digits.cpp b/pool/shard007/C++/0093981_0738-Monotone_Increasing_Digits.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a57cd55c275eddd76044786928cb9220e330fbfb --- /dev/null +++ b/pool/shard007/C++/0093981_0738-Monotone_Increasing_Digits.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int monotoneIncreasingDigits(int N) { + string s = to_string(N); + int j = -1; + for (int i = 0; i < s.size() - 1; ++i) { + if (s[i] > s[i + 1]) { + j = i; + break; + } + } + + if (j == -1) { + return N; + } + + for (int k = j; k >= 1; --k) { + if (s[k - 1] > s[k] - 1) { + --j; + } + else { + break; + } + } + + --s[j]; + for (int k = j + 1; k < s.size(); ++k) { + s[k] = '9'; + } + return stoi(s); + } +}; diff --git a/pool/shard007/C++/0093983_PriorityLayoutPass.cpp b/pool/shard007/C++/0093983_PriorityLayoutPass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ea7fcfb170d1c9f7eac025496d8e4e8f2f7f342c --- /dev/null +++ b/pool/shard007/C++/0093983_PriorityLayoutPass.cpp @@ -0,0 +1,118 @@ +/*! \file PriorityLayoutPass.cpp + \author Gregory Diamso <gregory.diamos@gatech.edu> + \date Monday May 16, 2011 + \brief The source file for the PriorityLayoutPass class. +*/ + +// Ocelot Includes +#include <ocelot/transforms/interface/PriorityLayoutPass.h> + +#include <ocelot/analysis/interface/ThreadFrontierAnalysis.h> + +#include <ocelot/ir/interface/ControlFlowGraph.h> +#include <ocelot/ir/interface/IRKernel.h> + +// Hydrazine Includes +#include <hydrazine/interface/debug.h> + +// Standard Library Includes +#include <unordered_map> + +// Preprocessor Macros +#ifdef REPORT_BASE +#undef REPORT_BASE +#endif + +#define REPORT_BASE 0 + +namespace transforms +{ + +PriorityLayoutPass::PriorityLayoutPass() +: ImmutableKernelPass({"ThreadFrontierAnalysis"}, "PriorityLayoutPass") +{ + +} + +void PriorityLayoutPass::initialize(const ir::Module& m) +{ + instructions.clear(); +} + +void PriorityLayoutPass::runOnKernel(const ir::IRKernel& k) +{ + report("Running priority layout pass"); + + typedef analysis::ThreadFrontierAnalysis::Priority Priority; + typedef std::unordered_map<std::string, unsigned int> LabelToPCMap; + typedef std::map<Priority, ir::ControlFlowGraph::const_iterator, + std::greater<Priority>> PriorityToBlockMap; + + LabelToPCMap pcs; + + PriorityToBlockMap blocks; + + auto tfAnalysis = static_cast<analysis::ThreadFrontierAnalysis*>( + getAnalysis("ThreadFrontierAnalysis")); + + // Sort blocks by priority + for(auto block = k.cfg()->begin(); block != k.cfg()->end(); ++block) + { + blocks.insert(std::make_pair(tfAnalysis->getPriority(block), block)); + } + + report(" Packing instructions into a vector"); + for(auto block = blocks.begin(); block != blocks.end(); ++block) + { + for(auto instruction = block->second->instructions.begin(); + instruction != block->second->instructions.end(); ++instruction) + { + const ir::PTXInstruction& ptx = static_cast< + const ir::PTXInstruction&>(**instruction); + + report(" [" << instructions.size() << "] '" << ptx.toString()); + + if(instruction == block->second->instructions.begin()) + { + pcs.insert(std::make_pair(block->second->label(), + instructions.size())); + } + + instructions.push_back(ptx); + instructions.back().pc = instructions.size() - 1; + } + } + + report(" Updating branch targets"); + unsigned int pc = 0; + for(auto block = blocks.begin(); block != blocks.end(); ++block) + { + for(auto instruction = block->second->instructions.begin(); + instruction != block->second->instructions.end(); + ++instruction, ++pc) + { + const ir::PTXInstruction& ptx = static_cast< + const ir::PTXInstruction&>(**instruction); + if(ptx.opcode == ir::PTXInstruction::Bra) + { + LabelToPCMap::const_iterator target = + pcs.find(ptx.d.identifier); + assert(target != pcs.end()); + + report(" setting branch target of '" << ptx.toString() + << "' to " << target->second); + + instructions[pc].branchTargetInstruction = target->second; + } + } + } +} + +void PriorityLayoutPass::finalize() +{ + +} + +} + + diff --git a/pool/shard007/C++/0093985_pointlightsourceprocessor.cpp b/pool/shard007/C++/0093985_pointlightsourceprocessor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..29e82b2e227b112a9e125dccc1cff7e11dd313b9 --- /dev/null +++ b/pool/shard007/C++/0093985_pointlightsourceprocessor.cpp @@ -0,0 +1,232 @@ +/********************************************************************************* + * + * Inviwo - Interactive Visualization Workshop + * + * Copyright (c) 2014-2015 Inviwo Foundation + * 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. + * + * 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 "pointlightsourceprocessor.h" +#include <inviwo/core/util/intersection/rayplaneintersection.h> +#include <inviwo/core/util/intersection/raysphereintersection.h> +#include <inviwo/core/datastructures/light/pointlight.h> + +namespace inviwo { + +PropertyClassIdentifier(PointLightTrackball, "org.inviwo.PointLightTrackball"); + +ProcessorClassIdentifier(PointLightSourceProcessor, "org.inviwo.Pointlightsource"); +ProcessorDisplayName(PointLightSourceProcessor, "Point light source"); +ProcessorTags(PointLightSourceProcessor, Tags::CPU); +ProcessorCategory(PointLightSourceProcessor, "Light source"); +ProcessorCodeState(PointLightSourceProcessor, CODE_STATE_EXPERIMENTAL); + +PointLightSourceProcessor::PointLightSourceProcessor() + : Processor() + , outport_("PointLightSource") + , camera_("camera", "Camera", vec3(0.0f, 0.0f, -2.0f), vec3(0.0f, 0.0f, 0.0f), + vec3(0.0f, 1.0f, 0.0f), nullptr, VALID) + , lightPosition_("lightPosition", "Light Source Position", + FloatVec3Property("position", "Position", vec3(-2.f, -50.f, 90.f), + vec3(-100.f), vec3(100.f)), + &camera_.get()) + , lighting_("lighting", "Light Parameters") + , lightPowerProp_("lightPower", "Light power (%)", 50.f, 0.f, 100.f) + , lightSize_("lightSize", "Light radius", 1.5f, 0.0f, 3.0f) + , lightDiffuse_("lightDiffuse", "Color", vec4(1.0f)) + , lightEnabled_("lightEnabled", "Enabled", true) + , lightScreenPosEnabled_("lightScreenPosEnabled", "Screen Pos Enabled", false) + , lightScreenPos_("lightScreenPos", "Light Screen Pos", vec2(0.7f), vec2(0.f), vec2(1.f)) + , interactionEvents_("interactionEvents", "Interaction Events") + , lightInteractionHandler_(&lightPosition_.position_, &camera_, &lightScreenPosEnabled_, + &lightScreenPos_) + , lightSource_(std::make_shared<PointLight>()) { + addPort(outport_); + addProperty(lightPosition_); + lighting_.addProperty(lightDiffuse_); + lighting_.addProperty(lightPowerProp_); + lighting_.addProperty(lightSize_); + lighting_.addProperty(lightEnabled_); + lighting_.addProperty(lightScreenPosEnabled_); + lighting_.addProperty(lightScreenPos_); + addProperty(lighting_); + + lightScreenPos_.setVisible(false); + lightScreenPosEnabled_.onChange( + [this]() { lightScreenPos_.setVisible(lightScreenPosEnabled_.get()); }); + + addProperty(camera_); + camera_.setVisible(false); + + lightDiffuse_.setSemantics(PropertySemantics::Color); + lightDiffuse_.setCurrentStateAsDefault(); + + lightScreenPos_.onChange( + [this]() { lightInteractionHandler_.setLightPosFromScreenCoords(lightScreenPos_.get()); }); + + interactionEvents_.addOption("off", "Handle None", 0); + interactionEvents_.addOption("on", "Handle All", 1); + interactionEvents_.addOption("onlytrackball", "Handle Trackball Related Only", 2); + interactionEvents_.addOption("onlyscreencorrds", "Handle Light Pos From Screen Coords Only", 3); + interactionEvents_.setSelectedValue(0); + interactionEvents_.setCurrentStateAsDefault(); + addProperty(interactionEvents_); + + interactionEvents_.onChange(this, &PointLightSourceProcessor::handleInteractionEventsChanged); +} + +PointLightSourceProcessor::~PointLightSourceProcessor() { + removeInteractionHandler(&lightInteractionHandler_); +} + +void PointLightSourceProcessor::process() { + updatePointLightSource(lightSource_.get()); + outport_.setData(lightSource_); +} + +void PointLightSourceProcessor::updatePointLightSource(PointLight* lightSource) { + vec3 lightPos = lightPosition_.get(); + vec3 dir; + switch ( + static_cast<PositionProperty::Space>(lightPosition_.referenceFrame_.getSelectedValue())) { + case PositionProperty::Space::VIEW: + dir = glm::normalize(camera_.getLookTo() - lightPos); + case PositionProperty::Space::WORLD: + default: + dir = glm::normalize(vec3(0.f) - lightPos); + } + mat4 transformationMatrix = getLightTransformationMatrix(lightPos, dir); + // Offset by 0.5 to get to texture coordinates + lightSource->setModelMatrix(glm::translate(vec3(0.5f))); + lightSource->setWorldMatrix(transformationMatrix); + + lightSource->setSize(vec2(lightSize_.get())); + vec3 diffuseLight = lightDiffuse_.get().xyz(); + lightSource->setIntensity(lightPowerProp_.get() * diffuseLight); + lightSource->setEnabled(lightEnabled_.get()); +} + +void PointLightSourceProcessor::handleInteractionEventsChanged() { + if (interactionEvents_.get() > 0) { + addInteractionHandler(&lightInteractionHandler_); + } else { + removeInteractionHandler(&lightInteractionHandler_); + } + lightInteractionHandler_.setHandleEventsOptions(interactionEvents_.get()); +} + +PointLightInteractionHandler::PointLightInteractionHandler(FloatVec3Property* pl, + CameraProperty* cam, + BoolProperty* screenPosEnabled, + FloatVec2Property* screenPos) + : InteractionHandler() + , lightPosition_(pl) + , camera_(cam) + , screenPosEnabled_(screenPosEnabled) + , screenPos_(screenPos) + , lookUp_(camera_->getLookUp()) + , lookTo_(0.f) + , trackball_(this) + , interactionEventOption_(0) { + // static_cast<TrackballObservable*>(&trackball_)->addObserver(this); + camera_->onChange(this, &PointLightInteractionHandler::onCameraChanged); +} + +void PointLightInteractionHandler::serialize(IvwSerializer& s) const {} + +void PointLightInteractionHandler::deserialize(IvwDeserializer& d) {} + +void PointLightInteractionHandler::invokeEvent(Event* event) { + // if(event->hasBeenUsed()) + // return; + + if (screenPosEnabled_->get()) setLightPosFromScreenCoords(screenPos_->get()); + + if (interactionEventOption_ == 1 || interactionEventOption_ == 3) { + GestureEvent* gestureEvent = dynamic_cast<GestureEvent*>(event); + if (gestureEvent) { + if (gestureEvent->type() == GestureEvent::PAN) { + setLightPosFromScreenCoords(gestureEvent->screenPosNormalized()); + gestureEvent->markAsUsed(); + return; + } + } + MouseEvent* mouseEvent = dynamic_cast<MouseEvent*>(event); + if (mouseEvent) { + int button = mouseEvent->button(); + if (button == MouseEvent::MOUSE_BUTTON_MIDDLE) { + // setLightPosFromScreenCoords(mouseEvent->posNormalized()); + mouseEvent->markAsUsed(); + screenPos_->set(mouseEvent->posNormalized()); + return; + } + } + } + + if (interactionEventOption_ == 1 || interactionEventOption_ == 2) trackball_.invokeEvent(event); +} + +void PointLightInteractionHandler::setHandleEventsOptions(int option) { + interactionEventOption_ = option; +} + +void PointLightInteractionHandler::setLightPosFromScreenCoords(const vec2& normalizedScreenCoord) { + vec2 deviceCoord(2.f * (normalizedScreenCoord - 0.5f)); + // Flip vertical axis since mouse event y position starts at top of screen + deviceCoord.y *= -1.f; + // Use half distance between look from and look to positions as scene radius. + float sceneRadius = 0.5f * glm::length(camera_->getLookTo() - camera_->getLookFrom()); + vec3 rayOrigin = camera_->getWorldPosFromNormalizedDeviceCoords(vec3(deviceCoord, 0.f)); + vec3 rayDir = glm::normalize( + camera_->getWorldPosFromNormalizedDeviceCoords(vec3(deviceCoord, 1.f)) - rayOrigin); + float t0 = 0, t1 = std::numeric_limits<float>::max(); + float lightRadius = glm::length(lightPosition_->get()); + + if (raySphereIntersection(vec3(0.f), sceneRadius, rayOrigin, rayDir, &t0, &t1)) { + lightPosition_->set(glm::normalize(rayOrigin + t1 * rayDir) * lightRadius); + } else { + // Project it to the rim of the sphere + t0 = 0; + t1 = std::numeric_limits<float>::max(); + if (rayPlaneIntersection(camera_->getLookTo(), + glm::normalize(camera_->getLookTo() - camera_->getLookFrom()), + rayOrigin, rayDir, &t0, &t1)) { + // Project it to the edge of the sphere + lightPosition_->set(glm::normalize(rayOrigin + t1 * rayDir) * lightRadius); + } + } + // Ensure that up vector is same as camera afterwards + setLookUp(camera_->getLookUp()); +} + +void PointLightInteractionHandler::onCameraChanged() { + // This makes sure that the interaction with the light source is consistent with the direction + // of the camera + setLookUp(camera_->getLookUp()); +} + +PointLightTrackball::PointLightTrackball(PointLightInteractionHandler* p) + : Trackball<PointLightInteractionHandler>(p, &(p->getCamera())) {} + +} // namespace diff --git a/pool/shard007/C++/0093998_priqueue.cc b/pool/shard007/C++/0093998_priqueue.cc new file mode 100644 index 0000000000000000000000000000000000000000..b7b24b92f1464f523c98f2952433d54007d2f51b --- /dev/null +++ b/pool/shard007/C++/0093998_priqueue.cc @@ -0,0 +1,193 @@ +/* -*- Mode:C++; c-basic-offset:8; tab-width:8; indent-tabs-mode:t -*- */ +/* + * Copyright (c) 1997 Regents of the University of California. + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the Computer Systems + * Engineering Group at Lawrence Berkeley Laboratory. + * 4. Neither the name of the University nor of the Laboratory may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. + */ +/* Ported from CMU/Monarch's code, nov'98 -Padma.*/ + +/* -*- c++ -*- + priqueue.cc + + A simple priority queue with a remove packet function + $Id: priqueue.cc,v 1.7 2004/10/07 17:56:03 haldar Exp $ + */ + +#include <object.h> +#include <queue.h> +#include <drop-tail.h> +#include <packet.h> +#include <cmu-trace.h> + +#include "priqueue.h" + +typedef int (*PacketFilter)(Packet *, void *); + +PriQueue_List PriQueue::prhead = { 0 }; + +static class PriQueueClass : public TclClass { +public: + PriQueueClass() : TclClass("Queue/DropTail/PriQueue") {} + TclObject* create(int, const char*const*) { + return (new PriQueue); + } +} class_PriQueue; + + +PriQueue::PriQueue() : DropTail() +{ + bind("Prefer_Routing_Protocols", &Prefer_Routing_Protocols); + LIST_INSERT_HEAD(&prhead, this, link); +} + +int +PriQueue::command(int argc, const char*const* argv) +{ + if (argc == 2 && strcasecmp(argv[1], "reset") == 0) + { + Terminate(); + //FALL-THROUGH to give parents a chance to reset + } + return DropTail::command(argc, argv); +} + +void +PriQueue::recv(Packet *p, Handler *h) +{ + struct hdr_cmn *ch = HDR_CMN(p); + + if(Prefer_Routing_Protocols) { + + switch(ch->ptype()) { + case PT_DSR: + case PT_MESSAGE: + case PT_TORA: + case PT_AODV: + recvHighPriority(p, h); + break; + + default: + Queue::recv(p, h); + } + } + else { + Queue::recv(p, h); + } +} + + +void +PriQueue::recvHighPriority(Packet *p, Handler *) + // insert packet at front of queue +{ + q_->enqueHead(p); + if (q_->length() >= qlim_) + { + Packet *to_drop = q_->lookup(q_->length()-1); + q_->remove(to_drop); + drop(to_drop); + } + + if (!blocked_) { + /* + * We're not blocked. Get a packet and send it on. + * We perform an extra check because the queue + * might drop the packet even if it was + * previously empty! (e.g., RED can do this.) + */ + p = deque(); + if (p != 0) { + blocked_ = 1; + target_->recv(p, &qh_); + } + } +} + +void +PriQueue::filter(PacketFilter filter, void * data) + // apply filter to each packet in queue, + // - if filter returns 0 leave packet in queue + // - if filter returns 1 remove packet from queue +{ + int i = 0; + while (i < q_->length()) + { + Packet *p = q_->lookup(i); + if (filter(p,data)) + { + q_->remove(p); // decrements q len + } + else i++; + } +} + +Packet* +PriQueue::filter(nsaddr_t id) +{ + Packet *p = 0; + Packet *pp = 0; + struct hdr_cmn *ch; + + for(p = q_->head(); p; p = p->next_) { + ch = HDR_CMN(p); + if(ch->next_hop() == id) + break; + pp = p; + } + + /* + * Deque Packet + */ + if(p) { + if(pp == 0) + q_->remove(p); + else + q_->remove(p, pp); + } + return p; +} + +/* + * Called at the end of the simulation to purge the IFQ. + */ +void +PriQueue::Terminate() +{ + Packet *p; + while((p = deque())) { + drop(p, DROP_END_OF_SIMULATION); + //drop(p); + + } +} + + + + diff --git a/pool/shard007/C++/0094010_abc.cpp b/pool/shard007/C++/0094010_abc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..509714a44079b2cbb3895012c7d825be7698e8ac --- /dev/null +++ b/pool/shard007/C++/0094010_abc.cpp @@ -0,0 +1,89 @@ +// Copyright (c) 2017-2020 The Bitcoin developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include <config.h> +#include <consensus/consensus.h> +#include <rpc/server.h> +#include <util/strencodings.h> +#include <validation.h> + +#include <univalue.h> + +static UniValue getexcessiveblock(const Config &config, + const JSONRPCRequest &request) { + if (request.fHelp || request.params.size() != 0) { + throw std::runtime_error( + "getexcessiveblock\n" + "\nReturn the excessive block size." + "\nResult\n" + " excessiveBlockSize (integer) block size in bytes\n" + "\nExamples:\n" + + HelpExampleCli("getexcessiveblock", "") + + HelpExampleRpc("getexcessiveblock", "")); + } + + UniValue ret(UniValue::VOBJ); + ret.pushKV("excessiveBlockSize", config.GetMaxBlockSize()); + return ret; +} + +static UniValue setexcessiveblock(Config &config, + const JSONRPCRequest &request) { + if (request.fHelp || request.params.size() != 1) { + throw std::runtime_error( + "setexcessiveblock blockSize\n" + "\nSet the excessive block size. Excessive blocks will not be used " + "in the active chain or relayed. This discourages the propagation " + "of blocks that you consider excessively large." + "\nResult\n" + " blockSize (integer) excessive block size in bytes\n" + "\nExamples:\n" + + HelpExampleCli("setexcessiveblock", "") + + HelpExampleRpc("setexcessiveblock", "")); + } + + int64_t ebs = 0; + if (request.params[0].isNum()) { + ebs = request.params[0].get_int64(); + } else if (!ParseInt64(request.params[0].get_str(), &ebs)) { + throw JSONRPCError( + RPC_INVALID_PARAMETER, + std::string( + "Invalid parameter, excessiveblock must be an integer")); + } + + // Do not allow maxBlockSize to be set below historic 1MB limit + if (ebs <= int64_t(LEGACY_MAX_BLOCK_SIZE)) { + throw JSONRPCError( + RPC_INVALID_PARAMETER, + std::string( + "Invalid parameter, excessiveblock must be larger than ") + + std::to_string(LEGACY_MAX_BLOCK_SIZE)); + } + + // Set the new max block size. + if (!config.SetMaxBlockSize(ebs)) { + throw JSONRPCError(RPC_INVALID_PARAMETER, "Unexpected error"); + } + + // settingsToUserAgentString(); + std::ostringstream ret; + ret << "Excessive Block set to " << ebs << " bytes."; + return UniValue(ret.str()); +} + +// clang-format off +static const ContextFreeRPCCommand commands[] = { + // category name actor (function) argNames + // ------------------- ------------------------ ---------------------- ---------- + { "network", "getexcessiveblock", getexcessiveblock, {}}, + { "network", "setexcessiveblock", setexcessiveblock, {"maxBlockSize"}}, +}; +// clang-format on + +void RegisterABCRPCCommands(CRPCTable &t) { + for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) { + t.appendCommand(commands[vcidx].name, &commands[vcidx]); + } +} diff --git a/pool/shard007/C++/0094018_mutex_pass.cpp b/pool/shard007/C++/0094018_mutex_pass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1e634807dbfd78b7bf0a755a55da352e98ea6987 --- /dev/null +++ b/pool/shard007/C++/0094018_mutex_pass.cpp @@ -0,0 +1,88 @@ +//===----------------------------------------------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is dual licensed under the MIT and the University of Illinois Open +// Source Licenses. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +// Copyright (C) 2011 Vicente J. Botet Escriba +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +// <boost/thread/locks.hpp> + +// template <class Mutex> class upgrade_lock; + +// explicit upgrade_lock(Mutex& m); + + +#include <boost/thread/lock_types.hpp> +#include <boost/thread/shared_mutex.hpp> +#include <boost/thread/thread.hpp> +#include <boost/detail/lightweight_test.hpp> +#include <iostream> +#include "../../../../../timming.hpp" + +boost::shared_mutex m; + +#if defined BOOST_THREAD_USES_CHRONO +typedef boost::chrono::high_resolution_clock Clock; +typedef Clock::time_point time_point; +typedef Clock::duration duration; +typedef boost::chrono::milliseconds ms; +typedef boost::chrono::nanoseconds ns; +time_point t0; +time_point t1; +#else +#endif + +const ms max_diff(BOOST_THREAD_TEST_TIME_MS); + +void f() +{ +#if defined BOOST_THREAD_USES_CHRONO + t0 = Clock::now(); + { + boost::upgrade_lock<boost::shared_mutex> ul(m); + t1 = Clock::now(); + } +#else + //time_point t0 = Clock::now(); + //time_point t1; + { + boost::upgrade_lock<boost::shared_mutex> ul(m); + //t1 = Clock::now(); + } + //ns d = t1 - t0 - ms(250); + //BOOST_TEST(d < max_diff); +#endif +} + +int main() +{ + m.lock(); + boost::thread t(f); +#if defined BOOST_THREAD_USES_CHRONO + time_point t2 = Clock::now(); + boost::this_thread::sleep_for(ms(250)); + time_point t3 = Clock::now(); +#else +#endif + m.unlock(); + t.join(); + +#if defined BOOST_THREAD_USES_CHRONO + ns sleep_time = t3 - t2; + ns d_ns = t1 - t0 - sleep_time; + ms d_ms = boost::chrono::duration_cast<boost::chrono::milliseconds>(d_ns); + // BOOST_TEST_GE(d_ms.count(), 0); + BOOST_THREAD_TEST_IT(d_ms, max_diff); + BOOST_THREAD_TEST_IT(d_ns, ns(max_diff)); +#endif + + return boost::report_errors(); +} + diff --git a/pool/shard007/C++/0094021_main.cc b/pool/shard007/C++/0094021_main.cc new file mode 100644 index 0000000000000000000000000000000000000000..093b7d32e50ab0cecb9e06b466b7cd64857ae0db --- /dev/null +++ b/pool/shard007/C++/0094021_main.cc @@ -0,0 +1,297 @@ +// main.cc +// Driver code to initialize, selftest, and run the +// operating system kernel. +// +// Usage: nachos -d <debugflags> -rs <random seed #> +// -s -x <nachos file> -ci <consoleIn> -co <consoleOut> +// -f -cp <unix file> <nachos file> +// -p <nachos file> -r <nachos file> -l -D +// -n <network reliability> -m <machine id> +// -z -K -C -N +// +// -d causes certain debugging messages to be printed (see debug.h) +// -rs causes Yield to occur at random (but repeatable) spots +// -z prints the copyright message +// -s causes user programs to be executed in single-step mode +// -x runs a user program +// -ci specify file for console input (stdin is the default) +// -co specify file for console output (stdout is the default) +// -n sets the network reliability +// -m sets this machine's host id (needed for the network) +// -K run a simple self test of kernel threads and synchronization +// -C run an interactive console test +// -N run a two-machine network test (see Kernel::NetworkTest) +// +// Filesystem-related flags: +// -f forces the Nachos disk to be formatted +// -cp copies a file from UNIX to Nachos +// -p prints a Nachos file to stdout +// -r removes a Nachos file from the file system +// -l lists the contents of the Nachos directory +// -D prints the contents of the entire file system +// +// Note: the file system flags are not used if the stub filesystem +// is being used +// +// Copyright (c) 1992-1996 The Regents of the University of California. +// All rights reserved. See copyright.h for copyright notice and limitation +// of liability and disclaimer of warranty provisions. + +#define MAIN +#include "copyright.h" +#undef MAIN + +#include "main.h" +#include "filesys.h" +#include "openfile.h" +#include "sysdep.h" + +// global variables +Kernel *kernel; +Debug *debug; + + +//---------------------------------------------------------------------- +// Cleanup +// Delete kernel data structures; called when user hits "ctl-C". +//---------------------------------------------------------------------- + +static void +Cleanup(int x) +{ + cerr << "\nCleaning up after signal " << x << "\n"; + delete kernel; +} + +//------------------------------------------------------------------- +// Constant used by "Copy" and "Print" +// It is the number of bytes read from the Unix file (for Copy) +// or the Nachos file (for Print) by each read operation +//------------------------------------------------------------------- +static const int TransferSize = 128; + + +#ifndef FILESYS_STUB +//---------------------------------------------------------------------- +// Copy +// Copy the contents of the UNIX file "from" to the Nachos file "to" +//---------------------------------------------------------------------- + +static void +Copy(char *from, char *to) +{ + int fd; + OpenFile* openFile; + int amountRead, fileLength; + char *buffer; + +// Open UNIX file + if ((fd = OpenForReadWrite(from,FALSE)) < 0) { + printf("Copy: couldn't open input file %s\n", from); + return; + } + +// Figure out length of UNIX file + Lseek(fd, 0, 2); + fileLength = Tell(fd); + Lseek(fd, 0, 0); + +// Create a Nachos file of the same length + DEBUG('f', "Copying file " << from << " of size " << fileLength << " to file " << to); + if (!kernel->fileSystem->Create(to, fileLength)) { // Create Nachos file + printf("Copy: couldn't create output file %s\n", to); + Close(fd); + return; + } + + openFile = kernel->fileSystem->Open(to); + ASSERT(openFile != NULL); + +// Copy the data in TransferSize chunks + buffer = new char[TransferSize]; + while ((amountRead=ReadPartial(fd, buffer, sizeof(char)*TransferSize)) > 0) + openFile->Write(buffer, amountRead); + delete [] buffer; + +// Close the UNIX and the Nachos files + delete openFile; + Close(fd); +} + +#endif // FILESYS_STUB + +//---------------------------------------------------------------------- +// Print +// Print the contents of the Nachos file "name". +//---------------------------------------------------------------------- + +void +Print(char *name) +{ + OpenFile *openFile; + int i, amountRead; + char *buffer; + + if ((openFile = kernel->fileSystem->Open(name)) == NULL) { + printf("Print: unable to open file %s\n", name); + return; + } + + buffer = new char[TransferSize]; + while ((amountRead = openFile->Read(buffer, TransferSize)) > 0) + for (i = 0; i < amountRead; i++) + printf("%c", buffer[i]); + delete [] buffer; + + delete openFile; // close the Nachos file + return; +} + + + +//---------------------------------------------------------------------- +// main +// Bootstrap the operating system kernel. +// +// Initialize kernel data structures +// Call some test routines +// Call "Run" to start an initial user program running +// +// "argc" is the number of command line arguments (including the name +// of the command) -- ex: "nachos -d +" -> argc = 3 +// "argv" is an array of strings, one for each command line argument +// ex: "nachos -d +" -> argv = {"nachos", "-d", "+"} +//---------------------------------------------------------------------- + +int +main(int argc, char **argv) +{ + int i; + char *debugArg = ""; + char *userProgName = NULL; // default is not to execute a user prog + bool threadTestFlag = false; + bool consoleTestFlag = false; + bool networkTestFlag = false; +#ifndef FILESYS_STUB + char *copyUnixFileName = NULL; // UNIX file to be copied into Nachos + char *copyNachosFileName = NULL; // name of copied file in Nachos + char *printFileName = NULL; + char *removeFileName = NULL; + bool dirListFlag = false; + bool dumpFlag = false; +#endif //FILESYS_STUB + + // some command line arguments are handled here. + // those that set kernel parameters are handled in + // the Kernel constructor + for (i = 1; i < argc; i++) { + if (strcmp(argv[i], "-d") == 0) { + ASSERT(i + 1 < argc); // next argument is debug string + debugArg = argv[i + 1]; + i++; + } + else if (strcmp(argv[i], "-z") == 0) { + cout << copyright << "\n"; + } + else if (strcmp(argv[i], "-x") == 0) { + ASSERT(i + 1 < argc); + userProgName = argv[i + 1]; + i++; + } + else if (strcmp(argv[i], "-K") == 0) { + threadTestFlag = TRUE; + } + else if (strcmp(argv[i], "-C") == 0) { + consoleTestFlag = TRUE; + } + else if (strcmp(argv[i], "-N") == 0) { + networkTestFlag = TRUE; + } +#ifndef FILESYS_STUB + else if (strcmp(argv[i], "-cp") == 0) { + ASSERT(i + 2 < argc); + copyUnixFileName = argv[i + 1]; + copyNachosFileName = argv[i + 2]; + i += 2; + } + else if (strcmp(argv[i], "-p") == 0) { + ASSERT(i + 1 < argc); + printFileName = argv[i + 1]; + i++; + } + else if (strcmp(argv[i], "-r") == 0) { + ASSERT(i + 1 < argc); + removeFileName = argv[i + 1]; + i++; + } + else if (strcmp(argv[i], "-l") == 0) { + dirListFlag = true; + } + else if (strcmp(argv[i], "-D") == 0) { + dumpFlag = true; + } +#endif //FILESYS_STUB + else if (strcmp(argv[i], "-u") == 0) { + cout << "Partial usage: nachos [-z -d debugFlags]\n"; + cout << "Partial usage: nachos [-x programName]\n"; + cout << "Partial usage: nachos [-K] [-C] [-N]\n"; +#ifndef FILESYS_STUB + cout << "Partial usage: nachos [-cp UnixFile NachosFile]\n"; + cout << "Partial usage: nachos [-p fileName] [-r fileName]\n"; + cout << "Partial usage: nachos [-l] [-D]\n"; +#endif //FILESYS_STUB + } + + } + debug = new Debug(debugArg); + + DEBUG(dbgThread, "Entering main"); + + kernel = new Kernel(argc, argv); + + kernel->Initialize(); + + CallOnUserAbort(Cleanup); // if user hits ctl-C + + // at this point, the kernel is ready to do something + // run some tests, if requested + if (threadTestFlag) { + kernel->ThreadSelfTest(); // test threads and synchronization + } + if (consoleTestFlag) { + kernel->ConsoleTest(); // interactive test of the synchronized console + } + if (networkTestFlag) { + kernel->NetworkTest(); // two-machine test of the network + } + +#ifndef FILESYS_STUB + if (removeFileName != NULL) { + kernel->fileSystem->Remove(removeFileName); + } + if (copyUnixFileName != NULL && copyNachosFileName != NULL) { + Copy(copyUnixFileName,copyNachosFileName); + } + if (dumpFlag) { + kernel->fileSystem->Print(); + } + if (dirListFlag) { + kernel->fileSystem->List(); + } + if (printFileName != NULL) { + Print(printFileName); + } +#endif // FILESYS_STUB + + // finally, run an initial user program if requested to do so + + kernel->ExecAll(); + // If we don't run a user program, we may get here. + // Calling "return" would terminate the program. + // Instead, call Halt, which will first clean up, then + // terminate. +// kernel->interrupt->Halt(); + + ASSERTNOTREACHED(); +} + diff --git a/pool/shard007/C++/0094022_EstimatingTheMean.cpp b/pool/shard007/C++/0094022_EstimatingTheMean.cpp new file mode 100644 index 0000000000000000000000000000000000000000..848e18cb744c0220062f72b2fda66380ad6e6321 --- /dev/null +++ b/pool/shard007/C++/0094022_EstimatingTheMean.cpp @@ -0,0 +1,58 @@ +#include <bits/stdc++.h> + +template<typename T> T gcd(T a, T b) { + if(!b) return a; + return gcd(b, a % b); +} +template<typename T> T lcm(T a, T b) { + return a * b / gcd(a, b); +} + +template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; } +template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; } +int in() { int x; scanf("%d", &x); return x; } + +using namespace std; + +typedef long long Int; +typedef unsigned uint; + +const int MAXN = 100005; + +int T, N, P[MAXN]; + +int main(void) { + cin >> T; + + for (int t = 1; t <= T; t++) { + cin >> N; + + int best = -1; + int ans = 0; + + for (int i = 0; i < N; i++) { + cin >> P[i]; + + if (P[i] > best) { + best = P[i]; + } + } + + for (int i = 0; i < N; i++) { + if (P[i] == best) { + int len = 1; + int j = i + 1; + + while (j < N && P[j] == best) { + j += 1; + len += 1; + } + + ans = max(ans, len); + i = j; + } + } + cout << "Caso #" << t << ": " << ans << "\n"; + } + return 0; +} diff --git a/pool/shard007/C++/0094023_TSeq_.cpp b/pool/shard007/C++/0094023_TSeq_.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bfda93f477c437fc3168bb77941125e7e586bc5d --- /dev/null +++ b/pool/shard007/C++/0094023_TSeq_.cpp @@ -0,0 +1,144 @@ +/* $Id$ + * =========================================================================== + * + * PUBLIC DOMAIN NOTICE + * National Center for Biotechnology Information + * + * This software/database is a "United States Government Work" under the + * terms of the United States Copyright Act. It was written as part of + * the author's official duties as a United States Government employee and + * thus cannot be copyrighted. This software/database is freely available + * to the public for use. The National Library of Medicine and the U.S. + * Government have not placed any restriction on its use or reproduction. + * + * Although all reasonable efforts have been taken to ensure the accuracy + * and reliability of the software and data, the NLM and the U.S. + * Government do not and cannot warrant the performance or results that + * may be obtained by using this software or data. The NLM and the U.S. + * Government disclaim all warranties, express or implied, including + * warranties of performance, merchantability or fitness for any particular + * purpose. + * + * Please cite the author in any work or product based on this material. + * + * =========================================================================== + * + * File Description: + * This code was generated by application DATATOOL + * using the following specifications: + * 'tinyseq.asn'. + * + * ATTENTION: + * Don't edit or commit this file into CVS as this file will + * be overridden (by DATATOOL) without warning! + * =========================================================================== + */ + +// standard includes +#include <ncbi_pch.hpp> +#include <serial/serialimpl.hpp> + +// generated includes +#include <objects/tinyseq/TSeq.hpp> +BEGIN_NCBI_SCOPE + +BEGIN_objects_SCOPE // namespace ncbi::objects:: + + +// generated classes + +BEGIN_NAMED_ENUM_IN_INFO("", CTSeq_Base::, ESeqtype, false) +{ + SET_ENUM_INTERNAL_NAME("TSeq", "seqtype"); + SET_ENUM_MODULE("NCBI-TSeq"); + ADD_ENUM_VALUE("nucleotide", eSeqtype_nucleotide); + ADD_ENUM_VALUE("protein", eSeqtype_protein); +} +END_ENUM_INFO + +void CTSeq_Base::ResetAccver(void) +{ + m_Accver.erase(); + m_set_State[0] &= ~0x30; +} + +void CTSeq_Base::ResetSid(void) +{ + m_Sid.erase(); + m_set_State[0] &= ~0xc0; +} + +void CTSeq_Base::ResetLocal(void) +{ + m_Local.erase(); + m_set_State[0] &= ~0x300; +} + +void CTSeq_Base::ResetOrgname(void) +{ + m_Orgname.erase(); + m_set_State[0] &= ~0x3000; +} + +void CTSeq_Base::ResetDefline(void) +{ + m_Defline.erase(); + m_set_State[0] &= ~0xc000; +} + +void CTSeq_Base::ResetSequence(void) +{ + m_Sequence.erase(); + m_set_State[0] &= ~0xc0000; +} + +void CTSeq_Base::Reset(void) +{ + ResetSeqtype(); + ResetGi(); + ResetAccver(); + ResetSid(); + ResetLocal(); + ResetTaxid(); + ResetOrgname(); + ResetDefline(); + ResetLength(); + ResetSequence(); +} + +BEGIN_NAMED_BASE_CLASS_INFO("TSeq", CTSeq) +{ + SET_CLASS_MODULE("NCBI-TSeq"); + ADD_NAMED_ENUM_MEMBER("seqtype", m_Seqtype, ESeqtype)->SetSetFlag(MEMBER_PTR(m_set_State[0])); + ADD_NAMED_STD_MEMBER("gi", m_Gi)->SetSetFlag(MEMBER_PTR(m_set_State[0]))->SetOptional(); + ADD_NAMED_STD_MEMBER("accver", m_Accver)->SetSetFlag(MEMBER_PTR(m_set_State[0]))->SetOptional(); + ADD_NAMED_STD_MEMBER("sid", m_Sid)->SetSetFlag(MEMBER_PTR(m_set_State[0]))->SetOptional(); + ADD_NAMED_STD_MEMBER("local", m_Local)->SetSetFlag(MEMBER_PTR(m_set_State[0]))->SetOptional(); + ADD_NAMED_STD_MEMBER("taxid", m_Taxid)->SetSetFlag(MEMBER_PTR(m_set_State[0]))->SetOptional(); + ADD_NAMED_STD_MEMBER("orgname", m_Orgname)->SetSetFlag(MEMBER_PTR(m_set_State[0]))->SetOptional(); + ADD_NAMED_STD_MEMBER("defline", m_Defline)->SetSetFlag(MEMBER_PTR(m_set_State[0])); + ADD_NAMED_STD_MEMBER("length", m_Length)->SetSetFlag(MEMBER_PTR(m_set_State[0])); + ADD_NAMED_STD_MEMBER("sequence", m_Sequence)->SetSetFlag(MEMBER_PTR(m_set_State[0])); + info->RandomOrder(); + info->CodeVersion(21600); +} +END_CLASS_INFO + +// constructor +CTSeq_Base::CTSeq_Base(void) + : m_Seqtype((ESeqtype)(0)), m_Gi(0), m_Taxid(0), m_Length(0) +{ + memset(m_set_State,0,sizeof(m_set_State)); +} + +// destructor +CTSeq_Base::~CTSeq_Base(void) +{ +} + + + +END_objects_SCOPE // namespace ncbi::objects:: + +END_NCBI_SCOPE + diff --git a/pool/shard007/C++/0094024_SphereTest.cpp b/pool/shard007/C++/0094024_SphereTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7096b95d46b0261f1a1f3700ab33f2ebb38e79f8 --- /dev/null +++ b/pool/shard007/C++/0094024_SphereTest.cpp @@ -0,0 +1,177 @@ +/* + This file is part of Magnum. + + Copyright © 2010, 2011, 2012, 2013, 2014, 2015 + Vladimír Vondruš <mosra@centrum.cz> + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. +*/ + +#include "Magnum/Magnum.h" +#include "Magnum/Math/Matrix3.h" +#include "Magnum/Math/Matrix4.h" +#include "Magnum/Shapes/LineSegment.h" +#include "Magnum/Shapes/Point.h" +#include "Magnum/Shapes/Sphere.h" + +#include "ShapeTestBase.h" + +namespace Magnum { namespace Shapes { namespace Test { + +struct SphereTest: TestSuite::Tester { + explicit SphereTest(); + + void transformed(); + void collisionPoint(); + void collisionPointInverted(); + void collisionLine(); + void collisionLineSegment(); + void collisionSphere(); + void collisionSphereInverted(); +}; + +SphereTest::SphereTest() { + addTests({&SphereTest::transformed, + &SphereTest::collisionPoint, + &SphereTest::collisionPointInverted, + &SphereTest::collisionLine, + &SphereTest::collisionLineSegment, + &SphereTest::collisionSphere, + &SphereTest::collisionSphereInverted}); +} + +void SphereTest::transformed() { + const Shapes::Sphere3D sphere({1.0f, 2.0f, 3.0f}, 7.0f); + + const auto transformed = sphere.transformed(Matrix4::scaling(Vector3(2.0f))*Matrix4::rotation(Deg(90.0f), Vector3::yAxis())); + CORRADE_COMPARE(transformed.position(), Vector3(6.0f, 4.0f, -2.0f)); + CORRADE_COMPARE(transformed.radius(), 14.0f); +} + +void SphereTest::collisionPoint() { + const Shapes::Sphere3D sphere({1.0f, 2.0f, 3.0f}, 2.0f); + + /* Collision */ + const Shapes::Point3D point({2.5f, 2.0f, 3.0f}); + const Shapes::Collision3D collision = sphere/point; + CORRADE_VERIFY(sphere%point && point%sphere); + CORRADE_COMPARE(collision.position(), point.position()); + CORRADE_COMPARE(collision.separationNormal(), -Vector3::xAxis()); + CORRADE_COMPARE(collision.separationDistance(), 0.5f); + + /* Collision, flipped */ + CORRADE_COMPARE(collision.separationNormal(), -(point/sphere).separationNormal()); + + /* Collision with ambiguous separation vector */ + const Shapes::Point3D point2(sphere.position()); + const Shapes::Collision3D collision2 = sphere/point2; + CORRADE_COMPARE(collision2.position(), point2.position()); + CORRADE_COMPARE(collision2.separationNormal(), Vector3::yAxis()); + CORRADE_COMPARE(collision2.separationDistance(), 2.0f); + + /* No collision */ + const Shapes::Point3D point3({-1.5f, 2.0f, 3.0f}); + CORRADE_VERIFY(!(sphere%point3) && !(sphere/point3)); +} + +void SphereTest::collisionPointInverted() { + const Shapes::InvertedSphere3D sphere({1.0f, 2.0f, 3.0f}, 2.0f); + + /* Collision */ + const Shapes::Point3D point({-1.5f, 2.0f, 3.0f}); + const Shapes::Collision3D collision = sphere/point; + CORRADE_VERIFY(sphere%point && point%sphere); + CORRADE_COMPARE(collision.position(), point.position()); + CORRADE_COMPARE(collision.separationNormal(), -Vector3::xAxis()); + CORRADE_COMPARE(collision.separationDistance(), 0.5f); + + /* Collision, flipped */ + CORRADE_COMPARE(collision.separationNormal(), -(point/sphere).separationNormal()); + + /* No collision */ + const Shapes::Point3D point3({2.0f, 2.0f, 3.0f}); + CORRADE_VERIFY(!(sphere%point3) && !(sphere/point3)); +} + +void SphereTest::collisionLine() { + Shapes::Sphere3D sphere({1.0f, 2.0f, 3.0f}, 2.0f); + Shapes::Line3D line({1.0f, 1.5f, 3.5f}, {1.0f, 2.5f, 2.5f}); + Shapes::Line3D line2({1.0f, 2.0f, 5.1f}, {1.0f, 3.0f, 5.1f}); + + VERIFY_COLLIDES(sphere, line); + VERIFY_NOT_COLLIDES(sphere, line2); +} + +void SphereTest::collisionLineSegment() { + Shapes::Sphere3D sphere({1.0f, 2.0f, 3.0f}, 2.0f); + Shapes::LineSegment3D line({1.0f, 2.0f, 4.9f}, {1.0f, 2.0f, 7.0f}); + Shapes::LineSegment3D line2({1.0f, 2.0f, 5.1f}, {1.0f, 2.0f, 7.0f}); + + VERIFY_COLLIDES(sphere, line); + VERIFY_NOT_COLLIDES(sphere, line2); +} + +void SphereTest::collisionSphere() { + const Shapes::Sphere3D sphere({1.0f, 2.0f, 3.0f}, 2.0f); + + /* Collision */ + const Shapes::Sphere3D sphere1({3.5f, 2.0f, 3.0f}, 1.0f); + const Shapes::Collision3D collision = sphere/sphere1; + CORRADE_VERIFY(sphere%sphere1 && sphere1%sphere); + CORRADE_COMPARE(collision.position(), sphere1.position() - Vector3::xAxis(sphere1.radius())); + CORRADE_COMPARE(collision.separationNormal(), -Vector3::xAxis()); + CORRADE_COMPARE(collision.separationDistance(), 0.5f); + + /* Collision, flipped */ + CORRADE_COMPARE(collision.separationNormal(), -(sphere1/sphere).separationNormal()); + + /* Collision with ambiguous separation vector */ + const Shapes::Sphere3D sphere2(sphere.position(), 0.5f); + const Shapes::Collision3D collision2 = sphere/sphere2; + CORRADE_COMPARE(collision2.position(), sphere2.position() + Vector3::yAxis(sphere2.radius())); + CORRADE_COMPARE(collision2.separationNormal(), Vector3::yAxis()); + CORRADE_COMPARE(collision2.separationDistance(), 2.5f); + + /* No collision */ + const Shapes::Sphere3D sphere3({-2.5f, 2.0f, 3.0f}, 1.0f); + CORRADE_VERIFY(!(sphere%sphere3) && !(sphere/sphere3)); +} + +void SphereTest::collisionSphereInverted() { + const Shapes::InvertedSphere3D sphere({1.0f, 2.0f, 3.0f}, 2.0f); + + /* Collision */ + const Shapes::Sphere3D sphere1({-0.5f, 2.0f, 3.0f}, 1.0f); + const Shapes::Collision3D collision = sphere/sphere1; + CORRADE_VERIFY(sphere%sphere1 && sphere1%sphere); + CORRADE_COMPARE(collision.position(), sphere1.position() - Vector3::xAxis(sphere1.radius())); + CORRADE_COMPARE(collision.separationNormal(), -Vector3::xAxis()); + CORRADE_COMPARE(collision.separationDistance(), 0.5f); + + /* Collision, flipped */ + CORRADE_COMPARE(collision.separationNormal(), -(sphere1/sphere).separationNormal()); + + /* No collision */ + const Shapes::Sphere3D sphere3({1.5f, 2.0f, 3.0f}, 1.0f); + CORRADE_VERIFY(!(sphere%sphere3) && !(sphere/sphere3)); +} + +}}} + +CORRADE_TEST_MAIN(Magnum::Shapes::Test::SphereTest) diff --git a/pool/shard007/C++/0094030_stmgr-register-processor.cpp b/pool/shard007/C++/0094030_stmgr-register-processor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e963ca5a3b226ec4978664179656c6275e6105f7 --- /dev/null +++ b/pool/shard007/C++/0094030_stmgr-register-processor.cpp @@ -0,0 +1,72 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include "processor/stmgr-register-processor.h" +#include <iostream> +#include <vector> +#include "processor/tmaster-processor.h" +#include "manager/tmaster.h" +#include "proto/messages.h" +#include "basics/basics.h" +#include "errors/errors.h" +#include "threads/threads.h" +#include "network/network.h" + +namespace heron { +namespace tmaster { + +StMgrRegisterProcessor::StMgrRegisterProcessor(REQID _reqid, Connection* _conn, + proto::tmaster::StMgrRegisterRequest* _request, + TMaster* _tmaster, Server* _server) + : Processor(_reqid, _conn, _request, _tmaster, _server) {} + +StMgrRegisterProcessor::~StMgrRegisterProcessor() { + // nothing to be done here +} + +void StMgrRegisterProcessor::Start() { + // We got a new stream manager registering to us + // Get the relevant info and ask tmaster to register + proto::tmaster::StMgrRegisterRequest* request = + static_cast<proto::tmaster::StMgrRegisterRequest*>(request_); + std::vector<proto::system::Instance*> instances; + for (sp_int32 i = 0; i < request->instances_size(); ++i) { + proto::system::Instance* instance = new proto::system::Instance(); + instance->CopyFrom(request->instances(i)); + instances.push_back(instance); + } + proto::system::PhysicalPlan* pplan = NULL; + + proto::system::Status* status = + tmaster_->RegisterStMgr(request->stmgr(), instances, GetConnection(), pplan); + + // Send the response + proto::tmaster::StMgrRegisterResponse response; + response.set_allocated_status(status); + if (status->status() == proto::system::OK) { + if (pplan) { + response.mutable_pplan()->CopyFrom(*pplan); + } + } + SendResponse(response); + delete this; + return; +} +} // namespace tmaster +} // namespace heron diff --git a/pool/shard007/C++/0094038_uifocussettingscontroller.cpp b/pool/shard007/C++/0094038_uifocussettingscontroller.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cef75713bc4524ab2d43e1ecb15a6239c3b3a07c --- /dev/null +++ b/pool/shard007/C++/0094038_uifocussettingscontroller.cpp @@ -0,0 +1,138 @@ +// This file is part of VSTGUI. It is subject to the license terms +// in the LICENSE file found in the top-level directory of this +// distribution and at http://github.com/steinbergmedia/vstgui/LICENSE + +#include "uifocussettingscontroller.h" + +#if VSTGUI_LIVE_EDITING + +#include "uidialogcontroller.h" +#include "uieditcontroller.h" +#include "uiactions.h" +#include "../uiattributes.h" +#include "../../lib/controls/ctextedit.h" +#include "../../lib/controls/coptionmenu.h" +#include <sstream> + +namespace VSTGUI { + +//---------------------------------------------------------------------------------------------------- +//---------------------------------------------------------------------------------------------------- +//---------------------------------------------------------------------------------------------------- +UIFocusSettingsController::UIFocusSettingsController (UIDescription* description, IActionPerformer* actionPerformer) +: editDescription (description) +, actionPerformer (actionPerformer) +{ + originalSettings = editDescription->getFocusDrawingSettings (); + for (auto& control : controls) + control = nullptr; +} + +//---------------------------------------------------------------------------------------------------- +CMessageResult UIFocusSettingsController::notify (CBaseObject* sender, IdStringPtr message) +{ + if (message == UIDialogController::kMsgDialogButton1Clicked) + { + FocusDrawingSettings fd; + + if (controls[kEnabledTag]) + fd.enabled = (controls[kEnabledTag]->getValue () == controls[kEnabledTag]->getMax ()) ? true : false; + if (controls[kColorTag]) + { + COptionMenu* menu = dynamic_cast<COptionMenu*>(controls[kColorTag]); + CMenuItem* item = menu->getCurrent (); + if (item) + fd.colorName = item->getTitle (); + } + if (controls[kWidthTag]) + fd.width = controls[kWidthTag]->getValue (); + if (originalSettings != fd) + actionPerformer->performChangeFocusDrawingSettings (fd); + return kMessageNotified; + } + return kMessageUnknown; +} + +//---------------------------------------------------------------------------------------------------- +CView* UIFocusSettingsController::verifyView (CView* view, const UIAttributes& attributes, const IUIDescription* description) +{ + CControl* control = dynamic_cast<CControl*>(view); + if (control) + { + switch (control->getTag ()) + { + case kEnabledTag: + { + control->setValue (originalSettings.enabled ? control->getMax () : control->getMin ()); + controls[kEnabledTag] = control; + break; + } + case kColorTag: + { + COptionMenu* menu = dynamic_cast<COptionMenu*>(control); + if (menu) + { + controls[kColorTag] = control; + std::list<const std::string*> names; + editDescription->collectColorNames (names); + names.sort (UIEditController::std__stringCompare); + int32_t index = 0; + for (auto& name : names) + { + menu->addEntry (new CMenuItem (name->c_str ())); + if (originalSettings.colorName == *name) + { + menu->setValue ((float)index); + } + index++; + } + } + break; + } + case kWidthTag: + { + controls[kWidthTag] = control; + CTextEdit* edit = dynamic_cast<CTextEdit*>(control); + if (edit) + { + edit->setStringToValueFunction (stringToValue); + edit->setValueToStringFunction (valueToString); + } + control->setValue (static_cast<float> (originalSettings.width)); + break; + } + } + } + return view; +} + +//---------------------------------------------------------------------------------------------------- +void UIFocusSettingsController::valueChanged (CControl* control) +{ +} + +//---------------------------------------------------------------------------------------------------- +bool UIFocusSettingsController::valueToString (float value, char utf8String[256], CParamDisplay::ValueToStringUserData* userData) +{ + int32_t intValue = (int32_t)value; + std::stringstream str; + str << (value == intValue ? intValue : value); + std::strcpy (utf8String, str.str ().c_str ()); + return true; +} + +//---------------------------------------------------------------------------------------------------- +bool UIFocusSettingsController::stringToValue (UTF8StringPtr txt, float& result, CTextEdit::StringToValueUserData* userData) +{ + if (txt) + { + float value = UTF8StringView (txt).toFloat (); + result = value; + return true; + } + return false; +} + +} // namespace + +#endif // VSTGUI_LIVE_EDITING diff --git a/pool/shard007/C++/0094039_UVa11582.cpp b/pool/shard007/C++/0094039_UVa11582.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c3056802078e98496d8bd57c1b2a6f2b0a4962e --- /dev/null +++ b/pool/shard007/C++/0094039_UVa11582.cpp @@ -0,0 +1,46 @@ +// UVa11582 Colossal Fibonacci Numbers! +// Rujia Liu +#include<iostream> +#include<cstring> +#include<cstdio> +using namespace std; + +const int maxn = 1000 + 5; +typedef unsigned long long ULL; + +int f[maxn][maxn*6], period[maxn]; + +int pow_mod(ULL a, ULL b, int n) { + if(!b) return 1; + int k = pow_mod(a, b/2, n); + k = k * k % n; + if(b % 2) k = k * a % n; + return k; +} + +int solve(ULL a, ULL b, int n) { + if(a == 0 || n == 1) return 0; // attention! + int p = pow_mod(a % period[n], b, period[n]); + return f[n][p]; +} + +int main() { + for(int n = 2; n <= 1000; n++) { + f[n][0] = 0; f[n][1] = 1; + for(int i = 2; ; i++) { + f[n][i] = (f[n][i-1] + f[n][i-2]) % n; + if(f[n][i-1] == 0 && f[n][i] == 1) { + period[n] = i - 1; + break; + } + } + } + ULL a, b; + int n, T; + cin >> T; + while(T--) { + cin >> a >> b >> n; + cout << solve(a, b, n) << "\n"; + } + return 0; +} diff --git a/pool/shard007/C++/0094043_Sound.cpp b/pool/shard007/C++/0094043_Sound.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6bab76ea86d76ff31f35596b28a7885e027c1a73 --- /dev/null +++ b/pool/shard007/C++/0094043_Sound.cpp @@ -0,0 +1,27 @@ +#include "core/features/Sound.hpp" + +#include <QSound> + +#include <iostream> +namespace Feature { + const QString Sound::NAME = "Sound"; + + Sound::Sound(const QString &label, const QString &path) : _label(label) { + _sound = new QSound(path); + } + + Sound::~Sound() { + delete _sound; + } + + QString Sound::getName() const { + return Sound::NAME; + } + + void Sound::play() { + if (_sound) + _sound->play(); + else + std::cerr << "Cannot play sound '" << _label.toStdString() << "' because it is NULL" << std::endl; + } +} diff --git a/pool/shard007/C++/0094046_dotProduct3.cpp b/pool/shard007/C++/0094046_dotProduct3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8f1bfe4b68c74e47fbb34a7b578d24da01cc5458 --- /dev/null +++ b/pool/shard007/C++/0094046_dotProduct3.cpp @@ -0,0 +1,83 @@ +#include <iostream> +#include <stdio.h> +#include <string.h> +#include <time.h> +#include "mpi.h" // message passing interface +using namespace std; + +// Do this ONCE when you start up thomas +// module load openmpi-x86_64 + +// New compile and run commands for MPI! +// mpicxx -o blah file.cpp +// mpirun -np 32 blah + +int main (int argc, char * argv[]) { + + int my_rank; // my CPU number for this process + int p; // number of CPUs that we have + int source; // rank of the sender + int dest; // rank of destination + int tag = 0; // message number + char message[100]; // message itself + MPI_Status status; // return status for receive + + // Start MPI + MPI_Init(&argc, &argv); + + // Find out my rank! + MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); + + // Find out the number of processes! + MPI_Comm_size(MPI_COMM_WORLD, &p); + + // THE REAL PROGRAM IS HERE + + srand(time(0)); +/* + int a[10], b[10]; + for (int x = 0; x < 10; x++) { + a[x] = rand() % 10; + b[x] = rand() % 10; + } + + int dotprod = 0; + for (int x = 0; x < 10; x++) + dotprod += a[x]*b[x]; + cout << dotprod << endl; +*/ + + // KNOW THE PROBLEM + int a[300000], b[300000]; + int n = 300000; + if (my_rank == 0) { + for (int x = 0; x < n; x++) { + a[x] = rand() % 8; + b[x] = rand() % 8; + } + } + + // DIVIDE THE PROBLEM UP + int local_n = n/p; + int * locala = new int[local_n]; + int * localb = new int[local_n]; + + MPI_Scatter(&a[0], local_n, MPI_INT, locala, local_n, MPI_INT, 0, MPI_COMM_WORLD); + MPI_Scatter(&b[0], local_n, MPI_INT, localb, local_n, MPI_INT, 0, MPI_COMM_WORLD); + + // After executing these lines of code, locala and localb all have the "right stuff" + + // DO THE LOCAL WORK + double localdot = 0; + for (int x = 0; x < local_n; x++) + localdot += locala[x] * localb[x]; + + // COLLECT THE RESULTS BACK IN THE OVERSEER + double dotproduct = 0; + MPI_Allreduce(&localdot, &dotproduct, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); + + // Shut down MPI + MPI_Finalize(); + + return 0; +} \ No newline at end of file diff --git a/pool/shard007/C++/0094057_DFA.cpp b/pool/shard007/C++/0094057_DFA.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c66f70e7682b0225e9a665b1abf1825f1f98c526 --- /dev/null +++ b/pool/shard007/C++/0094057_DFA.cpp @@ -0,0 +1,176 @@ +#include<iostream> +#include<string> +using namespace std; +#define VERTEX_COUNT_MAX 10 +const int VERTEX_COUNT = 4; +#define ARC_COUNT_MAX 4 +const int ARC_COUNT = 2; +#define MAX_FINAL_COUNT 5 +typedef char VElemType; +typedef char AElemType; +//the Vertex's data structure +struct Vertex +{ + VElemType data; + int Vid; +}vertex[VERTEX_COUNT_MAX]; +//the arc's data structure +typedef struct Arc +{ + AElemType data; + int Aid; +}arc[ARC_COUNT_MAX]; +//the final word about the DFA +char arrayFinal[MAX_FINAL_COUNT]; +//the array about DFA +char arrayDFA[VERTEX_COUNT + 1][ARC_COUNT + 1]={ + ' ','a','b', + 'S','U','V', + 'U','Q','V', + 'V','U','Q', + 'Q','Q','Q' +}; +int findFinal(char ch) +{ + for(int i=1;i<ARC_COUNT+1;i++) + { + if(arrayDFA[0][i]==ch) + { + return i; + } + } + return -1;//not find +} +int findNotFinal(char ch) +{ + for(int i=1;i<VERTEX_COUNT+1;i++) + { + if(arrayDFA[i][0]==ch) + { + return i; + } + } + return -1;//not find +} +//recognize the right str +string isRightStr(string str) +{ + char start='S';//init the start + char end='Q'; + for(int i=0;i<str.size();i++) + { + char ch=str[i]; + int row=findNotFinal(start); + int col=findFinal(ch); + if(row==-1||col==-1) + { + return "no"; + } + start=arrayDFA[row][col];//change the start + } + if(start==end) + return "yes"; + return "no"; +} +//delete the ' ' from the string where start and ending +string Trim(string str) +{ + string newStr=""; + int start; + for(int i=0;i<str.size();i++) + { + if(str[i]!=' ') + { + start=i; + break; + } + } + int end; + for(int i=str.size()-1;i>=0;i--) + { + if(str[i]!=' ') + { + end=i; + break; + } + } + for(int i=start;i<=end;i++) + { + newStr+=str[i]; + } + return newStr; +} +void TestTrim() +{ + string s=" aa av b "; + string news=Trim(s); + cout<<news.size()<<endl<<news<<endl; +} +string string1="S¡úaU|bV"; +//the char is lower like 'a','b'...'z' +bool isLower(char ch) +{ + if(ch>='a'&&ch<='z') + { + return true; + } + return false; +} +//the char is Uper like 'A','B'...'Z' +bool isUper(char ch) +{ + if(ch>='A'&&ch<='Z') + { + return true; + } + return false; +} +void TestChar() +{ + char ch; + cout<<"Please type a word: "; + while(cin>>ch) + { + if(isUper(ch)) + cout<<ch<<" is upper!"<<endl; + else if(isLower(ch)) + cout<<ch<<" is lower!"<<endl; + else + cout<<ch<<" is not word!"<<endl; + getchar(); + cout<<"Please type a word: "; + } +} +void divideString(string str) +{ + //delete the ' ' from the start and ending + string newStr=Trim(str); + int vertex_count=0; + int arc_count=0; +} +void Test() +{ + string str; + cout<<"ÇëÊäÈëÒªÑéÖ¤µÄ´®:"; + while(cin>>str) + { + cout<<isRightStr(str)<<endl; + system("pause"); + system("cls"); + cout<<"ÇëÊäÈëÒªÑéÖ¤µÄ´®:"; + } +} +int main() +{ + Test(); + return 0; +} +/* +4 +S¡úaU|bV +U¡úbV|aQ +V¡úaU|bQ +Q¡úaQ|bQ +1 +Q +*/ \ No newline at end of file diff --git a/pool/shard007/C++/0094060_user_script_slave.cc b/pool/shard007/C++/0094060_user_script_slave.cc new file mode 100644 index 0000000000000000000000000000000000000000..a06d856176bd4c614a186c7bcbb83d9ee11c7fcd --- /dev/null +++ b/pool/shard007/C++/0094060_user_script_slave.cc @@ -0,0 +1,235 @@ +// Copyright (c) 2009 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 "chrome/renderer/user_script_slave.h" + +#include "app/resource_bundle.h" +#include "base/command_line.h" +#include "base/histogram.h" +#include "base/logging.h" +#include "base/perftimer.h" +#include "base/pickle.h" +#include "base/shared_memory.h" +#include "base/string_util.h" +#include "chrome/common/chrome_switches.h" +#include "chrome/common/extensions/extension.h" +#include "chrome/common/extensions/extension_constants.h" +#include "chrome/renderer/extension_groups.h" +#include "googleurl/src/gurl.h" +#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" + +#include "grit/renderer_resources.h" + +using WebKit::WebFrame; +using WebKit::WebString; + +// These two strings are injected before and after the Greasemonkey API and +// user script to wrap it in an anonymous scope. +static const char kUserScriptHead[] = "(function (unsafeWindow) {\n"; +static const char kUserScriptTail[] = "\n})(window);"; + +// Sets up the chrome.extension module. This may be run multiple times per +// context, but the init method deletes itself after the first time. +static const char kInitExtension[] = + "if (chrome.initExtension) chrome.initExtension('%s', true);"; + + +int UserScriptSlave::GetIsolatedWorldId(const std::string& extension_id) { + typedef std::map<std::string, int> IsolatedWorldMap; + + static IsolatedWorldMap g_isolated_world_ids; + static int g_next_isolated_world_id = 1; + + IsolatedWorldMap::iterator iter = g_isolated_world_ids.find(extension_id); + if (iter != g_isolated_world_ids.end()) + return iter->second; + + int new_id = g_next_isolated_world_id; + ++g_next_isolated_world_id; + + // This map will tend to pile up over time, but realistically, you're never + // going to have enough extensions for it to matter. + g_isolated_world_ids[extension_id] = new_id; + return new_id; +} + +UserScriptSlave::UserScriptSlave() + : shared_memory_(NULL), + script_deleter_(&scripts_) { + api_js_ = ResourceBundle::GetSharedInstance().GetRawDataResource( + IDR_GREASEMONKEY_API_JS); +} + +void UserScriptSlave::GetActiveExtensions(std::set<std::string>* extension_ids) { + for (size_t i = 0; i < scripts_.size(); ++i) { + DCHECK(!scripts_[i]->extension_id().empty()); + extension_ids->insert(scripts_[i]->extension_id()); + } +} + +bool UserScriptSlave::UpdateScripts(base::SharedMemoryHandle shared_memory) { + scripts_.clear(); + + // Create the shared memory object (read only). + shared_memory_.reset(new base::SharedMemory(shared_memory, true)); + if (!shared_memory_.get()) + return false; + + // First get the size of the memory block. + if (!shared_memory_->Map(sizeof(Pickle::Header))) + return false; + Pickle::Header* pickle_header = + reinterpret_cast<Pickle::Header*>(shared_memory_->memory()); + + // Now map in the rest of the block. + int pickle_size = sizeof(Pickle::Header) + pickle_header->payload_size; + shared_memory_->Unmap(); + if (!shared_memory_->Map(pickle_size)) + return false; + + // Unpickle scripts. + void* iter = NULL; + size_t num_scripts = 0; + Pickle pickle(reinterpret_cast<char*>(shared_memory_->memory()), + pickle_size); + pickle.ReadSize(&iter, &num_scripts); + + scripts_.reserve(num_scripts); + for (size_t i = 0; i < num_scripts; ++i) { + scripts_.push_back(new UserScript()); + UserScript* script = scripts_.back(); + script->Unpickle(pickle, &iter); + + // Note that this is a pointer into shared memory. We don't own it. It gets + // cleared up when the last renderer or browser process drops their + // reference to the shared memory. + for (size_t j = 0; j < script->js_scripts().size(); ++j) { + const char* body = NULL; + int body_length = 0; + CHECK(pickle.ReadData(&iter, &body, &body_length)); + script->js_scripts()[j].set_external_content( + base::StringPiece(body, body_length)); + } + for (size_t j = 0; j < script->css_scripts().size(); ++j) { + const char* body = NULL; + int body_length = 0; + CHECK(pickle.ReadData(&iter, &body, &body_length)); + script->css_scripts()[j].set_external_content( + base::StringPiece(body, body_length)); + } + } + + return true; +} + +// static +void UserScriptSlave::InsertInitExtensionCode( + std::vector<WebScriptSource>* sources, const std::string& extension_id) { + DCHECK(sources); + sources->insert(sources->begin(), + WebScriptSource(WebString::fromUTF8( + StringPrintf(kInitExtension, extension_id.c_str())))); +} + +bool UserScriptSlave::InjectScripts(WebFrame* frame, + UserScript::RunLocation location) { + GURL frame_url = GURL(frame->url()); + // Don't bother if this is not a URL we inject script into. + if (!URLPattern::IsValidScheme(frame_url.scheme())) + return true; + + // Don't inject user scripts into the gallery itself. This prevents + // a user script from removing the "report abuse" link, for example. + if (frame_url.host() == GURL(extension_urls::kGalleryBrowsePrefix).host()) + return true; + + PerfTimer timer; + int num_css = 0; + int num_scripts = 0; + + for (size_t i = 0; i < scripts_.size(); ++i) { + std::vector<WebScriptSource> sources; + UserScript* script = scripts_[i]; + + if (frame->parent() && !script->match_all_frames()) + continue; // Only match subframes if the script declared it wanted to. + + if (!script->MatchesUrl(frame->url())) + continue; // This frame doesn't match the script url pattern, skip it. + + // CSS files are always injected on document start before js scripts. + if (location == UserScript::DOCUMENT_START) { + num_css += script->css_scripts().size(); + for (size_t j = 0; j < script->css_scripts().size(); ++j) { + PerfTimer insert_timer; + UserScript::File& file = script->css_scripts()[j]; + frame->insertStyleText( + WebString::fromUTF8(file.GetContent().as_string()), WebString()); + UMA_HISTOGRAM_TIMES("Extensions.InjectCssTime", insert_timer.Elapsed()); + } + } + if (script->run_location() == location) { + num_scripts += script->js_scripts().size(); + for (size_t j = 0; j < script->js_scripts().size(); ++j) { + UserScript::File &file = script->js_scripts()[j]; + std::string content = file.GetContent().as_string(); + + // We add this dumb function wrapper for standalone user script to + // emulate what Greasemonkey does. + if (script->is_standalone() || script->emulate_greasemonkey()) { + content.insert(0, kUserScriptHead); + content += kUserScriptTail; + } + sources.push_back( + WebScriptSource(WebString::fromUTF8(content), file.url())); + } + } + + if (!sources.empty()) { + int isolated_world_id = 0; + + // Emulate Greasemonkey API for scripts that were converted to extensions + // and "standalone" user scripts. + if (script->is_standalone() || script->emulate_greasemonkey()) { + sources.insert(sources.begin(), + WebScriptSource(WebString::fromUTF8(api_js_.as_string()))); + } + + // Setup chrome.self to contain an Extension object with the correct + // ID. + if (!script->extension_id().empty()) { + InsertInitExtensionCode(&sources, script->extension_id()); + isolated_world_id = GetIsolatedWorldId(script->extension_id()); + } + + PerfTimer exec_timer; + frame->executeScriptInIsolatedWorld( + isolated_world_id, &sources.front(), sources.size(), + EXTENSION_GROUP_CONTENT_SCRIPTS); + UMA_HISTOGRAM_TIMES("Extensions.InjectScriptTime", exec_timer.Elapsed()); + } + } + + // Log debug info. + if (location == UserScript::DOCUMENT_START) { + UMA_HISTOGRAM_COUNTS_100("Extensions.InjectStart_CssCount", num_css); + UMA_HISTOGRAM_COUNTS_100("Extensions.InjectStart_ScriptCount", num_scripts); + if (num_css || num_scripts) + UMA_HISTOGRAM_TIMES("Extensions.InjectStart_Time", timer.Elapsed()); + } else if (location == UserScript::DOCUMENT_END) { + UMA_HISTOGRAM_COUNTS_100("Extensions.InjectEnd_ScriptCount", num_scripts); + if (num_scripts) + UMA_HISTOGRAM_TIMES("Extensions.InjectEnd_Time", timer.Elapsed()); + } else if (location == UserScript::DOCUMENT_IDLE) { + UMA_HISTOGRAM_COUNTS_100("Extensions.InjectIdle_ScriptCount", num_scripts); + if (num_scripts) + UMA_HISTOGRAM_TIMES("Extensions.InjectIdle_Time", timer.Elapsed()); + } else { + NOTREACHED(); + } + + LOG(INFO) << "Injected " << num_scripts << " scripts and " << num_css << + "css files into " << frame->url().spec().data(); + return true; +} diff --git a/pool/shard007/C++/0094071_core_Misc.cpp b/pool/shard007/C++/0094071_core_Misc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..462709e8f7d415840dd2917bd6dd6cbdb7fceaf7 --- /dev/null +++ b/pool/shard007/C++/0094071_core_Misc.cpp @@ -0,0 +1,179 @@ +/////////////////////////////////////////////////////////////////////////////// +// GPU inicialization/deinicialization functions +#include "newGPU.h" +#include "fixed.h" + +#if defined(PSP) || defined(DREAMCAST) +#include "string.h" +#else +// EDIT: Not found and not needed: #include "memory.h" +#endif + +/////////////////////////////////////////////////////////////////////////////// +//#define GetMem(p1) malloc((p1)) +//#define FreeMem(p1) free((p1)) +#define CopyMemory(Destination,Source,Length) memcpy((Destination),(Source),(Length)) +//#define ZeroMemory(Destination,Length) memset((Destination),0,(Length)) +#define CopyMem(p1,p2,p3) CopyMemory((p1),(p2),(p3)) +//#define ZeroMem(p1,p2) ZeroMemory((p1),(p2)) + +extern int global_enable_frameskip; + +/////////////////////////////////////////////////////////////////////////////// +void gpuReset(void) +{ + //ZeroMem(&gpuFreezeBegin, + // (long) &gpuFreezeEnd - (long) &gpuFreezeBegin); + GPU_GP1 = 0x14802000; + TextureWindow[0] = 0; + TextureWindow[1] = 0; + TextureWindow[2] = 255; + TextureWindow[3] = 255; + DrawingArea[2] = 256; + DrawingArea[3] = 240; + DisplayArea[2] = 256; + DisplayArea[3] = 240; + DisplayArea[6] = 256; + DisplayArea[7] = 240; + + Skip = 0; + if(global_enable_frameskip) + { + DrawingCount[0] = 3; + DrawingCount[1] = 3; + } + else + { + DrawingCount[0] = 0; + DrawingCount[1] = 0; + } + DrawingCount[2] = 0; + DrawingCount[3] = 0; + DisplayCount[0] = Config.PsxType == 0 ? 16714 : 20050; + DisplayCount[1] = 0; + DisplayCount[2] = 0; + DisplayCount[3] = 0; + curFPS = 0; + lastFPSCheck = timeGetTime(); +} + +BOOL gpuInnerInit(); + +/////////////////////////////////////////////////////////////////////////////// +extern "C" long GPU_init(void) +{ + GPU_updateLace = GPUupdateLace; + vBlank = 0; + gpuInnerInit(); + gp2x_video_RGB_clearscreen16(); + gpuDrawInit(); + gpuReset(); + xInit(); + return (0); +} + +/////////////////////////////////////////////////////////////////////////////// +extern "C" long GPU_open(unsigned long * unused1, char * unused2, char * unused3) +{ + return 0; +} + +/////////////////////////////////////////////////////////////////////////////// +extern "C" long GPU_close(void) +{ + return 0; +} + +/////////////////////////////////////////////////////////////////////////////// +extern "C" long GPU_shutdown(void) +{ + return 0; +} + + +/////////////////////////////////////////////////////////////////////////////// +extern "C" long GPU_freeze(uint32_t bWrite, GPUFreeze_t* p2) +{ +//u32 temp; + /* + if (p1 == 2) { + temp = *(u32 *) p2; + if ((temp < 0) || (temp > 8)) + return (0); + return (1); + } + */ + if (!p2) + return (0); + + if (p2->ulFreezeVersion != 1) + return (0); + + if (bWrite) + { + p2->GP1 = GPU_GP1; + //CopyMem(p2->Control, &gpuFreezeBegin, + // (long) &gpuFreezeEnd - (long) &gpuFreezeBegin); + CopyMem(p2->FrameBuffer, (u16*)GPU_FrameBuffer, FRAME_BUFFER_SIZE); + p2->isPAL = isPAL; + p2->isDisplaySet = isDisplaySet; + CopyMem(p2->DisplayArea, DisplayArea, 8*4); + CopyMem(p2->DirtyArea, DirtyArea, 4*4); + CopyMem(p2->LastDirtyArea, LastDirtyArea, 4*4); + CopyMem(p2->CheckArea, CheckArea, 4*4); + + CopyMem(p2->TextureWindow, TextureWindow, 4*4); + CopyMem(p2->DrawingArea, DrawingArea, 4*4); + CopyMem(p2->DrawingOffset, DrawingOffset, 2*4); + p2->MaskU = MaskU; + p2->MaskV = MaskV; + p2->Masking = Masking; + p2->PixelMSB = PixelMSB; + p2->vBlank = vBlank; + return (1); + } + else + { + GPU_GP1 = p2->GP1; + //CopyMem(&gpuFreezeBegin, p2->Control, + // (long) &gpuFreezeEnd - (long) &gpuFreezeBegin); + CopyMem((u16*)GPU_FrameBuffer, p2->FrameBuffer, FRAME_BUFFER_SIZE); + isPAL = p2->isPAL; + isDisplaySet = p2->isDisplaySet; + CopyMem(DisplayArea, p2->DisplayArea, 8*4); + CopyMem(DirtyArea, p2->DirtyArea, 4*4); + CopyMem(LastDirtyArea, p2->LastDirtyArea, 4*4); + CopyMem(CheckArea, p2->CheckArea, 4*4); + + CopyMem(TextureWindow, p2->TextureWindow, 4*4); + CopyMem(DrawingArea, p2->DrawingArea, 4*4); + CopyMem(DrawingOffset, p2->DrawingOffset, 2*4); + MaskU = p2->MaskU; + MaskV = p2->MaskV; + Masking = p2->Masking; + PixelMSB = p2->PixelMSB; + vBlank = p2->vBlank; + return (1); + } + return (0); +} + +extern "C" void GPU_vBlank( int val ) +{ + if(val == 0) + { + /* NOTE: GP1 must have the interlace bit toggle here, + since it shouldn't be in readStatus as it was previously */ + GPU_GP1 ^= 0x80000000; + } + vBlank = val; +} + +extern "C" long GPU_getScreenPic(unsigned char * pMem) +{ +} + +extern "C" uint32_t GPU_readStatus(void) +{ + return GPU_GP1 | (vBlank ? 0x80000000 : 0 ); +} diff --git a/pool/shard007/C++/0094077_PrettyStackTrace.cpp b/pool/shard007/C++/0094077_PrettyStackTrace.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5b3dbaff856deea3460ed065407ca331eb324d24 --- /dev/null +++ b/pool/shard007/C++/0094077_PrettyStackTrace.cpp @@ -0,0 +1,197 @@ +//===--- PrettyStackTrace.cpp - Swift-specific PrettyStackTraceEntries ----===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See http://swift.org/LICENSE.txt for license information +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// +// +// This file implements several Swift-specific implementations of +// PrettyStackTraceEntry. +// +//===----------------------------------------------------------------------===// + +#include "swift/AST/AST.h" +#include "swift/AST/PrettyStackTrace.h" +#include "swift/AST/TypeVisitor.h" +#include "swift/Basic/SourceManager.h" +#include "llvm/Support/raw_ostream.h" +#include "llvm/Support/MemoryBuffer.h" + +using namespace swift; + +void PrettyStackTraceDecl::print(llvm::raw_ostream &out) const { + out << "While " << Action << ' '; + if (!TheDecl) { + out << "NULL declaration!\n"; + return; + } + printDeclDescription(out, TheDecl, TheDecl->getASTContext()); +} + +void swift::printDeclDescription(llvm::raw_ostream &out, const Decl *D, + ASTContext &Context) { + bool hasPrintedName = false; + if (auto *named = dyn_cast<ValueDecl>(D)) { + if (named->hasName()) { + out << '\'' << named->getName() << '\''; + hasPrintedName = true; + } else if (auto *fn = dyn_cast<FuncDecl>(named)) { + if (auto *ASD = fn->getAccessorStorageDecl()) { + if (ASD->hasName()) { + switch (fn->getAccessorKind()) { + case AccessorKind::NotAccessor: + llvm_unreachable("Isn't an accessor?"); + case AccessorKind::IsGetter: + out << "getter"; + break; + case AccessorKind::IsSetter: + out << "setter"; + break; + case AccessorKind::IsWillSet: + out << "willset"; + break; + case AccessorKind::IsDidSet: + out << "didset"; + break; + case AccessorKind::IsMaterializeForSet: + out << "materializeForSet"; + break; + case AccessorKind::IsAddressor: + out << "addressor"; + break; + case AccessorKind::IsMutableAddressor: + out << "mutableAddressor"; + break; + } + + out << " for " << ASD->getFullName(); + hasPrintedName = true; + } + } + } + } + + if (!hasPrintedName) + out << "declaration " << (const void *)D; + + out << " at "; + D->getStartLoc().print(out, Context.SourceMgr); + out << '\n'; +} + +void PrettyStackTraceExpr::print(llvm::raw_ostream &out) const { + out << "While " << Action << ' '; + if (!TheExpr) { + out << "NULL expression!\n"; + return; + } + printExprDescription(out, TheExpr, Context); +} + +void swift::printExprDescription(llvm::raw_ostream &out, Expr *E, + ASTContext &Context) { + out << "expression at "; + E->getSourceRange().print(out, Context.SourceMgr); + out << '\n'; +} + +void PrettyStackTraceStmt::print(llvm::raw_ostream &out) const { + out << "While " << Action << ' '; + if (!TheStmt) { + out << "NULL statement!\n"; + return; + } + printStmtDescription(out, TheStmt, Context); +} + +void swift::printStmtDescription(llvm::raw_ostream &out, Stmt *S, + ASTContext &Context) { + out << "statement at "; + S->getSourceRange().print(out, Context.SourceMgr); + out << '\n'; +} + +void PrettyStackTracePattern::print(llvm::raw_ostream &out) const { + out << "While " << Action << ' '; + if (!ThePattern) { + out << "NULL pattern!\n"; + return; + } + printPatternDescription(out, ThePattern, Context); +} + +void swift::printPatternDescription(llvm::raw_ostream &out, Pattern *P, + ASTContext &Context) { + out << "pattern at "; + P->getSourceRange().print(out, Context.SourceMgr); + out << '\n'; +} + +namespace { + /// Map a Type to an interesting declaration whose source range we + /// should print. + struct InterestingDeclForType + : TypeVisitor<InterestingDeclForType, Decl*> { + Decl *visitType(TypeBase *type) { + return nullptr; + } + Decl *visitUnboundGenericType(UnboundGenericType *type) { + return type->getDecl(); + } + Decl *visitBoundGenericType(BoundGenericType *type) { + return type->getDecl(); + } + Decl *visitNominalType(NominalType *type) { + return type->getDecl(); + } + Decl *visitNameAliasType(NameAliasType *type) { + return type->getDecl(); + } + }; +} + +void PrettyStackTraceType::print(llvm::raw_ostream &out) const { + out << "While " << Action << ' '; + if (TheType.isNull()) { + out << "NULL type!\n"; + return; + } + printTypeDescription(out, TheType, Context); +} + +void swift::printTypeDescription(llvm::raw_ostream &out, Type type, + ASTContext &Context) { + out << "type '" << type << '\''; + if (Decl *decl = InterestingDeclForType().visit(type)) { + out << " (declared at "; + decl->getSourceRange().print(out, Context.SourceMgr); + out << ')'; + } + out << '\n'; +} + +void PrettyStackTraceTypeRepr::print(llvm::raw_ostream &out) const { + out << "While " << Action << " type "; + TheType->print(out); + if (TheType && TheType->getSourceRange().isValid()) { + out << " at "; + TheType->getSourceRange().print(out, Context.SourceMgr); + } + out << '\n'; +} + +void swift::printSourceLocDescription(llvm::raw_ostream &out, + SourceLoc loc, ASTContext &ctx) { + loc.print(out, ctx.SourceMgr); + out << '\n'; +} + +void PrettyStackTraceLocation::print(llvm::raw_ostream &out) const { + out << "While " << Action << " starting at "; + printSourceLocDescription(out, Loc, Context); +} diff --git a/pool/shard007/C++/0094086_async_layout.cpp b/pool/shard007/C++/0094086_async_layout.cpp new file mode 100644 index 0000000000000000000000000000000000000000..60a55b37550d7e6d3650e256ab3a2f3b788c1d0d --- /dev/null +++ b/pool/shard007/C++/0094086_async_layout.cpp @@ -0,0 +1,133 @@ +// async_layout.cpp +/* + neogfx C++ App/Game Engine + Copyright (c) 2021 Leigh Johnston. All Rights Reserved. + + This program is free software: you can redistribute it and / or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include <neogfx/neogfx.hpp> +#include <neogfx/gui/layout/async_layout.hpp> + +template <> neogfx::i_async_layout& services::start_service<neogfx::i_async_layout>() +{ + static neogfx::async_layout sAsyncLayout; + return sAsyncLayout; +} + +namespace neogfx +{ + async_layout::async_layout() : + iTimer{ service<i_async_task>(), [this](neolib::callback_timer& aTimer) + { + aTimer.again(); + process(); + }, std::chrono::milliseconds{ 20 } } + { + } + + bool async_layout::exists(i_widget& aWidget) const noexcept + { + return pending(aWidget) || processing(aWidget); + } + + bool async_layout::defer_layout(i_widget& aWidget) + { + if (aWidget.has_root()) + { + if (!exists(aWidget)) + iPending.emplace_back(aWidget, &aWidget); + else + invalidate(aWidget); + return true; + } + return false; + } + + void async_layout::validate(i_widget& aWidget) + { + if (auto existing = pending(aWidget)) + (**existing).validated = true; + else if (existing = processing(aWidget)) + (**existing).validated = true; + } + + void async_layout::invalidate(i_widget& aWidget) + { + if (auto existing = pending(aWidget)) + (**existing).validated = false; + else if (existing = processing(aWidget)) + (**existing).validated = false; + } + + std::optional<async_layout::entry_queue::const_iterator> async_layout::pending(i_widget& aWidget) const noexcept + { + auto existing = std::find_if(iPending.begin(), iPending.end(), [&](auto const& e) { return !e.destroyed && e.widget == &aWidget; }); + if (existing != iPending.end()) + return existing; + else + return std::nullopt; + } + + std::optional<async_layout::entry_queue::iterator> async_layout::pending(i_widget& aWidget) noexcept + { + auto existing = std::find_if(iPending.begin(), iPending.end(), [&](auto const& e) { return !e.destroyed && e.widget == &aWidget; }); + if (existing != iPending.end()) + return existing; + else + return std::nullopt; + } + + std::optional<async_layout::entry_queue::const_iterator> async_layout::processing(i_widget& aWidget) const noexcept + { + auto existing = std::find_if(iProcessing.begin(), iProcessing.end(), [&](auto const& e) { return !e.destroyed && e.widget == &aWidget; }); + if (existing != iProcessing.end()) + return existing; + else + return std::nullopt; + } + + std::optional<async_layout::entry_queue::iterator> async_layout::processing(i_widget& aWidget) noexcept + { + auto existing = std::find_if(iProcessing.begin(), iProcessing.end(), [&](auto const& e) { return !e.destroyed && e.widget == &aWidget; }); + if (existing != iProcessing.end()) + return existing; + else + return std::nullopt; + } + + void async_layout::process() + { + std::swap(iPending, iProcessing); + + for (auto& e : iProcessing) + { + if (e.validated || e.destroyed) + continue; + auto& next = *e.widget; +#ifdef NEOGFX_DEBUG + if (debug::layoutItem == &next) + service<debug::logger>() << typeid(next).name() << ": async_layout::process()" << endl; +#endif + if (next.root().has_native_window()) + { + neolib::scoped_optional_if soi{ next.layout_reason(), layout_reason::Async }; + next.layout_items(); + next.update(); + } + } + + iProcessing.clear(); + } +} \ No newline at end of file diff --git a/pool/shard007/C++/0094091_JSONParser.cpp b/pool/shard007/C++/0094091_JSONParser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..53b93d85e3a3aa57cef01bddddcd33caa464b9c4 --- /dev/null +++ b/pool/shard007/C++/0094091_JSONParser.cpp @@ -0,0 +1,190 @@ +//JSONParser.cpp +//Author: Bombo +//09.03.2017 +//Класс JSONParser производит проверку и обработку запросов в формате JSON + +#include"JSONParser.h" + +//************************************JSONParser*********************************************// +JSONParser::JSONParser() +{ + pcJSONRequest = NULL; + stStartPointer = -1; + stEndPointer = -1; + pjfFirst = NULL; +} + +JSONParser::JSONParser(char * const in_pcJSONRequest) +{ + size_t stLen; + + if(in_pcJSONRequest == NULL || (stLen = strlen(in_pcJSONRequest)) == 0) + { + pcJSONRequest = NULL; + return; + } + + pcJSONRequest = new char[stLen+1]; + memset(pcJSONRequest, 0, stLen + 1); + strncpy(pcJSONRequest, in_pcJSONRequest, stLen); + + stStartPointer = 0; + stEndPointer = stLen-1; + + pjfFirst = NULL; +} + +JSONParser::~JSONParser() +{ + JSONField *pjfList; + + if(pcJSONRequest != NULL) + { + delete [] pcJSONRequest; + } + + pjfList = pjfFirst; + while(pjfList != NULL) + { + pjfList = pjfFirst->pjfNext; + delete pjfFirst; + pjfFirst = pjfList; + } +} + +bool JSONParser::CheckRequest(void) +{ + int nIndex; + long lBraceCounter, lBracketCounter, lQuotesCounter; + + // pcJSONRequest = new char[128]; //отладка!!! + // memset(pcJSONRequest, 0, 128); //отладка!!! + // strncpy(pcJSONRequest, "[{\"\"}\"]\"]", 127); //отладка!!! + // fprintf(stderr, "JSONParser::CheckRequest() : Start debug:\n%s\n", pcJSONRequest); //отладка!!! + // stStartPointer = 0; //отладка!!! + // stEndPointer = (long) strlen((char *)pcJSONRequest); //отладка!!! + + if(pcJSONRequest == NULL || strlen(pcJSONRequest) == 0 || stStartPointer < 0 || stEndPointer < 0) + return false; + + lBraceCounter = lBracketCounter = lQuotesCounter = 0; + for(nIndex = stStartPointer; nIndex < stEndPointer; ++nIndex) + { + switch(pcJSONRequest[nIndex]) + { + case '[': + { + if(lQuotesCounter == 0) + lBracketCounter++; + break; + } + case ']': + { + if(lQuotesCounter == 0) + lBracketCounter--; + break; + } + case '\"': + { + if(nIndex > 0 && pcJSONRequest[nIndex-1] != '\\') + lQuotesCounter ^= 1; + break; + } + case '{': + { + if(lQuotesCounter == 0) + lBraceCounter++; + break; + } + case '}': + { + if(lQuotesCounter == 0) + lBraceCounter--; + break; + } + } + } + if(lQuotesCounter == 0 && lBraceCounter == 0 && lBracketCounter == 0) + return true; + + fprintf(stderr, "JSONParser::CheckRequest() : Wrong JSON format!!!\n%s\n", pcJSONRequest); + return false; +} + +void JSONParser::InitFields(void) +{ + if(!CheckRequest()) + return; + + //получаем имена и значения полей для текущей записи в JSON-запросе + //для этого анализируем запись между stStartPointer и stEndPointer + //... +} + +//метод возвращает true, если ещё остались необработанные поля +bool JSONParser::ParseUndefined(void) +{ + //получаем первую запись из списка полей + //... + + //обрабатываем запись в зависимости от значения её имени + //... + + //если в списке есть ещё поля - возвращаем true + //... + + return false; +} + +//метод обрабатывает все записи в запросе (при помощи обработчика полей каждой записи, ParseUndefined()) +void JSONParser::ParseAllItems(void) +{ + return; +} + +//*************************************JSONField*********************************************// + +JSONField::JSONField(void) +{ + pcName = NULL; + pcValue = NULL; + pjfNext = NULL; +} + +JSONField::JSONField(char * const in_pcName, char * const in_pcValue) +{ + size_t stLen; + + if(in_pcName == NULL || (stLen = strlen(in_pcName)) == 0) + { + pcName = NULL; + pcValue = NULL; + pjfNext = NULL; + return; + } + pcName = new char[stLen + 1]; + memset(pcName, 0, stLen + 1); + strncpy(pcName, in_pcName, stLen); + + if(in_pcValue == NULL || (stLen = strlen(in_pcValue)) == 0) + { + pcValue = new char[2]; + memset(pcValue, 0, 2); + } + else + { + pcValue = new char[stLen + 1]; + memset(pcValue, 0, stLen + 1); + strncpy(pcValue, in_pcValue, stLen); + } + + pjfNext = NULL; +} + +JSONField::~JSONField() +{ + if(pcName != NULL) + delete [] pcName; + if(pcValue != NULL) + delete [] pcValue; +} diff --git a/pool/shard007/C++/0094097_WatchdogAppRunner.cpp b/pool/shard007/C++/0094097_WatchdogAppRunner.cpp new file mode 100644 index 0000000000000000000000000000000000000000..90c64ffb897ebc2fe77705a49190474ef51f262d --- /dev/null +++ b/pool/shard007/C++/0094097_WatchdogAppRunner.cpp @@ -0,0 +1,164 @@ +#include "WatchdogAppRunner.h" +#include "HTTPWatchdogServer.h" +#include "firtex/extension/util/Application.h" +#include "firtex/extension/util/SharedOptionCallback.h" +#include "firtex/extension/util/OptionException.h" + +#include "RPCWatchdogServer.h" + +using namespace std; +// using namespace apache; +// using namespace apache::thrift; + +FX_NS_USE(common); +FX_NS_USE(config); +FX_NS_USE(thread); +FX_NS_USE(util); +FX_NS_USE(utility); + +FX_NS_DEF(app); + +SETUP_LOGGER(app, WatchdogAppRunner); + +WatchdogAppRunner::WatchdogAppRunner() + : m_sServiceType("rpc") + , m_nListenPort(0) +{ +} + +WatchdogAppRunner::~WatchdogAppRunner() +{ +} + +AppRunner::Status WatchdogAppRunner::run() +{ + if (m_sServiceType == "http") + { + if (!initHttpServer()) + { + return S_EXIT; + } + } + else + { + if (!initRPCServer()) + { + return S_EXIT; + } + } + + try + { + m_pServer->run(); + return S_RUNNING; + } + catch(const FirteXException& e) + { + FX_LOG(ERROR, "Run watchdog server FAILED: [%s]", e.what().c_str()); + return S_EXIT; + } + return S_EXIT; +} + +bool WatchdogAppRunner::initHttpServer() +{ + m_pServer.reset(new HTTPWatchdogServer(m_sWorkDir, m_nListenPort)); + if (!m_pServer->init("")) + { + FX_LOG(ERROR, "Initialize HTTP watchdog server FAILED."); + return false; + } + return true; +} + +bool WatchdogAppRunner::initRPCServer() +{ + m_pServer.reset(new RPCWatchdogServer(m_sWorkDir, m_nListenPort)); + if (!m_pServer->init("")) + { + FX_LOG(ERROR, "Initialize RPC server FAILED."); + return false; + } + return true; +} + +void WatchdogAppRunner::registerOption(Application* pApp) +{ + pApp->addDescription("Setup daemon server : "); + pApp->addDescription(string(" ") + pApp->getProgName() + + " -p [LISTEN_PORT] -t [SERVICE_TYPE]"); + + pApp->addOption(Option("listen-port", "p", "listen port") + .required(true) + .repeatable(false) + .argument("[LISTEN_PORT]", true) + .callback(SharedOptionCallback(this, &AppRunner::optionCallback))); + + pApp->addOption(Option("work-dir", "w", "work directory") + .required(true) + .repeatable(false) + .argument("[WORK_DIR]", true) + .callback(SharedOptionCallback(this, &AppRunner::optionCallback))); + + pApp->addOption(Option("service-type", "t", "specify service type (rpc/http)") + .repeatable(false) + .argument("[SERVICE_TYPE]", true) + .callback(SharedOptionCallback(this, &AppRunner::optionCallback))); +} + +void WatchdogAppRunner::optionCallback(const Option& option, + const string& sValue) +{ + if (option.matchFull("service-type") || option.matchShort("t")) + { + if (sValue.empty()) + { + throw MissingArgumentException("--service-type/-t"); + } + + if (sValue != "rpc" && sValue != "http") + { + FIRTEX_THROW(BadParameterException, "the value of --service-type " + "must be rpc or http"); + } + m_sServiceType = sValue; + } + + if (option.matchFull("listen-port") || option.matchShort("p")) + { + if (sValue.empty()) + { + throw MissingArgumentException("--listen-port/-p"); + } + + m_nListenPort = NumberParser::parseInt32(sValue); + } + + if (option.matchFull("work-dir") || option.matchShort("w")) + { + if (sValue.empty()) + { + throw MissingArgumentException("--work-dir/-w"); + } + + m_sWorkDir = sValue; + } +} + +void WatchdogAppRunner::stop() +{ + if (m_pServer) + { + m_pServer->stop(); + } +} + +void WatchdogAppRunner::waitStop() +{ + if (m_pServer) + { + m_pServer->join(); + } +} + +FX_NS_END diff --git a/pool/shard007/C++/0094099_GUIViewStatePVR.cpp b/pool/shard007/C++/0094099_GUIViewStatePVR.cpp new file mode 100644 index 0000000000000000000000000000000000000000..411749c74a196a168362d4080f7d337b2148fb6b --- /dev/null +++ b/pool/shard007/C++/0094099_GUIViewStatePVR.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2012-2013 Team XBMC + * http://www.xbmc.org + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XBMC; see the file COPYING. If not, see + * <http://www.gnu.org/licenses/>. + * + */ + +#include "GUIViewStatePVR.h" +#include "GUIWindowPVR.h" +#include "GUIWindowPVRCommon.h" +#include "guilib/GUIWindowManager.h" +#include "settings/GUISettings.h" +#include "settings/Settings.h" + +using namespace PVR; + +CGUIViewStatePVR::CGUIViewStatePVR(const CFileItemList& items) : + CGUIViewState(items) +{ + PVRWindow ActiveView = GetActiveView(); + if (ActiveView == PVR_WINDOW_RECORDINGS) + { + if (g_guiSettings.GetBool("filelists.ignorethewhensorting")) + AddSortMethod(SORT_METHOD_LABEL_IGNORE_THE, 551, LABEL_MASKS("%L", "%I", "%L", "")); // FileName, Size | Foldername, e + else + AddSortMethod(SORT_METHOD_LABEL, 551, LABEL_MASKS("%L", "%I", "%L", "")); // FileName, Size | Foldername, empty + AddSortMethod(SORT_METHOD_SIZE, 553, LABEL_MASKS("%L", "%I", "%L", "%I")); // FileName, Size | Foldername, Size + AddSortMethod(SORT_METHOD_DATE, 552, LABEL_MASKS("%L", "%J", "%L", "%J")); // FileName, Date | Foldername, Date + AddSortMethod(SORT_METHOD_FILE, 561, LABEL_MASKS("%L", "%I", "%L", "")); // Filename, Size | FolderName, empty + + // Sort recordings view by date as default + SetSortMethod(SORT_METHOD_DATE); + } + + LoadViewState(items.GetPath(), ActiveView == PVR_WINDOW_UNKNOWN ? WINDOW_PVR : WINDOW_PVR + 100 - ActiveView ); +} + +PVRWindow CGUIViewStatePVR::GetActiveView() +{ + PVRWindow returnWindow = PVR_WINDOW_UNKNOWN; + + int iActiveWindow = g_windowManager.GetActiveWindow(); + if (iActiveWindow == WINDOW_PVR) + { + CGUIWindowPVR *pWindow = (CGUIWindowPVR *) g_windowManager.GetWindow(WINDOW_PVR); + CGUIWindowPVRCommon *pActiveView = NULL; + if (pWindow && (pActiveView = pWindow->GetActiveView()) != NULL) + returnWindow = pActiveView->GetWindowId(); + } + + return returnWindow; +} + +void CGUIViewStatePVR::SaveViewState(void) +{ + PVRWindow ActiveView = GetActiveView(); + SaveViewToDb(m_items.GetPath(), ActiveView == PVR_WINDOW_UNKNOWN ? WINDOW_PVR : WINDOW_PVR + 100 - ActiveView, NULL); +} diff --git a/pool/shard007/C++/0094100_ping.cpp b/pool/shard007/C++/0094100_ping.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a12e49e20e6c312d68c3189d537b28c8c250b053 --- /dev/null +++ b/pool/shard007/C++/0094100_ping.cpp @@ -0,0 +1,162 @@ +// +// ping.cpp +// ~~~~~~~~ +// +// Copyright (c) 2003-2014 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include <asio.hpp> +#include <boost/bind.hpp> +#include <istream> +#include <iostream> +#include <ostream> + +#include "icmp_header.hpp" +#include "ipv4_header.hpp" + +using asio::ip::icmp; +using asio::deadline_timer; +namespace posix_time = boost::posix_time; + +class pinger +{ +public: + pinger(asio::io_service& io_service, const char* destination) + : resolver_(io_service), socket_(io_service, icmp::v4()), + timer_(io_service), sequence_number_(0), num_replies_(0) + { + icmp::resolver::query query(icmp::v4(), destination, ""); + destination_ = *resolver_.resolve(query); + + start_send(); + start_receive(); + } + +private: + void start_send() + { + std::string body("\"Hello!\" from Asio ping."); + + // Create an ICMP header for an echo request. + icmp_header echo_request; + echo_request.type(icmp_header::echo_request); + echo_request.code(0); + echo_request.identifier(get_identifier()); + echo_request.sequence_number(++sequence_number_); + compute_checksum(echo_request, body.begin(), body.end()); + + // Encode the request packet. + asio::streambuf request_buffer; + std::ostream os(&request_buffer); + os << echo_request << body; + + // Send the request. + time_sent_ = posix_time::microsec_clock::universal_time(); + socket_.send_to(request_buffer.data(), destination_); + + // Wait up to five seconds for a reply. + num_replies_ = 0; + timer_.expires_at(time_sent_ + posix_time::seconds(5)); + timer_.async_wait(boost::bind(&pinger::handle_timeout, this)); + } + + void handle_timeout() + { + if (num_replies_ == 0) + std::cout << "Request timed out" << std::endl; + + // Requests must be sent no less than one second apart. + timer_.expires_at(time_sent_ + posix_time::seconds(1)); + timer_.async_wait(boost::bind(&pinger::start_send, this)); + } + + void start_receive() + { + // Discard any data already in the buffer. + reply_buffer_.consume(reply_buffer_.size()); + + // Wait for a reply. We prepare the buffer to receive up to 64KB. + socket_.async_receive(reply_buffer_.prepare(65536), + boost::bind(&pinger::handle_receive, this, _2)); + } + + void handle_receive(std::size_t length) + { + // The actual number of bytes received is committed to the buffer so that we + // can extract it using a std::istream object. + reply_buffer_.commit(length); + + // Decode the reply packet. + std::istream is(&reply_buffer_); + ipv4_header ipv4_hdr; + icmp_header icmp_hdr; + is >> ipv4_hdr >> icmp_hdr; + + // We can receive all ICMP packets received by the host, so we need to + // filter out only the echo replies that match the our identifier and + // expected sequence number. + if (is && icmp_hdr.type() == icmp_header::echo_reply + && icmp_hdr.identifier() == get_identifier() + && icmp_hdr.sequence_number() == sequence_number_) + { + // If this is the first reply, interrupt the five second timeout. + if (num_replies_++ == 0) + timer_.cancel(); + + // Print out some information about the reply packet. + posix_time::ptime now = posix_time::microsec_clock::universal_time(); + std::cout << length - ipv4_hdr.header_length() + << " bytes from " << ipv4_hdr.source_address() + << ": icmp_seq=" << icmp_hdr.sequence_number() + << ", ttl=" << ipv4_hdr.time_to_live() + << ", time=" << (now - time_sent_).total_milliseconds() << " ms" + << std::endl; + } + + start_receive(); + } + + static unsigned short get_identifier() + { +#if defined(ASIO_WINDOWS) + return static_cast<unsigned short>(::GetCurrentProcessId()); +#else + return static_cast<unsigned short>(::getpid()); +#endif + } + + icmp::resolver resolver_; + icmp::endpoint destination_; + icmp::socket socket_; + deadline_timer timer_; + unsigned short sequence_number_; + posix_time::ptime time_sent_; + asio::streambuf reply_buffer_; + std::size_t num_replies_; +}; + +int main(int argc, char* argv[]) +{ + try + { + if (argc != 2) + { + std::cerr << "Usage: ping <host>" << std::endl; +#if !defined(ASIO_WINDOWS) + std::cerr << "(You may need to run this program as root.)" << std::endl; +#endif + return 1; + } + + asio::io_service io_service; + pinger p(io_service, argv[1]); + io_service.run(); + } + catch (std::exception& e) + { + std::cerr << "Exception: " << e.what() << std::endl; + } +} diff --git a/pool/shard007/C++/0094101_dijkstra.cpp b/pool/shard007/C++/0094101_dijkstra.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0d6f53f4c0054b477b4d69b5d0c052cb3b119248 --- /dev/null +++ b/pool/shard007/C++/0094101_dijkstra.cpp @@ -0,0 +1,68 @@ +#include <iostream> +#include <queue> + +using namespace std; + +#define MAX_VER 100 +#define MAX 100 +// +typedef struct vertex { + int num; + int data; +}Gnode; + +typedef struct graph { + int n; + int e; + Gnode ver[MAX_VER]; + int edge[MAX_VER][MAX_VER]; +}Graph; + + +int create_graph_for_dijkstra(Graph * G) +{ + assert(G != NULL); + memset(G, 0, sizeof(Graph)); + + int i = 0; + G->n = 4; + G->e = 5; + for(i = 0; i < G->n; i++) + { + G->ver[i].num = i; + G->ver[i].data = i + 1; + } + + G->edge[0][0] = 0; + G->edge[0][1] = MAX; + G->edge[0][2] = 3; + G->edge[0][3] = MAX; + G->edge[1][0] = 2; + G->edge[1][1] = 0; + G->edge[1][2] = MAX; + G->edge[1][3] = MAX; + G->edge[2][0] = MAX; + G->edge[2][1] = 7; + G->edge[2][2] = 0; + G->edge[2][3] = 1; + G->edge[3][0] = 6; + G->edge[3][1] = MAX; + G->edge[3][2] = MAX; + G->edge[3][3] = 0; +} + +struct node +{ + int id; //顶点id + int weight; //顶点到起始点的距离 + friend bool operator<(node a, node b) //实现最小堆所需 + { + return a.weight < b.weight; + } +}; + +void dijkstra(Graph *G, int s) //s :源节点的num +{ + for() +} + diff --git a/pool/shard007/C++/0094102_prerender_util.cc b/pool/shard007/C++/0094102_prerender_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..6519371a93fe9fa733c700402daeb15464d484bc --- /dev/null +++ b/pool/shard007/C++/0094102_prerender_util.cc @@ -0,0 +1,271 @@ +// Copyright (c) 2011 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 "chrome/browser/prerender/prerender_util.h" + +#include "base/logging.h" +#include "base/metrics/histogram.h" +#include "base/metrics/sparse_histogram.h" +#include "base/strings/string_util.h" +#include "content/public/browser/resource_request_info.h" +#include "net/http/http_response_headers.h" +#include "net/url_request/url_request.h" +#include "url/url_canon.h" +#include "url/url_parse.h" +#include "url/url_util.h" +#include "webkit/common/resource_type.h" + +namespace prerender { + +namespace { + +const char kModPagespeedHeader[] = "X-Mod-Pagespeed"; +const char kPageSpeedHeader[] = "X-Page-Speed"; +const char kPagespeedServerHistogram[] = + "Prerender.PagespeedHeader.ServerCounts"; +const char kPagespeedVersionHistogram[] = + "Prerender.PagespeedHeader.VersionCounts"; + +enum PagespeedHeaderServerType { + PAGESPEED_TOTAL_RESPONSES = 0, + PAGESPEED_MOD_PAGESPEED_SERVER = 1, + PAGESPEED_NGX_PAGESPEED_SERVER = 2, + PAGESPEED_PAGESPEED_SERVICE_SERVER = 3, + PAGESPEED_UNKNOWN_SERVER = 4, + PAGESPEED_SERVER_MAXIMUM = 5 +}; + +// Private function to parse the PageSpeed version number and encode it in +// buckets 2 through 99: if it is in the format a.b.c.d-e the bucket will be +// 2 + 2 * (max(c, 10) - 10) + (d > 1 ? 1 : 0); if it is not in this format +// we return zero. +int GetXModPagespeedBucketFromVersion(const std::string& version) { + int a, b, c, d, e; + int num_parsed = sscanf(version.c_str(), "%d.%d.%d.%d-%d", + &a, &b, &c, &d, &e); + int output = 0; + if (num_parsed == 5) { + output = 2; + if (c > 10) + output += 2 * (c - 10); + if (d > 1) + output++; + if (output < 2 || output > 99) + output = 0; + } + return output; +} + +// Private function to parse the X-Page-Speed header value and determine +// whether it is in the PageSpeed Service format, namely m_n_dc were m_n is +// a version number and dc is an encoded 2-character value. +bool IsPageSpeedServiceVersionNumber(const std::string& version) { + int a, b; + char c, d, e; // e is to detect EOL as we check that it /isn't/ converted. + int num_parsed = sscanf(version.c_str(), "%d_%d_%c%c%c", &a, &b, &c, &d, &e); + return (num_parsed == 4); +} + +enum PrerenderSchemeCancelReason { + PRERENDER_SCHEME_CANCEL_REASON_EXTERNAL_PROTOCOL, + PRERENDER_SCHEME_CANCEL_REASON_DATA, + PRERENDER_SCHEME_CANCEL_REASON_BLOB, + PRERENDER_SCHEME_CANCEL_REASON_FILE, + PRERENDER_SCHEME_CANCEL_REASON_FILESYSTEM, + PRERENDER_SCHEME_CANCEL_REASON_WEBSOCKET, + PRERENDER_SCHEME_CANCEL_REASON_FTP, + PRERENDER_SCHEME_CANCEL_REASON_CHROME, + PRERENDER_SCHEME_CANCEL_REASON_CHROME_EXTENSION, + PRERENDER_SCHEME_CANCEL_REASON_ABOUT, + PRERENDER_SCHEME_CANCEL_REASON_UNKNOWN, + PRERENDER_SCHEME_CANCEL_REASON_MAX, +}; + +void ReportPrerenderSchemeCancelReason(PrerenderSchemeCancelReason reason) { + UMA_HISTOGRAM_ENUMERATION( + "Prerender.SchemeCancelReason", reason, + PRERENDER_SCHEME_CANCEL_REASON_MAX); +} + +} // namespace + +const char kChromeNavigateExtraDataKey[] = "chrome_navigate"; + +bool MaybeGetQueryStringBasedAliasURL( + const GURL& url, GURL* alias_url) { + DCHECK(alias_url); + url::Parsed parsed; + url::ParseStandardURL(url.spec().c_str(), url.spec().length(), &parsed); + url::Component query = parsed.query; + url::Component key, value; + while (url::ExtractQueryKeyValue(url.spec().c_str(), &query, &key, &value)) { + if (key.len != 3 || strncmp(url.spec().c_str() + key.begin, "url", key.len)) + continue; + // We found a url= query string component. + if (value.len < 1) + continue; + url::RawCanonOutputW<1024> decoded_url; + url::DecodeURLEscapeSequences(url.spec().c_str() + value.begin, value.len, + &decoded_url); + GURL new_url(base::string16(decoded_url.data(), decoded_url.length())); + if (!new_url.is_empty() && new_url.is_valid()) { + *alias_url = new_url; + return true; + } + return false; + } + return false; +} + +uint8 GetQueryStringBasedExperiment(const GURL& url) { + url::Parsed parsed; + url::ParseStandardURL(url.spec().c_str(), url.spec().length(), &parsed); + url::Component query = parsed.query; + url::Component key, value; + while (url::ExtractQueryKeyValue(url.spec().c_str(), &query, &key, &value)) { + if (key.len != 3 || strncmp(url.spec().c_str() + key.begin, "lpe", key.len)) + continue; + + // We found a lpe= query string component. + if (value.len != 1) + continue; + uint8 exp = *(url.spec().c_str() + value.begin) - '0'; + if (exp < 1 || exp > 9) + continue; + return exp; + } + return kNoExperiment; +} + +bool IsGoogleDomain(const GURL& url) { + return StartsWithASCII(url.host(), std::string("www.google."), true); +} + +bool IsGoogleSearchResultURL(const GURL& url) { + if (!IsGoogleDomain(url)) + return false; + return (url.path().empty() || + StartsWithASCII(url.path(), std::string("/search"), true) || + (url.path() == "/") || + StartsWithASCII(url.path(), std::string("/webhp"), true)); +} + +bool IsNoSwapInExperiment(uint8 experiment_id) { + // Currently, experiments 5 and 6 fall in this category. + return experiment_id == 5 || experiment_id == 6; +} + +bool IsControlGroupExperiment(uint8 experiment_id) { + // Currently, experiments 7 and 8 fall in this category. + return experiment_id == 7 || experiment_id == 8; +} + +void GatherPagespeedData(const ResourceType::Type resource_type, + const GURL& request_url, + const net::HttpResponseHeaders* response_headers) { + if (resource_type != ResourceType::MAIN_FRAME || + !request_url.SchemeIsHTTPOrHTTPS()) + return; + + // bucket 0 counts every response seen. + UMA_HISTOGRAM_ENUMERATION(kPagespeedServerHistogram, + PAGESPEED_TOTAL_RESPONSES, + PAGESPEED_SERVER_MAXIMUM); + if (!response_headers) + return; + + void* iter = NULL; + std::string name; + std::string value; + while (response_headers->EnumerateHeaderLines(&iter, &name, &value)) { + if (name == kModPagespeedHeader) { + // Bucket 1 counts occurences of the X-Mod-Pagespeed header. + UMA_HISTOGRAM_ENUMERATION(kPagespeedServerHistogram, + PAGESPEED_MOD_PAGESPEED_SERVER, + PAGESPEED_SERVER_MAXIMUM); + if (!value.empty()) { + // If the header value is in the X-Mod-Pagespeed version number format + // then increment the appropriate bucket, otherwise increment bucket 1, + // which is the catch-all "unknown version number" bucket. + int bucket = GetXModPagespeedBucketFromVersion(value); + if (bucket > 0) { + UMA_HISTOGRAM_SPARSE_SLOWLY(kPagespeedVersionHistogram, bucket); + } else { + UMA_HISTOGRAM_SPARSE_SLOWLY(kPagespeedVersionHistogram, 1); + } + } + break; + } else if (name == kPageSpeedHeader) { + // X-Page-Speed header versions are either in the X-Mod-Pagespeed format, + // indicating an nginx installation, or they're in the PageSpeed Service + // format, indicating a PSS installation, or in some other format, + // indicating an unknown installation [possibly IISpeed]. + if (!value.empty()) { + int bucket = GetXModPagespeedBucketFromVersion(value); + if (bucket > 0) { + // Bucket 2 counts occurences of the X-Page-Speed header with a + // value in the X-Mod-Pagespeed version number format. We also + // count these responses in the version histogram. + UMA_HISTOGRAM_ENUMERATION(kPagespeedServerHistogram, + PAGESPEED_NGX_PAGESPEED_SERVER, + PAGESPEED_SERVER_MAXIMUM); + UMA_HISTOGRAM_SPARSE_SLOWLY(kPagespeedVersionHistogram, bucket); + } else if (IsPageSpeedServiceVersionNumber(value)) { + // Bucket 3 counts occurences of the X-Page-Speed header with a + // value in the PageSpeed Service version number format. + UMA_HISTOGRAM_ENUMERATION(kPagespeedServerHistogram, + PAGESPEED_PAGESPEED_SERVICE_SERVER, + PAGESPEED_SERVER_MAXIMUM); + } else { + // Bucket 4 counts occurences of all other values. + UMA_HISTOGRAM_ENUMERATION(kPagespeedServerHistogram, + PAGESPEED_UNKNOWN_SERVER, + PAGESPEED_SERVER_MAXIMUM); + } + } + break; + } + } +} + +void URLRequestResponseStarted(net::URLRequest* request) { + const content::ResourceRequestInfo* info = + content::ResourceRequestInfo::ForRequest(request); + GatherPagespeedData(info->GetResourceType(), + request->url(), + request->response_headers()); +} + +void ReportPrerenderExternalURL() { + ReportPrerenderSchemeCancelReason( + PRERENDER_SCHEME_CANCEL_REASON_EXTERNAL_PROTOCOL); +} + +void ReportUnsupportedPrerenderScheme(const GURL& url) { + if (url.SchemeIs("data")) { + ReportPrerenderSchemeCancelReason(PRERENDER_SCHEME_CANCEL_REASON_DATA); + } else if (url.SchemeIs("blob")) { + ReportPrerenderSchemeCancelReason(PRERENDER_SCHEME_CANCEL_REASON_BLOB); + } else if (url.SchemeIsFile()) { + ReportPrerenderSchemeCancelReason(PRERENDER_SCHEME_CANCEL_REASON_FILE); + } else if (url.SchemeIsFileSystem()) { + ReportPrerenderSchemeCancelReason( + PRERENDER_SCHEME_CANCEL_REASON_FILESYSTEM); + } else if (url.SchemeIs("ws") || url.SchemeIs("wss")) { + ReportPrerenderSchemeCancelReason(PRERENDER_SCHEME_CANCEL_REASON_WEBSOCKET); + } else if (url.SchemeIs("ftp")) { + ReportPrerenderSchemeCancelReason(PRERENDER_SCHEME_CANCEL_REASON_FTP); + } else if (url.SchemeIs("chrome")) { + ReportPrerenderSchemeCancelReason(PRERENDER_SCHEME_CANCEL_REASON_CHROME); + } else if (url.SchemeIs("chrome-extension")) { + ReportPrerenderSchemeCancelReason( + PRERENDER_SCHEME_CANCEL_REASON_CHROME_EXTENSION); + } else if (url.SchemeIs("about")) { + ReportPrerenderSchemeCancelReason(PRERENDER_SCHEME_CANCEL_REASON_ABOUT); + } else { + ReportPrerenderSchemeCancelReason(PRERENDER_SCHEME_CANCEL_REASON_UNKNOWN); + } +} + +} // namespace prerender diff --git a/pool/shard007/C++/0094103_epdownload.cpp b/pool/shard007/C++/0094103_epdownload.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9cf66eb00255a045ee0772894f46e45f3ebfbb10 --- /dev/null +++ b/pool/shard007/C++/0094103_epdownload.cpp @@ -0,0 +1,135 @@ +/* This file is part of DoIP. DoIP is free software: you + * can redistribute it and/or modify it under the terms of the GNU + * General Public License as published by the Free Software Foundation, + * either version 3 of the License, or (at your option) any later + * version. + * + * DoIP is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with DoIP. If not, see <http://www.gnu.org/licenses/>. */ + + #include "../include/epdownload.h" +#include "../include/ependpointdefinition.h" +using namespace tj::shared; +using namespace tj::ep; +using namespace tj::np; +using namespace tj::scout; + +/** EPDownloadedState **/ +EPDownloadedState::EPDownloadedState(strong<Service> service, const String& path): + Download(NetworkAddress(service->GetHostName()), path, service->GetPort()), + _service(service) { +} + +EPDownloadedState::~EPDownloadedState() { + Stop(); +} + +strong<Service> EPDownloadedState::GetService() { + return _service; +} + +void EPDownloadedState::GetState(ValueMap& vals) { + ThreadLock lock(&_lock); + vals = _state; +} + +Any EPDownloadedState::GetValue(const String& key) { + EPState::ValueMap::const_iterator it = _state.find(key); + if(it!=_state.end()) { + return it->second; + } + return Any(); +} + +void EPDownloadedState::LoadState(TiXmlElement* root) { + ThreadLock lock(&_lock); + + TiXmlElement* var = root->FirstChildElement("var"); + while(var!=0) { + String key = LoadAttributeSmall(var, "key", String(L"")); + String val = LoadAttributeSmall(var, "value", String(L"???")); + Any value; + value.Load(var); + _state[key] = value; + var = var->NextSiblingElement("var"); + } +} + +void EPDownloadedState::OnDownloadComplete(ref<DataWriter> cw) { + Download::OnDownloadComplete(cw); + if(cw) { + TiXmlDocument doc; + std::string data((const char*)cw->GetBuffer(), 0, (unsigned int)cw->GetSize()); + doc.Parse(data.c_str()); + TiXmlElement* root = doc.FirstChildElement("state"); + if(root!=0) { + LoadState(root); + EventDownloaded.Fire(this, EPStateDownloadNotification()); + return; + } + else { + Log::Write(L"TJEP/EPDownloadedState", L"No root element in this state file! (path="+_path+L")"); + return; + } + } + else { + Log::Write(L"TJEP/EPDownloadedState", L"No data, download failed!"); + } + EventDownloaded.Fire(this, EPStateDownloadNotification()); +} + + +/** EPDownloadedDefinition **/ +EPDownloadedDefinition::EPDownloadNotification::EPDownloadNotification(ref<EPEndpoint> t, strong<Service> s): endpoint(t), service(s) { +} + +EPDownloadedDefinition::EPDownloadedDefinition(strong<Service> service, const tj::shared::String& path): + Download(NetworkAddress(service->GetHostName()), path, service->GetPort()), + _service(service) { +} + +strong<Service> EPDownloadedDefinition::GetService() { + return _service; +} + +EPDownloadedDefinition::~EPDownloadedDefinition() { + Stop(); +} + +ref<EPEndpoint> EPDownloadedDefinition::GetEndpoint() { + return _createdEndpoint; +} + +void EPDownloadedDefinition::OnCreated() { + Download::OnCreated(); +} + +void EPDownloadedDefinition::OnDownloadComplete(ref<DataWriter> cw) { + Download::OnDownloadComplete(cw); + if(cw) { + TiXmlDocument doc; + std::string data((const char*)cw->GetBuffer(), 0, (unsigned int)cw->GetSize()); + doc.Parse(data.c_str()); + TiXmlElement* root = doc.FirstChildElement("endpoint"); + if(root!=0) { + ref<EPEndpointDefinition> epd = GC::Hold(new EPEndpointDefinition()); + epd->Load(root); + _createdEndpoint = epd; + EventDownloaded.Fire(this, EPDownloadNotification(_createdEndpoint, _service)); + return; + } + else { + Log::Write(L"TJEP/EPDownloadedState", L"No root element in this definition file! (path="+_path+L"); ignoring!"); + } + } + else { + Log::Write(L"TJEP/EPDownloadedState", L"No data, download failed!"); + } + + EventDownloaded.Fire(this, EPDownloadNotification(null, _service)); +} diff --git a/pool/shard007/C++/0094107_SampleAARects.cpp b/pool/shard007/C++/0094107_SampleAARects.cpp new file mode 100644 index 0000000000000000000000000000000000000000..942242b02e77d17a7ab71006adb9ffeb97e8be03 --- /dev/null +++ b/pool/shard007/C++/0094107_SampleAARects.cpp @@ -0,0 +1,192 @@ +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ +#include "SampleCode.h" +#include "SkView.h" +#include "SkCanvas.h" +#include "SkPaint.h" +#include "SkShader.h" + +static SkBitmap createBitmap(int n) { + SkBitmap bitmap; + bitmap.allocN32Pixels(n, n); + bitmap.eraseColor(SK_ColorGREEN); + + SkCanvas canvas(bitmap); + SkRect r; + r.set(0, 0, SkIntToScalar(n), SkIntToScalar(n)); + SkPaint paint; + paint.setAntiAlias(true); + + paint.setColor(SK_ColorRED); + canvas.drawOval(r, paint); + paint.setColor(SK_ColorBLUE); + paint.setStrokeWidth(SkIntToScalar(n)/15); + paint.setStyle(SkPaint::kStroke_Style); + canvas.drawLine(0, 0, r.fRight, r.fBottom, paint); + canvas.drawLine(0, r.fBottom, r.fRight, 0, paint); + + return bitmap; +} + +class AARectView : public SampleView { + SkBitmap fBitmap; + enum { + N = 64 + }; +public: + AARectView() { + fBitmap = createBitmap(N); + + fWidth = N; + } + +protected: + // overrides from SkEventSink + virtual bool onQuery(SkEvent* evt) { + if (SampleCode::TitleQ(*evt)) { + SampleCode::TitleR(evt, "AA Rects"); + return true; + } + return this->INHERITED::onQuery(evt); + } + + virtual void onDrawContent(SkCanvas* canvas) { + canvas->translate(SkIntToScalar(10), SkIntToScalar(10)); + + SkPaint bluePaint; + bluePaint.setARGB(0xff, 0x0, 0x0, 0xff); + SkPaint bmpPaint; + bmpPaint.setShader(SkShader::MakeBitmapShader(fBitmap, SkShader::kRepeat_TileMode, + SkShader::kRepeat_TileMode)); + bluePaint.setStrokeWidth(3); + bmpPaint.setStrokeWidth(3); + + SkPaint paints[] = { bluePaint, bmpPaint }; + + SkRect rect; + + SkScalar dx = SkIntToScalar(80); + SkScalar dy = SkIntToScalar(100); + SkMatrix matrix; + for (size_t p = 0; p < SK_ARRAY_COUNT(paints); ++p) { + for (int stroke = 0; stroke < 2; ++stroke) { + paints[p].setStyle(stroke ? SkPaint::kStroke_Style : SkPaint::kFill_Style); + for (int a = 0; a < 3; ++ a) { + paints[p].setAntiAlias(a > 0); + paints[p].setAlpha(a > 1 ? 0x80 : 0xff); + + canvas->save(); + rect = SkRect::MakeLTRB(0.f, + 0.f, + 40.f, + 40.f); + canvas->drawRect(rect, paints[p]); + canvas->translate(dx, 0); + + rect = SkRect::MakeLTRB(0.5f, + 0.5f, + 40.5f, + 40.5f); + canvas->drawRect(rect, paints[p]); + canvas->translate(dx, 0); + + rect = SkRect::MakeLTRB(0.5f, + 0.5f, + 40.f, + 40.f); + canvas->drawRect(rect, paints[p]); + canvas->translate(dx, 0); + + rect = SkRect::MakeLTRB(0.75f, + 0.75f, + 40.75f, + 40.75f); + canvas->drawRect(rect, paints[p]); + canvas->translate(dx, 0); + + canvas->save(); + canvas->translate(.33f, .67f); + rect = SkRect::MakeLTRB(0.0f, + 0.0f, + 40.0f, + 40.0f); + canvas->drawRect(rect, paints[p]); + canvas->restore(); + canvas->translate(dx, 0); + + canvas->save(); + matrix.setRotate(45.f); + canvas->concat(matrix); + canvas->translate(20.0f / sqrtf(2.f), + 20.0f / sqrtf(2.f)); + rect = SkRect::MakeLTRB(-20.0f, + -20.0f, + 20.0f, + 20.0f); + canvas->drawRect(rect, paints[p]); + canvas->restore(); + canvas->translate(dx, 0); + + canvas->save(); + canvas->rotate(90.f); + rect = SkRect::MakeLTRB(0.0f, + 0.0f, + 40.0f, + -40.0f); + canvas->drawRect(rect, paints[p]); + canvas->restore(); + canvas->translate(dx, 0); + + canvas->save(); + canvas->rotate(90.f); + rect = SkRect::MakeLTRB(0.5f, + 0.5f, + 40.5f, + -40.5f); + canvas->drawRect(rect, paints[p]); + canvas->restore(); + canvas->translate(dx, 0); + + canvas->save(); + matrix.setScale(-1.f, -1.f); + canvas->concat(matrix); + rect = SkRect::MakeLTRB(0.5f, + 0.5f, + -40.5f, + -40.5f); + canvas->drawRect(rect, paints[p]); + canvas->restore(); + canvas->translate(dx, 0); + + canvas->save(); + matrix.setScale(2.1f, 4.1f); + canvas->concat(matrix); + rect = SkRect::MakeLTRB(0.1f, + 0.1f, + 19.1f, + 9.1f); + canvas->drawRect(rect, paints[p]); + canvas->restore(); + canvas->translate(dx, 0); + + canvas->restore(); + canvas->translate(0, dy); + } + } + } + } + +private: + int fWidth; + + typedef SampleView INHERITED; +}; + +////////////////////////////////////////////////////////////////////////////// + +static SkView* MyFactory() { return new AARectView; } +static SkViewRegister reg(MyFactory); diff --git a/pool/shard007/C++/0094111_variant_compare.cpp b/pool/shard007/C++/0094111_variant_compare.cpp new file mode 100644 index 0000000000000000000000000000000000000000..60eeebfce6800afc9d3020598729a32af9ba618e --- /dev/null +++ b/pool/shard007/C++/0094111_variant_compare.cpp @@ -0,0 +1,109 @@ +/************************************************************************************ +* * +* Copyright (c) 2014 - 2018 Axel Menzel <info@rttr.org> * +* * +* This file is part of RTTR (Run Time Type Reflection) * +* License: MIT License * +* * +* Permission is hereby granted, free of charge, to any person obtaining * +* a copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * +* SOFTWARE. * +* * +*************************************************************************************/ + +#include "rttr/detail/variant/variant_compare.h" +#include "rttr/type.h" +#include "rttr/variant.h" + +#include <cmath> +#include <algorithm> + +namespace rttr +{ +namespace detail +{ + +///////////////////////////////////////////////////////////////////////////////////////// + +static RTTR_INLINE bool is_floating_point(const type& type) +{ + return (type == type::get<float>() || type == type::get<double>()); +} + +///////////////////////////////////////////////////////////////////////////////////////// + +static RTTR_INLINE bool almost_equal(double p1, double p2) +{ + return (std::abs(p1 - p2) * 1000000000000. <= std::min(std::abs(p1), std::abs(p2))); +} + +///////////////////////////////////////////////////////////////////////////////////////// + +bool variant_compare_equal(const variant& lhs, const type& lhs_type, const variant& rhs, const type& rhs_type, bool& ok) +{ + ok = true; + if (is_floating_point(lhs_type) || is_floating_point(rhs_type)) + { + return almost_equal(lhs.to_double(), rhs.to_double()); + } + else + { + return (lhs.to_int64() == rhs.to_int64()); + } +} + +///////////////////////////////////////////////////////////////////////////////////////// + +bool variant_compare_less(const variant& lhs, const type& lhs_type, const variant& rhs, const type& rhs_type, bool& ok) +{ + ok = true; + if (lhs_type.is_arithmetic() && rhs_type.is_arithmetic()) + { + if (is_floating_point(lhs_type) || is_floating_point(rhs_type)) + return (lhs.to_double() < rhs.to_double()); + else + return (lhs.to_int64() < rhs.to_int64()); + } + else + { + variant lhs_tmp; + if (lhs.convert(rhs_type, lhs_tmp)) + return lhs_tmp.compare_less(rhs, ok); + + if (!lhs.is_nullptr() && rhs.is_nullptr()) + return false; + + // as last try, do a string conversion + bool ok1 = false; + bool ok2 = false; + auto ret = (lhs.to_string(&ok1) < rhs.to_string(&ok2)); + if (ok1 && ok2) + { + return ret; + } + else + { + ok = false; + return false; + } + } +} + +///////////////////////////////////////////////////////////////////////////////////////// + +} // end namespace detail +} // end namespace rttr diff --git a/pool/shard007/C++/0094124_Variations01.cpp b/pool/shard007/C++/0094124_Variations01.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d3e4c871e93bd2e6fcf5b8965a3315ea0d19c2c --- /dev/null +++ b/pool/shard007/C++/0094124_Variations01.cpp @@ -0,0 +1,52 @@ +#include <iostream> + +//Can hold variations up to 2^15 +char result[32768][100] = { 0 }; +int row = 0; + +//Added additional parameter index to recieve the result in +//lexicographical order +void Gen01(int index, int lenght, char* input) +{ + if (index == lenght) + { + strcpy(result[row++], input); + return; + } + + if (input[index] != '*') + { + Gen01(index + 1, lenght, input); + } + else + { + for (char i = '0'; i < '2'; i++) + { + input[index] = i; + Gen01(index + 1, lenght, input); + } + + input[index] = '*'; + } +} + +void Print() +{ + for (size_t i = 0; i < row; i++) + { + printf("%s\n", result[i]); + } +} + +int main() +{ + char input[128]; + std::cin.getline(input, 128); + int lenght = strlen(input); + + Gen01(0, lenght, input); + + Print(); + + return 0; +} \ No newline at end of file diff --git a/pool/shard007/C++/0094126_B.LuckyMask.cpp b/pool/shard007/C++/0094126_B.LuckyMask.cpp new file mode 100644 index 0000000000000000000000000000000000000000..10bbca72fa0b5c96d9b8567a51b47238edde590f --- /dev/null +++ b/pool/shard007/C++/0094126_B.LuckyMask.cpp @@ -0,0 +1,78 @@ +#include<bits/stdc++.h> +using namespace std; +bool mayor (string a,string b) +{ + if(b.size() != a.size() ) + return a.size() > b.size(); + for(int i=0;i<a.size();i++) + { + if(b[i]>a[i]) + return 0; + else if (b[i]<a[i]) + return 1; + } + return 0; +} +bool verificar1(string a , string b) +{ + for(int i=0;i<a.size();i++) + if(a[i]>b[i]) + return 0; + return 1; +} +string mask(int x) +{ + string ans=""; + while(x>0) + { + int last=x%10; + x/=10; + if(last==7 || last==4) + ans= (char)(last+'0') + ans; + } + //cout<<ans<<endl; + return ans; +} +int main() +{ + string a,b; + cin>>a>>b; + string ans; + if(mayor(b, a)) + cout<<b<<endl; + else + { + if(a == b ) + { + string ans=b; + bool f=0; + for(int i=b.size()-1;i>=0;i--) + { + if(b[i]==4) + { + f=1; + ans[i]=7; + break; + } + } + if(f) + cout<<ans<<endl; + else + cout<<"1"+ans<<endl; + } + else + { + int a1=atoi(a.c_str()), aux; + for(int i=1;i<1e5+500;i++) + { + aux=a1+i; + string Mask=mask(aux); + //cout<<aux<<" : "<<Mask<<endl; + if(Mask==b) + break; + } + cout<<aux<<endl; + } + } +} + diff --git a/pool/shard007/C++/0094129_benchmark.cpp b/pool/shard007/C++/0094129_benchmark.cpp new file mode 100644 index 0000000000000000000000000000000000000000..251a89d78387169a0b45a566496984b0c5416126 --- /dev/null +++ b/pool/shard007/C++/0094129_benchmark.cpp @@ -0,0 +1,31 @@ +#include <iostream> +#include <parser.h> +#include <exception.h> + +using namespace std; +using namespace lexers; +using namespace parser; +using namespace exception; + +int main() { + try { + auto s = make_shared<Scope>(); + lexers::Lexer lex; + lex.appendExp("(load \"setup.scm\")").appendExp("(load \"benchmark.scm\")"); + lex.appendExp("#(length (l-painter default))"); + lex.appendExp( + "(length ((beside (below painter (flip-vert painter)) (below painter (flip-vert painter))) default))"); + auto ast = parseAllExpr(lex); + auto res = ast->eval(s, ast); + auto numPtr = std::dynamic_pointer_cast<NumberAST>(res); + if (numPtr) { + cout << numPtr->getValue() << endl; + } else { + cout << "ERROR" << endl; + } + } catch (RuntimeError &e) { + CLOG(DEBUG, "exception") << e.what(); + throw; + } + return 0; +} diff --git a/pool/shard007/C++/0094130_KeyboardHook.cpp b/pool/shard007/C++/0094130_KeyboardHook.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ae4366f93bf57d0161fbeeaf5056721a3e3eefc9 --- /dev/null +++ b/pool/shard007/C++/0094130_KeyboardHook.cpp @@ -0,0 +1,55 @@ +/////////////////////////////////////////////////////////////// +// +// KeyboardHook.cpp +// +// Created: rhare - 21/07/2005 +// Copyright (c) 2005 Ralph Hare (ralph.hare@ysgyfarnog.co.uk) +// All rights reserved. +// +// The code and information is provided "as-is" without +// warranty of any kind, either expressed or implied. +// +/////////////////////////////////////////////////////////////// + +#include "stdafx.h" +#include "KeyboardHook.h" + +KeyboardHook::KeyboardHook() : + WindowHook(), + m_pObserver( NULL ) +{ +} + +KeyboardHook::~KeyboardHook() +{ + Shutdown(); +} + +void KeyboardHook::Initialise( Observer *pObserver ) +{ + m_pObserver = pObserver; + SetWindowsHookEx( WH_KEYBOARD_LL, 0 ); +} + +void KeyboardHook::Shutdown() +{ + UnhookWindowsHookEx(); +} + +LRESULT KeyboardHook::OnHook( int nCode, WPARAM wParam, LPARAM lParam ) +{ + if( ( nCode == HC_ACTION ) && ( m_pObserver != NULL ) ) + { + LRESULT ret = m_pObserver->OnKeyHook( + static_cast< UINT >( wParam ), + reinterpret_cast< KBDLLHOOKSTRUCT * >( lParam ) + ); + + if( ret > 0 ) + { + return ret; + } + } + + return WindowHook::OnHook( nCode, wParam, lParam ); +} \ No newline at end of file diff --git a/pool/shard007/C++/0094133_countdescriptorstest.cpp b/pool/shard007/C++/0094133_countdescriptorstest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c5716af16355cbef20aff54ba70767c087e5d33d --- /dev/null +++ b/pool/shard007/C++/0094133_countdescriptorstest.cpp @@ -0,0 +1,86 @@ +/****************************************************************************** +** +** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com> +** All rights reserved. +** +** This file is a part of the chemkit project. For more information +** see <http://www.chemkit.org>. +** +** 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 chemkit project nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +** +******************************************************************************/ + +#include "countdescriptorstest.h" + +#include <boost/range/algorithm.hpp> + +#include <chemkit/molecule.h> +#include <chemkit/moleculardescriptor.h> + +void CountDescriptorsTest::initTestCase() +{ + // verify that the countdescriptors plugin registered itself correctly + QVERIFY(boost::count(chemkit::MolecularDescriptor::descriptors(), "atom-count") == 1); + QVERIFY(boost::count(chemkit::MolecularDescriptor::descriptors(), "heavy-atom-count") == 1); + QVERIFY(boost::count(chemkit::MolecularDescriptor::descriptors(), "bond-count") == 1); + QVERIFY(boost::count(chemkit::MolecularDescriptor::descriptors(), "ring-count") == 1); +} + +void CountDescriptorsTest::test_data() +{ + QTest::addColumn<QString>("smilesString"); + QTest::addColumn<QString>("formulaString"); + QTest::addColumn<int>("atomCount"); + QTest::addColumn<int>("heavyAtomCount"); + QTest::addColumn<int>("bondCount"); + QTest::addColumn<int>("ringCount"); + + QTest::newRow("methane") << "C" << "CH4" << 5 << 1 << 4 << 0; + QTest::newRow("propane") << "CCC" << "C3H8" << 11 << 3 << 10 << 0; + QTest::newRow("benzene") << "c1ccccc1" << "C6H6" << 12 << 6 << 12 << 1; +} + +void CountDescriptorsTest::test() +{ + QFETCH(QString, smilesString); + QFETCH(QString, formulaString); + QFETCH(int, atomCount); + QFETCH(int, heavyAtomCount); + QFETCH(int, bondCount); + QFETCH(int, ringCount); + + QByteArray smiles = smilesString.toAscii(); + QByteArray formula = formulaString.toAscii(); + + chemkit::Molecule molecule(smiles.constData(), "smiles"); + QCOMPARE(molecule.formula().c_str(), formula.constData()); + QCOMPARE(molecule.descriptor("atom-count").toInt(), atomCount); + QCOMPARE(molecule.descriptor("heavy-atom-count").toInt(), heavyAtomCount); + QCOMPARE(molecule.descriptor("bond-count").toInt(), bondCount); + QCOMPARE(molecule.descriptor("ring-count").toInt(), ringCount); +} + +QTEST_APPLESS_MAIN(CountDescriptorsTest) diff --git a/pool/shard007/C++/0094134_PatchFilterKey.cpp b/pool/shard007/C++/0094134_PatchFilterKey.cpp new file mode 100644 index 0000000000000000000000000000000000000000..700b098655ba12d3e744cf147d202af57fb2b5fc --- /dev/null +++ b/pool/shard007/C++/0094134_PatchFilterKey.cpp @@ -0,0 +1,129 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include <aws/ssm/model/PatchFilterKey.h> +#include <aws/core/utils/HashingUtils.h> +#include <aws/core/Globals.h> +#include <aws/core/utils/EnumParseOverflowContainer.h> + +using namespace Aws::Utils; + + +namespace Aws +{ + namespace SSM + { + namespace Model + { + namespace PatchFilterKeyMapper + { + + static const int PATCH_SET_HASH = HashingUtils::HashString("PATCH_SET"); + static const int PRODUCT_HASH = HashingUtils::HashString("PRODUCT"); + static const int PRODUCT_FAMILY_HASH = HashingUtils::HashString("PRODUCT_FAMILY"); + static const int CLASSIFICATION_HASH = HashingUtils::HashString("CLASSIFICATION"); + static const int MSRC_SEVERITY_HASH = HashingUtils::HashString("MSRC_SEVERITY"); + static const int PATCH_ID_HASH = HashingUtils::HashString("PATCH_ID"); + static const int SECTION_HASH = HashingUtils::HashString("SECTION"); + static const int PRIORITY_HASH = HashingUtils::HashString("PRIORITY"); + static const int SEVERITY_HASH = HashingUtils::HashString("SEVERITY"); + + + PatchFilterKey GetPatchFilterKeyForName(const Aws::String& name) + { + int hashCode = HashingUtils::HashString(name.c_str()); + if (hashCode == PATCH_SET_HASH) + { + return PatchFilterKey::PATCH_SET; + } + else if (hashCode == PRODUCT_HASH) + { + return PatchFilterKey::PRODUCT; + } + else if (hashCode == PRODUCT_FAMILY_HASH) + { + return PatchFilterKey::PRODUCT_FAMILY; + } + else if (hashCode == CLASSIFICATION_HASH) + { + return PatchFilterKey::CLASSIFICATION; + } + else if (hashCode == MSRC_SEVERITY_HASH) + { + return PatchFilterKey::MSRC_SEVERITY; + } + else if (hashCode == PATCH_ID_HASH) + { + return PatchFilterKey::PATCH_ID; + } + else if (hashCode == SECTION_HASH) + { + return PatchFilterKey::SECTION; + } + else if (hashCode == PRIORITY_HASH) + { + return PatchFilterKey::PRIORITY; + } + else if (hashCode == SEVERITY_HASH) + { + return PatchFilterKey::SEVERITY; + } + EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); + if(overflowContainer) + { + overflowContainer->StoreOverflow(hashCode, name); + return static_cast<PatchFilterKey>(hashCode); + } + + return PatchFilterKey::NOT_SET; + } + + Aws::String GetNameForPatchFilterKey(PatchFilterKey enumValue) + { + switch(enumValue) + { + case PatchFilterKey::PATCH_SET: + return "PATCH_SET"; + case PatchFilterKey::PRODUCT: + return "PRODUCT"; + case PatchFilterKey::PRODUCT_FAMILY: + return "PRODUCT_FAMILY"; + case PatchFilterKey::CLASSIFICATION: + return "CLASSIFICATION"; + case PatchFilterKey::MSRC_SEVERITY: + return "MSRC_SEVERITY"; + case PatchFilterKey::PATCH_ID: + return "PATCH_ID"; + case PatchFilterKey::SECTION: + return "SECTION"; + case PatchFilterKey::PRIORITY: + return "PRIORITY"; + case PatchFilterKey::SEVERITY: + return "SEVERITY"; + default: + EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); + if(overflowContainer) + { + return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); + } + + return {}; + } + } + + } // namespace PatchFilterKeyMapper + } // namespace Model + } // namespace SSM +} // namespace Aws diff --git a/pool/shard007/C++/0094135_desktopchain.cpp b/pool/shard007/C++/0094135_desktopchain.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8bc67a706b7f26ab5051905f272c1f31eb9980c8 --- /dev/null +++ b/pool/shard007/C++/0094135_desktopchain.cpp @@ -0,0 +1,142 @@ +/******************************************************************** + KWin - the KDE window manager + This file is part of the KDE project. + +Copyright (C) 2012 Martin Gräßlin <mgraesslin@kde.org> + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see <http://www.gnu.org/licenses/>. +*********************************************************************/ +#include "desktopchain.h" + +namespace KWin +{ +namespace TabBox +{ + +DesktopChain::DesktopChain(uint initialSize) + : m_chain(initialSize) +{ + init(); +} + +void DesktopChain::init() +{ + for (int i = 0; i < m_chain.size(); ++i) { + m_chain[i] = i + 1; + } +} + +uint DesktopChain::next(uint indexDesktop) const +{ + const int i = m_chain.indexOf(indexDesktop); + if (i >= 0 && i + 1 < m_chain.size()) { + return m_chain[i+1]; + } else if (m_chain.size() > 0) { + return m_chain[0]; + } else { + return 1; + } +} + +void DesktopChain::resize(uint previousSize, uint newSize) +{ + Q_ASSERT(previousSize == m_chain.size()); + m_chain.resize(newSize); + + if (newSize >= previousSize) { + // We do not destroy the chain in case new desktops are added + for (uint i = previousSize; i < newSize; ++i) { + m_chain[i] = i + 1; + } + } else { + // But when desktops are removed, we may have to modify the chain a bit, + // otherwise invalid desktops may show up. + for (int i = 0; i < m_chain.size(); ++i) { + m_chain[i] = qMin(m_chain[i], newSize); + } + } +} + +void DesktopChain::add(uint desktop) +{ + if (m_chain.isEmpty() || int(desktop) > m_chain.count()) { + return; + } + int index = m_chain.indexOf(desktop); + if (index == -1) { + // not found - shift all elements by one position + index = m_chain.size() - 1; + } + for (int i = index; i > 0; --i) { + m_chain[i] = m_chain[i-1]; + } + m_chain[0] = desktop; +} + +DesktopChainManager::DesktopChainManager(QObject *parent) + : QObject(parent) + , m_maxChainSize(0) +{ + m_currentChain = m_chains.insert(QString(), DesktopChain()); +} + +DesktopChainManager::~DesktopChainManager() +{ +} + +uint DesktopChainManager::next(uint indexDesktop) const +{ + return m_currentChain.value().next(indexDesktop); +} + +void DesktopChainManager::resize(uint previousSize, uint newSize) +{ + m_maxChainSize = newSize; + for (DesktopChains::iterator it = m_chains.begin(); it != m_chains.end(); ++it) { + it.value().resize(previousSize, newSize); + } +} + +void DesktopChainManager::addDesktop(uint previousDesktop, uint currentDesktop) +{ + Q_UNUSED(previousDesktop) + m_currentChain.value().add(currentDesktop); +} + +void DesktopChainManager::useChain(const QString &identifier) +{ + if (m_currentChain.key().isNull()) { + createFirstChain(identifier); + } else { + m_currentChain = m_chains.find(identifier); + if (m_currentChain == m_chains.end()) { + m_currentChain = addNewChain(identifier); + } + } +} + +void DesktopChainManager::createFirstChain(const QString &identifier) +{ + DesktopChain value(m_currentChain.value()); + m_chains.erase(m_currentChain); + m_currentChain = m_chains.insert(identifier, value); +} + +QHash< QString, DesktopChain >::Iterator DesktopChainManager::addNewChain(const QString &identifier) +{ + return m_chains.insert(identifier, DesktopChain(m_maxChainSize)); +} + +} // namespace TabBox +} // namespace KWin diff --git a/pool/shard007/C++/0094137_ca.cpp b/pool/shard007/C++/0094137_ca.cpp new file mode 100644 index 0000000000000000000000000000000000000000..41dd409d5fd2ae6e7593e88fd809f50154b94317 --- /dev/null +++ b/pool/shard007/C++/0094137_ca.cpp @@ -0,0 +1,74 @@ +/* + Implement the functionality of a simple CA: read in a CA certificate, + the associated private key, and a PKCS #10 certificate request. Sign the + request and print out the new certificate. + + File names are hardcoded for simplicity. + cacert.pem: The CA's certificate (perhaps created by self_sig) + caprivate.pem: The CA's private key + req.pem: The user's PKCS #10 certificate request + + Written by Jack Lloyd, May 19, 2003 + + This file is in the public domain. +*/ + +#include <botan/botan.h> +#include <botan/x509_ca.h> +#include <botan/util.h> +using namespace Botan; + +#include <iostream> +#include <memory> + +int main(int argc, char* argv[]) + { + if(argc != 5) + { + std::cout << "Usage: " << argv[0] << " <passphrase> " + << "<ca cert> <ca key> <pkcs10>" << std::endl; + return 1; + } + + Botan::LibraryInitializer init; + + try + { + const std::string arg_passphrase = argv[1]; + const std::string arg_ca_cert = argv[2]; + const std::string arg_ca_key = argv[3]; + const std::string arg_req_file = argv[4]; + + AutoSeeded_RNG rng; + + X509_Certificate ca_cert(arg_ca_cert); + + std::auto_ptr<PKCS8_PrivateKey> privkey( + PKCS8::load_key(arg_ca_key, rng, arg_passphrase) + ); + + X509_CA ca(ca_cert, *privkey); + + // got a request + PKCS10_Request req(arg_req_file); + + // you would insert checks here, and perhaps modify the request + // (this example should be extended to show how) + + // now sign the request + X509_Time start_time(system_time()); + X509_Time end_time(system_time() + 365 * 60 * 60 * 24); + + X509_Certificate new_cert = ca.sign_request(req, rng, + start_time, end_time); + + // send the new cert back to the requestor + std::cout << new_cert.PEM_encode(); + } + catch(std::exception& e) + { + std::cout << e.what() << std::endl; + return 1; + } + return 0; + } diff --git a/pool/shard007/C++/0094138_boss_vectus.cpp b/pool/shard007/C++/0094138_boss_vectus.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb0535bd0b3800ff7e0022a66c9c21c721a66ad2 --- /dev/null +++ b/pool/shard007/C++/0094138_boss_vectus.cpp @@ -0,0 +1,105 @@ +/* Copyright (C) 2006 - 2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* ScriptData +SDName: Boss_Vectus +SD%Complete: 100 +SDComment: +SDCategory: Scholomance +EndScriptData */ + +#include "ScriptedPch.h" + +enum eEnums +{ + EMOTE_GENERIC_FRENZY_KILL = -1000001, + + SPELL_FLAMESTRIKE = 18399, + SPELL_BLAST_WAVE = 16046, + SPELL_FIRESHIELD = 19626, + SPELL_FRENZY = 8269 //28371, +}; + +struct boss_vectusAI : public ScriptedAI +{ + boss_vectusAI(Creature *c) : ScriptedAI(c) {} + + uint32 m_uiFireShield_Timer; + uint32 m_uiBlastWave_Timer; + uint32 m_uiFrenzy_Timer; + + void Reset() + { + m_uiFireShield_Timer = 2000; + m_uiBlastWave_Timer = 14000; + m_uiFrenzy_Timer = 0; + } + + void UpdateAI(const uint32 uiDiff) + { + if (!UpdateVictim()) + return; + + //FireShield_Timer + if (m_uiFireShield_Timer <= uiDiff) + { + DoCast(m_creature, SPELL_FIRESHIELD); + m_uiFireShield_Timer = 90000; + } + else + m_uiFireShield_Timer -= uiDiff; + + //BlastWave_Timer + if (m_uiBlastWave_Timer <= uiDiff) + { + DoCast(m_creature->getVictim(), SPELL_BLAST_WAVE); + m_uiBlastWave_Timer = 12000; + } + else + m_uiBlastWave_Timer -= uiDiff; + + //Frenzy_Timer + if (m_creature->GetHealth()*100 / m_creature->GetMaxHealth() < 25) + { + if (m_uiFrenzy_Timer <= uiDiff) + { + DoCast(m_creature, SPELL_FRENZY); + DoScriptText(EMOTE_GENERIC_FRENZY_KILL, m_creature); + + m_uiFrenzy_Timer = 24000; + } + else + m_uiFrenzy_Timer -= uiDiff; + } + + DoMeleeAttackIfReady(); + } +}; + +CreatureAI* GetAI_boss_vectus(Creature* pCreature) +{ + return new boss_vectusAI (pCreature); +} + +void AddSC_boss_vectus() +{ + Script *newscript; + newscript = new Script; + newscript->Name = "boss_vectus"; + newscript->GetAI = &GetAI_boss_vectus; + newscript->RegisterSelf(); +} + diff --git a/pool/shard007/C++/0094139_miscmatrices.cpp b/pool/shard007/C++/0094139_miscmatrices.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b14bca61cac60839645eb69281f582d0e6f7251d --- /dev/null +++ b/pool/shard007/C++/0094139_miscmatrices.cpp @@ -0,0 +1,63 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com> +// +// Eigen is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3 of the License, or (at your option) any later version. +// +// Alternatively, you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of +// the License, or (at your option) any later version. +// +// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License and a copy of the GNU General Public License along with +// Eigen. If not, see <http://www.gnu.org/licenses/>. + +#include "main.h" + +template<typename MatrixType> void miscMatrices(const MatrixType& m) +{ + /* this test covers the following files: + DiagonalMatrix.h Ones.h + */ + typedef typename MatrixType::Index Index; + typedef typename MatrixType::Scalar Scalar; + typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; + typedef Matrix<Scalar, 1, MatrixType::ColsAtCompileTime> RowVectorType; + Index rows = m.rows(); + Index cols = m.cols(); + + Index r = ei_random<Index>(0, rows-1), r2 = ei_random<Index>(0, rows-1), c = ei_random<Index>(0, cols-1); + VERIFY_IS_APPROX(MatrixType::Ones(rows,cols)(r,c), static_cast<Scalar>(1)); + MatrixType m1 = MatrixType::Ones(rows,cols); + VERIFY_IS_APPROX(m1(r,c), static_cast<Scalar>(1)); + VectorType v1 = VectorType::Random(rows); + v1[0]; + Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> + square(v1.asDiagonal()); + if(r==r2) VERIFY_IS_APPROX(square(r,r2), v1[r]); + else VERIFY_IS_MUCH_SMALLER_THAN(square(r,r2), static_cast<Scalar>(1)); + square = MatrixType::Zero(rows, rows); + square.diagonal() = VectorType::Ones(rows); + VERIFY_IS_APPROX(square, MatrixType::Identity(rows, rows)); +} + +void test_miscmatrices() +{ + for(int i = 0; i < g_repeat; i++) { + CALL_SUBTEST_1( miscMatrices(Matrix<float, 1, 1>()) ); + CALL_SUBTEST_2( miscMatrices(Matrix4d()) ); + CALL_SUBTEST_3( miscMatrices(MatrixXcf(3, 3)) ); + CALL_SUBTEST_4( miscMatrices(MatrixXi(8, 12)) ); + CALL_SUBTEST_5( miscMatrices(MatrixXcd(20, 20)) ); + } +} diff --git a/pool/shard007/C++/0094143_JobManagemetPassBruteForce.cpp b/pool/shard007/C++/0094143_JobManagemetPassBruteForce.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dac0c8b0c575a3a17c0ef1666608f968a80e28fa --- /dev/null +++ b/pool/shard007/C++/0094143_JobManagemetPassBruteForce.cpp @@ -0,0 +1,118 @@ + +#include "JobManagemetPassBruteForce.h" +#include <iostream> +#include <cmath> + +void ThreadsManagementSystemPassBreak::JobManagemetPassBruteForce::nothing() { + +} + + +void ThreadsManagementSystemPassBreak::JobManagemetPassBruteForce::calculationMaxNumberSteps() { + TypeNumberSteps max = static_cast<TypeNumberSteps>(std::pow( + job->getAlphabet()->size(), + job->getMaxLengthPassword())); + + *(const_cast<TypeNumberSteps*>(&maxNumberSteps)) = max; +} + + + +void ThreadsManagementSystemPassBreak::JobManagemetPassBruteForce::intializeCurrentLengthPassw() { + currentLengthPassw = job->getMinLengthPassword(); +} + + + + + +std::unique_ptr< ThreadsManagementSystem::TaskInterface> +ThreadsManagementSystemPassBreak::JobManagemetPassBruteForce::getTask() { + if(!nextTaskGenerator->next()) + { + noHaveTask(); + } + + auto passwordBeginSearch = std::make_unique<GeneratePass>(*nextTaskGenerator); + passwordBeginSearch->setNumberStepsExecuted(0); + passwordBeginSearch->setNumberStepsMax(job->getResolutionStepTask()); + + auto alphabetP = std::make_unique<const Alphabet>( *(job->getAlphabet())); + + std::unique_ptr< ThreadsManagementSystem::TaskInterface> task = std::make_unique< TaskPassBruteForce>( + job->getId(), + idTask++, + job->getHashType(), + job->getMethod(), + job->getHash(), + std::move(alphabetP), + std::move(passwordBeginSearch) + ); + + nextTaskGenerator->next(job->getResolutionStepTask() + 1); + + ++numberTaskSend; + + return task; +} + +ThreadsManagementSystemPassBreak::JobManagemetPassBruteForce::JobManagemetPassBruteForce( + std::unique_ptr<const ThreadsManagementSystemPassBreak::JobPass> &&job) : JobManagementPass(std::move(job)) { + + calculationMaxNumberSteps(); + intializeCurrentLengthPassw(); + nextTaskGenerator = std::make_unique<GeneratePass>(maxNumberSteps,this->job->getAlphabet()->size()); +} + + + + + +void ThreadsManagementSystemPassBreak::JobManagemetPassBruteForce::updateStateJobInGetTask() { + haveState(); + + double tasksToEnd = (double)(maxNumberSteps - stateJob.getNumberExecutedSteps()) / (double) job->getResolutionStepTask(); + + setTimeToEnd(tasksToEnd); + + + stateJob.addnumberExecutedStep(job->getResolutionStepTask()); + if(stateJob.getNumberExecutedSteps() >= maxNumberSteps){ + stateJob.setNumberExecutedSteps(maxNumberSteps); + noHaveTask(); + stateJob.setTimeEnd(0.0); + } + + + const double doubMaxNumberSteps = maxNumberSteps + 0.01 * (double)maxNumberSteps; + + double progresss =(double)stateJob.getNumberExecutedSteps()/doubMaxNumberSteps; + std::cout << "\n\n PROGRES => " << progresss << " MAX STEPS " << maxNumberSteps << "\n\n"; + stateJob.setProgress(progresss); + + + if(currentLengthStateTask >= currentLengthPassw){ + stateJob.setLengthOfCheckedPasswords(currentLengthPassw); + currentLengthPassw = currentLengthStateTask; + //std::cout << "\n\n LengPass " << currentLengthPassw << " " << nextTaskGenerator->size() << "\n\n"; + } + + setTimeForStartInStateJob(); +} + + + + + + +void ThreadsManagementSystemPassBreak::JobManagemetPassBruteForce::addSatateTask( + std::unique_ptr<const ThreadsManagementSystem::StateTaskInterface> &&stateTask) { + const StateTaskPass* stateTaspPtr = dynamic_cast<const StateTaskPass*>(stateTask.get()); + + if(stateTaspPtr != nullptr) { + currentLengthStateTask = stateTaspPtr->getCurrentLengthPassw(); + } + + updateStateJobInGetTask(); + JobManagementPass::addSatateTask(std::move(stateTask)); +} diff --git a/pool/shard007/C++/0094144_timedata.cpp b/pool/shard007/C++/0094144_timedata.cpp new file mode 100644 index 0000000000000000000000000000000000000000..74c460be80f78b1847d6ea9762ccd1cedd9c43c6 --- /dev/null +++ b/pool/shard007/C++/0094144_timedata.cpp @@ -0,0 +1,115 @@ +// Copyright (c) 2014-2015 The Deuscoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "timedata.h" + +#include "netbase.h" +#include "sync.h" +#include "ui_interface.h" +#include "util.h" +#include "utilstrencodings.h" + +#include <boost/foreach.hpp> + +using namespace std; + +static CCriticalSection cs_nTimeOffset; +static int64_t nTimeOffset = 0; + +/** + * "Never go to sea with two chronometers; take one or three." + * Our three time sources are: + * - System clock + * - Median of other nodes clocks + * - The user (asking the user to fix the system clock if the first two disagree) + */ +int64_t GetTimeOffset() +{ + LOCK(cs_nTimeOffset); + return nTimeOffset; +} + +int64_t GetAdjustedTime() +{ + return GetTime() + GetTimeOffset(); +} + +static int64_t abs64(int64_t n) +{ + return (n >= 0 ? n : -n); +} + +#define DEUSCOIN_TIMEDATA_MAX_SAMPLES 200 + +void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample) +{ + LOCK(cs_nTimeOffset); + // Ignore duplicates + static set<CNetAddr> setKnown; + if (setKnown.size() == DEUSCOIN_TIMEDATA_MAX_SAMPLES) + return; + if (!setKnown.insert(ip).second) + return; + + // Add data + static CMedianFilter<int64_t> vTimeOffsets(DEUSCOIN_TIMEDATA_MAX_SAMPLES, 0); + vTimeOffsets.input(nOffsetSample); + LogPrint("net","added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60); + + // There is a known issue here (see issue #4521): + // + // - The structure vTimeOffsets contains up to 200 elements, after which + // any new element added to it will not increase its size, replacing the + // oldest element. + // + // - The condition to update nTimeOffset includes checking whether the + // number of elements in vTimeOffsets is odd, which will never happen after + // there are 200 elements. + // + // But in this case the 'bug' is protective against some attacks, and may + // actually explain why we've never seen attacks which manipulate the + // clock offset. + // + // So we should hold off on fixing this and clean it up as part of + // a timing cleanup that strengthens it in a number of other ways. + // + if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1) + { + int64_t nMedian = vTimeOffsets.median(); + std::vector<int64_t> vSorted = vTimeOffsets.sorted(); + // Only let other nodes change our time by so much + if (abs64(nMedian) < 70 * 60) + { + nTimeOffset = nMedian; + } + else + { + nTimeOffset = 0; + + static bool fDone; + if (!fDone) + { + // If nobody has a time different than ours but within 5 minutes of ours, give a warning + bool fMatch = false; + BOOST_FOREACH(int64_t nOffset, vSorted) + if (nOffset != 0 && abs64(nOffset) < 5 * 60) + fMatch = true; + + if (!fMatch) + { + fDone = true; + string strMessage = _("Please check that your computer's date and time are correct! If your clock is wrong Deuscoin Core will not work properly."); + strMiscWarning = strMessage; + uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING); + } + } + } + + BOOST_FOREACH(int64_t n, vSorted) + LogPrint("net", "%+d ", n); + LogPrint("net", "| "); + + LogPrint("net", "nTimeOffset = %+d (%+d minutes)\n", nTimeOffset, nTimeOffset/60); + } +} diff --git a/pool/shard007/C++/0094145_netif.cpp b/pool/shard007/C++/0094145_netif.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7a029df2fdf8f8cb3817b217c08f409af50188a9 --- /dev/null +++ b/pool/shard007/C++/0094145_netif.cpp @@ -0,0 +1,148 @@ +#include "netif.h" +#include "../core/common.h" +#include <sstream> +#include <sys/ioctl.h> +#include <net/if.h> + + +namespace Epyx +{ + + NetIf::NetIf() + :flags(0) { + // Everything is correctly initialized by default but flags... + } + + NetIf::NetIf(const struct ifaddrs& iface) + :name(iface.ifa_name), flags(iface.ifa_flags) { + if (iface.ifa_addr->sa_family == AF_INET || iface.ifa_addr->sa_family == AF_INET6) { + if (iface.ifa_addr != NULL) + addr = IpAddress(iface.ifa_addr); + if (iface.ifa_netmask != NULL) + netmask = IpAddress(iface.ifa_netmask); + } + if (flags & IFF_BROADCAST && iface.ifa_ifu.ifu_broadaddr != NULL) { + broadcast = IpAddress(iface.ifa_ifu.ifu_broadaddr); + } + } + + std::ostream& operator<<(std::ostream& os, const NetIf& ni) { + os << ni.name << " (" << ni.addr << "/" << ni.netmask; + if (!ni.broadcast.empty()) + os << " bdcast " << ni.broadcast; + os << ")"; + return os; + } + + const std::string& NetIf::getName() const { + return name; + } + + const IpAddress& NetIf::getAddress() const { + return addr; + } + + const IpAddress& NetIf::getBroadcast() const { + return broadcast; + } + + bool NetIf::isUp() const { + return flags & IFF_UP; + } + + std::vector<NetIf> NetIf::getAllNet() { + std::vector<NetIf> ifaces; + struct ifaddrs *ifAddrStruct = NULL; + struct ifaddrs *ifa = NULL; + + getifaddrs(&ifAddrStruct); + for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { + if (ifa->ifa_addr != NULL + && (ifa->ifa_addr->sa_family == AF_INET || ifa->ifa_addr->sa_family == AF_INET6)) { + ifaces.push_back(NetIf(*ifa)); + } + } + if (ifAddrStruct != NULL) + freeifaddrs(ifAddrStruct); + return ifaces; + } + + std::vector<NetIf> NetIf::getByName(const std::string& name) { + std::vector<NetIf> ifaces; + struct ifaddrs *ifAddrStruct = NULL; + struct ifaddrs *ifa = NULL; + + getifaddrs(&ifAddrStruct); + for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { + if (name.compare(ifa->ifa_name) == 0) { + ifaces.push_back(NetIf(*ifa)); + } + } + if (ifAddrStruct != NULL) + freeifaddrs(ifAddrStruct); + return ifaces; + } + + NetIf NetIf::pickExternalInterface(int ipVersion, bool doLog) { + std::vector<NetIf> ifaces = NetIf::getAllNet(); + std::vector<NetIf> externIfaces; + std::vector<NetIf> localIfaces; + + for (std::vector<NetIf>::const_iterator iiface = ifaces.begin(); + iiface != ifaces.end(); iiface++) { + // Keep only specific IP version + const IpAddress& addr = iiface->getAddress(); + if (addr.empty() || addr.getVersion() != ipVersion) + continue; + // Difference between local and extern + if (addr.isLocal()) + localIfaces.push_back(*iiface); + else + externIfaces.push_back(*iiface); + } + + if (!externIfaces.empty()) { + if (doLog) { + if (externIfaces.size() >= 2) { + // Found more than 2 external interface, keep first + log::info << "More than one extern network interface found. Using first of:\n"; + for (std::vector<NetIf>::const_iterator iiface = externIfaces.begin(); + iiface != externIfaces.end(); iiface++) { + log::info << " * " << *iiface << "\n"; + } + log::info << log::endl; + + } else if (doLog) { + // Found exactly one external interface + log::info << "Found extern network interface " << externIfaces[0] + << log::endl; + } + } + return externIfaces[0]; + } else if (!localIfaces.empty()) { + if (doLog) { + log::info << "No extern network interface found, using local." + << log::endl; + if (localIfaces.size() >= 2) { + // Found more than 2 external interface, keep first + log::info << "More than one local network interface found. Using first of:\n"; + for (std::vector<NetIf>::const_iterator iiface = localIfaces.begin(); + iiface != localIfaces.end(); iiface++) { + log::info << " * " << *iiface << "\n"; + } + log::info << log::endl; + + } else if (doLog) { + // Found exactly one external interface + log::info << "Found local network interface " << localIfaces[0] + << log::endl; + } + } + return localIfaces[0]; + } + if (doLog) { + log::info << "No network interface found" << log::endl; + } + throw MinorException("NetIf", "No network interface found"); + } +} diff --git a/pool/shard007/C++/0094154_AXObjectCacheWin.cpp b/pool/shard007/C++/0094154_AXObjectCacheWin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..59ff6b0bf85810363f2b632c5ba60e763daca924 --- /dev/null +++ b/pool/shard007/C++/0094154_AXObjectCacheWin.cpp @@ -0,0 +1,187 @@ +/* + * Copyright (C) 2008, 2009, 2010, 2013 Apple Inc. All Rights Reserved. + * Copyright (C) 2012 Serotek Corporation. 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. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 "config.h" +#include "AXObjectCache.h" + +#include "AccessibilityObject.h" +#include "Chrome.h" +#include "ChromeClient.h" +#include "Document.h" +#include "Page.h" +#include "RenderObject.h" + +// Provided by IAccessibleEventID.idl +#define IA2_EVENT_DOCUMENT_LOAD_COMPLETE 261 + + +namespace WebCore { +using namespace std; + +void AXObjectCache::detachWrapper(AccessibilityObject* obj, AccessibilityDetachmentType) +{ + // On Windows, AccessibilityObjects are created when get_accChildCount is + // called, but they are not wrapped until get_accChild is called, so this + // object may not have a wrapper. + if (AccessibilityObjectWrapper* wrapper = obj->wrapper()) + wrapper->detach(); +} + +void AXObjectCache::attachWrapper(AccessibilityObject*) +{ + // On Windows, AccessibilityObjects are wrapped when the accessibility + // software requests them via get_accChild. +} + +void AXObjectCache::handleScrolledToAnchor(const Node* anchorNode) +{ + // The anchor node may not be accessible. Post the notification for the + // first accessible object. + postPlatformNotification(AccessibilityObject::firstAccessibleObjectFromNode(anchorNode), AXScrolledToAnchor); +} + +void AXObjectCache::postPlatformNotification(AccessibilityObject* obj, AXNotification notification) +{ + if (!obj) + return; + + Document* document = obj->document(); + if (!document) + return; + + Page* page = document->page(); + if (!page || !page->chrome().platformPageClient()) + return; + + DWORD msaaEvent; + switch (notification) { + case AXCheckedStateChanged: + msaaEvent = EVENT_OBJECT_STATECHANGE; + break; + + case AXFocusedUIElementChanged: + case AXActiveDescendantChanged: + msaaEvent = EVENT_OBJECT_FOCUS; + break; + + case AXScrolledToAnchor: + msaaEvent = EVENT_SYSTEM_SCROLLINGSTART; + break; + + case AXLayoutComplete: + msaaEvent = EVENT_OBJECT_REORDER; + break; + + case AXLoadComplete: + msaaEvent = IA2_EVENT_DOCUMENT_LOAD_COMPLETE; + break; + + case AXValueChanged: + case AXMenuListValueChanged: + msaaEvent = EVENT_OBJECT_VALUECHANGE; + break; + + case AXMenuListItemSelected: + msaaEvent = EVENT_OBJECT_SELECTION; + break; + + default: + return; + } + + // Windows will end up calling get_accChild() on the root accessible + // object for the WebView, passing the child ID that we specify below. We + // negate the AXID so we know that the caller is passing the ID of an + // element, not the index of a child element. + + ASSERT(obj->axObjectID() >= 1); + ASSERT(obj->axObjectID() <= numeric_limits<LONG>::max()); + + NotifyWinEvent(msaaEvent, page->chrome().platformPageClient(), OBJID_CLIENT, -static_cast<LONG>(obj->axObjectID())); +} + +void AXObjectCache::nodeTextChangePlatformNotification(AccessibilityObject*, AXTextChange, unsigned, const String&) +{ +} + +void AXObjectCache::frameLoadingEventPlatformNotification(AccessibilityObject* obj, AXLoadingEvent notification) +{ + if (!obj) + return; + + Document* document = obj->document(); + if (!document) + return; + + Page* page = document->page(); + if (!page) + return; + + if (notification == AXLoadingStarted) + page->chrome().client().AXStartFrameLoad(); + else if (notification == AXLoadingFinished) + page->chrome().client().AXFinishFrameLoad(); +} + +AXID AXObjectCache::platformGenerateAXID() const +{ + static AXID lastUsedID = 0; + + // Generate a new ID. Windows accessibility relies on a positive AXID, + // ranging from 1 to LONG_MAX. + AXID objID = lastUsedID; + do { + ++objID; + objID %= std::numeric_limits<LONG>::max(); + } while (objID == 0 || HashTraits<AXID>::isDeletedValue(objID) || m_idsInUse.contains(objID)); + + ASSERT(objID >= 1 && objID <= std::numeric_limits<LONG>::max()); + + lastUsedID = objID; + + return objID; +} + +void AXObjectCache::platformHandleFocusedUIElementChanged(Node*, Node* newFocusedNode) +{ + if (!newFocusedNode) + return; + + Page* page = newFocusedNode->document().page(); + if (!page || !page->chrome().platformPageClient()) + return; + + AccessibilityObject* focusedObject = focusedUIElementForPage(page); + if (!focusedObject) + return; + + ASSERT(!focusedObject->accessibilityIsIgnored()); + + postPlatformNotification(focusedObject, AXFocusedUIElementChanged); +} + +} // namespace WebCore diff --git a/pool/shard007/C++/0094158_ftp_directory_listing_parser_os2.cc b/pool/shard007/C++/0094158_ftp_directory_listing_parser_os2.cc new file mode 100644 index 0000000000000000000000000000000000000000..094a9bdb8d8475e50b008d670249d909a619c231 --- /dev/null +++ b/pool/shard007/C++/0094158_ftp_directory_listing_parser_os2.cc @@ -0,0 +1,77 @@ +// Copyright (c) 2011 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 "net/ftp/ftp_directory_listing_parser_os2.h" + +#include <vector> + +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_split.h" +#include "base/strings/string_util.h" +#include "base/time/time.h" +#include "net/ftp/ftp_directory_listing_parser.h" +#include "net/ftp/ftp_util.h" + +namespace net { + +bool ParseFtpDirectoryListingOS2( + const std::vector<base::string16>& lines, + std::vector<FtpDirectoryListingEntry>* entries) { + for (size_t i = 0; i < lines.size(); i++) { + if (lines[i].empty()) + continue; + + std::vector<base::string16> columns; + base::SplitString(base::CollapseWhitespace(lines[i], false), ' ', &columns); + + // Every line of the listing consists of the following: + // + // 1. size in bytes (0 for directories) + // 2. type (A for files, DIR for directories) + // 3. date + // 4. time + // 5. filename (may be empty or contain spaces) + // + // For now, make sure we have 1-4, and handle 5 later. + if (columns.size() < 4) + return false; + + FtpDirectoryListingEntry entry; + if (!base::StringToInt64(columns[0], &entry.size)) + return false; + if (EqualsASCII(columns[1], "DIR")) { + if (entry.size != 0) + return false; + entry.type = FtpDirectoryListingEntry::DIRECTORY; + entry.size = -1; + } else if (EqualsASCII(columns[1], "A")) { + entry.type = FtpDirectoryListingEntry::FILE; + if (entry.size < 0) + return false; + } else { + return false; + } + + if (!FtpUtil::WindowsDateListingToTime(columns[2], + columns[3], + &entry.last_modified)) { + return false; + } + + entry.name = FtpUtil::GetStringPartAfterColumns(lines[i], 4); + if (entry.name.empty()) { + // Some FTP servers send listing entries with empty names. + // It's not obvious how to display such an entry, so ignore them. + // We don't want to make the parsing fail at this point though. + // Other entries can still be useful. + continue; + } + + entries->push_back(entry); + } + + return true; +} + +} // namespace net diff --git a/pool/shard007/C++/0094159_fchmodat.cpp b/pool/shard007/C++/0094159_fchmodat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f83c4b9bf38a61d0128ea117bd25ad3c23ce865 --- /dev/null +++ b/pool/shard007/C++/0094159_fchmodat.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2015 The Android Open Source Project + * 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. + * + * 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 <fcntl.h> +#include <sys/stat.h> +#include <sys/types.h> +#include <errno.h> +#include <unistd.h> + +#include "private/ErrnoRestorer.h" + +extern "C" int ___fchmodat(int, const char*, mode_t); + +int fchmodat(int dirfd, const char* pathname, mode_t mode, int flags) { + if ((flags & ~AT_SYMLINK_NOFOLLOW) != 0) { + errno = EINVAL; + return -1; + } + + if (flags & AT_SYMLINK_NOFOLLOW) { + // Emulate AT_SYMLINK_NOFOLLOW using the mechanism described + // at https://sourceware.org/bugzilla/show_bug.cgi?id=14578 + // comment #10 + + int fd = openat(dirfd, pathname, O_PATH | O_NOFOLLOW | O_CLOEXEC); + if (fd == -1) { + return -1; // returns errno from openat + } + + // POSIX requires that ENOTSUP be returned when the system + // doesn't support setting the mode of a symbolic link. + // This is true for all Linux kernels. + // We rely on the O_PATH compatibility layer added in the + // fchmod() function to get errno correct. + int result = fchmod(fd, mode); + ErrnoRestorer errno_restorer; // don't let close() clobber errno + close(fd); + return result; + } + + return ___fchmodat(dirfd, pathname, mode); +} diff --git a/pool/shard007/C++/0094160_ctkDICOMAppWidgetTest1.cpp b/pool/shard007/C++/0094160_ctkDICOMAppWidgetTest1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e6d498dea3f0f3d6d263293de4f382a7c01eac69 --- /dev/null +++ b/pool/shard007/C++/0094160_ctkDICOMAppWidgetTest1.cpp @@ -0,0 +1,87 @@ +/*========================================================================= + + Library: CTK + + Copyright (c) Kitware Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0.txt + + 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. + +=========================================================================*/ + +// Qt includes +#include <QApplication> +#include <QDebug> +#include <QDir> +#include <QTimer> +#include <QString> + +// ctk includes +#include "ctkUtils.h" + +// ctkDICOMCore includes +#include "ctkDICOMAppWidget.h" + +// STD includes +#include <iostream> + +/* Test from build directory: + ./CTK-build/bin/CTKDICOMWidgetsCppTests ctkDICOMAppWidgetTest1 <test directory> + + if the test directory does not have 100 instances in one patient/study/series, test will fail +*/ + +int ctkDICOMAppWidgetTest1( int argc, char * argv [] ) +{ + QApplication app(argc, argv); + + ctkDICOMAppWidget appWidget; + + QFileInfo tempFileInfo(QDir::tempPath() + QString("/ctkDICOMAppWidgetTest1-db")); + QString dbDir = tempFileInfo.absoluteFilePath(); + qDebug() << "\n\nUsing directory: " << dbDir; + if (tempFileInfo.exists()) + { + qDebug() << "\n\nRemoving directory: " << dbDir; + ctk::removeDirRecursively(dbDir); + } + qDebug() << "\n\nMaking directory: " << dbDir; + QDir dir(dbDir); + dir.mkdir(dbDir); + + appWidget.setDatabaseDirectory(dbDir); + QString testString = QString("Test String"); + appWidget.onFileIndexed(testString); + appWidget.openImportDialog(); + appWidget.openExportDialog(); + appWidget.openQueryDialog(); + + appWidget.openQueryDialog(); + + appWidget.setDisplayImportSummary(false); + appWidget.onImportDirectory(argv[argc -1]); + if ( appWidget.patientsAddedDuringImport() != 1 + || appWidget.studiesAddedDuringImport() != 1 + || appWidget.seriesAddedDuringImport() != 1 + || appWidget.instancesAddedDuringImport() != 100) + { + qDebug() << "\n\nDirectory did not import as expected!\n\n"; + return EXIT_FAILURE; + } + + if (argc <= 2 || QString(argv[1]) != "-I") + { + QTimer::singleShot(200, &app, SLOT(quit())); + } + qDebug() << "\n\nAdded to database directory: " << dbDir; + return app.exec(); +} diff --git a/pool/shard007/C++/0094162_mersenne.cpp b/pool/shard007/C++/0094162_mersenne.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c04520f292c1cdfa8fb8a6bb5b67bd30fde3b996 --- /dev/null +++ b/pool/shard007/C++/0094162_mersenne.cpp @@ -0,0 +1,193 @@ +/* + A C-program for MT19937, with initialization improved 2002/1/26. + Coded by Takuji Nishimura and Makoto Matsumoto. + + Before using, initialize the state by using init_genrand(seed) + or init_by_array(init_key, key_length). + + Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, + 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. The names of its contributors may not 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. + + + Any feedback is very welcome. + http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html + email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) +*/ + +#include "mersenne.h" + +#include <string.h> + +namespace AndSoft { + + /* Period parameters */ +#define N 624 +#define M 397 +#define MATRIX_A 0x9908b0dfUL /* constant vector a */ +#define UPPER_MASK 0x80000000UL /* most significant w-r bits */ +#define LOWER_MASK 0x7fffffffUL /* least significant r bits */ + + MersenneTwister::MersenneTwister(const unsigned dim, const unsigned long s) : RandomNumber(dim), mt(new unsigned long [N]), mti(N + 1) { + init_genrand(s); + } + + MersenneTwister::MersenneTwister(const MersenneTwister& rhs) : RandomNumber(rhs.myDim), mt(new unsigned long [N]), mti(rhs.mti) { + memcpy(mt, rhs.mt, N * sizeof(double)); + } + + MersenneTwister::~MersenneTwister() { + delete [] mt; + } + + /* initializes mt[N] with a seed */ + void MersenneTwister::init_genrand(unsigned long s) + { + mt[0]= s & 0xffffffffUL; + for (mti=1; mti<N; mti++) { + mt[mti] = + (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); + /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ + /* In the previous versions, MSBs of the seed affect */ + /* only MSBs of the array mt[]. */ + /* 2002/01/09 modified by Makoto Matsumoto */ + mt[mti] &= 0xffffffffUL; + /* for >32 bit machines */ + } + } + + /* initialize by an array with array-length */ + /* init_key is the array for initializing keys */ + /* key_length is its length */ + /* slight change for C++, 2004/2/26 */ + void MersenneTwister::init_by_array(unsigned long init_key[], int key_length) + { + int i, j, k; + init_genrand(19650218UL); + i=1; j=0; + k = (N>key_length ? N : key_length); + for (; k; k--) { + mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL)) + + init_key[j] + j; /* non linear */ + mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ + i++; j++; + if (i>=N) { mt[0] = mt[N-1]; i=1; } + if (j>=key_length) j=0; + } + for (k=N-1; k; k--) { + mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) + - i; /* non linear */ + mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ + i++; + if (i>=N) { mt[0] = mt[N-1]; i=1; } + } + + mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ + } + + /* generates a random number on [0,0xffffffff]-interval */ + unsigned long MersenneTwister::genrand_int32(void) + { + unsigned long y; + static unsigned long mag01[2]={0x0UL, MATRIX_A}; + /* mag01[x] = x * MATRIX_A for x=0,1 */ + + if (mti >= N) { /* generate N words at one time */ + int kk; + + if (mti == N+1) /* if init_genrand() has not been called, */ + init_genrand(5489UL); /* a default initial seed is used */ + + for (kk=0;kk<N-M;kk++) { + y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); + mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL]; + } + for (;kk<N-1;kk++) { + y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); + mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL]; + } + y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); + mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL]; + + mti = 0; + } + + y = mt[mti++]; + + /* Tempering */ + y ^= (y >> 11); + y ^= (y << 7) & 0x9d2c5680UL; + y ^= (y << 15) & 0xefc60000UL; + y ^= (y >> 18); + + return y; + } + + /* generates a random number on [0,0x7fffffff]-interval */ + long MersenneTwister::genrand_int31(void) + { + return (long)(genrand_int32()>>1); + } + + /* generates a random number on [0,1]-real-interval */ + double MersenneTwister::genrand_real1(void) + { + return genrand_int32()*(1.0/4294967295.0); + /* divided by 2^32-1 */ + } + + /* generates a random number on [0,1)-real-interval */ + double MersenneTwister::genrand_real2(void) + { + return genrand_int32()*(1.0/4294967296.0); + /* divided by 2^32 */ + } + + /* generates a random number on (0,1)-real-interval */ + double MersenneTwister::genrand_real3(void) + { + return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0); + /* divided by 2^32 */ + } + + /* generates a random number on [0,1) with 53-bit resolution*/ + double MersenneTwister::genrand_res53(void) + { + unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6; + return(a*67108864.0+b)*(1.0/9007199254740992.0); + } + /* These real versions are due to Isaku Wada, 2002/01/09 added */ + + void MersenneTwister::nextUniform() { + for (unsigned int i = 0; i < myDim; ++i) { + myUniform[i] = genrand_real3(); + } + } + +}; diff --git a/pool/shard007/C++/0094163_SubroutinesShared.cpp b/pool/shard007/C++/0094163_SubroutinesShared.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd3d1d55ba3f232c7fb6f83f1b701dac840941e0 --- /dev/null +++ b/pool/shard007/C++/0094163_SubroutinesShared.cpp @@ -0,0 +1,132 @@ +#include "Shared/SubroutinesShared.h" +#include "SubroutinesSharedDeepWalkers.h" + +namespace OPS +{ + namespace Shared + { + using namespace OPS; + using namespace OPS::Reprise; + + SubroutineDeclaration* findSubroutineWithImplementationByName(OPS::Reprise::ProgramUnit* pProgramUnit, std::string subroutineName) + { + OPS_ASSERT(pProgramUnit != NULL); + + FindSubroutinesByNameDeepWalker deepWalker(subroutineName, true); + deepWalker.visit(*pProgramUnit); + + FindSubroutinesByNameDeepWalker::SubroutinesDeclarationsContainer dwResult = deepWalker.getSubroutinesDeclaration(); + if(dwResult.size() > 0) + { + return *(dwResult.begin()); + } + + return NULL; + } + + SubroutineDeclaration* findSubroutineWithImplementationByName(OPS::Reprise::TranslationUnit* pTranslationUnit, std::string subroutineName) + { + OPS_ASSERT(pTranslationUnit != NULL); + + FindSubroutinesByNameDeepWalker deepWalker(subroutineName, true); + deepWalker.visit(*pTranslationUnit); + + FindSubroutinesByNameDeepWalker::SubroutinesDeclarationsContainer dwResult = deepWalker.getSubroutinesDeclaration(); + if(dwResult.size() > 0) + { + return *(dwResult.begin()); + } + + return NULL; + } + + SubroutineDeclaration* findSubroutineByName(OPS::Reprise::TranslationUnit* pTranslationUnit, std::string subroutineName) + { + OPS_ASSERT(pTranslationUnit != NULL); + + FindSubroutinesByNameDeepWalker deepWalker(subroutineName, false); + deepWalker.visit(*pTranslationUnit); + + FindSubroutinesByNameDeepWalker::SubroutinesDeclarationsContainer dwResult = deepWalker.getSubroutinesDeclaration(); + if(dwResult.size() > 0) + { + return *(dwResult.begin()); + } + + return NULL; + } + + TranslationUnit* getTranslationUnitBySubroutineDeclaration(SubroutineDeclaration* pSubroutineDeclaration) + { + OPS_ASSERT(pSubroutineDeclaration != NULL); + + TranslationUnit* pResult = NULL; + + if(pSubroutineDeclaration->getParent() != NULL && pSubroutineDeclaration->getParent()->getParent()) + { + pResult = pSubroutineDeclaration->getParent()->getParent()->cast_ptr<TranslationUnit>(); + } + + return pResult; + } + + TypeDeclaration* findTypeDeclarationByName(TranslationUnit* pTranslationUnit, std::string typeName) + { + OPS_ASSERT(pTranslationUnit != NULL); + + FindTypesDeclarationsByNameDeepWalker deepWalker(typeName); + deepWalker.visit(*pTranslationUnit); + + FindTypesDeclarationsByNameDeepWalker::TypesDeclarationsContainer dwResult = deepWalker.getSubroutinesDeclaration(); + if(dwResult.size() > 0) + { + return *(dwResult.begin()); + } + + return NULL; + } + + OPS::Reprise::TypeBase* getArgumentPointedType(OPS::Reprise::SubroutineDeclaration* pSubroutineDeclaration, int argumentIndex) + { + OPS_ASSERT(pSubroutineDeclaration != NULL); + OPS_ASSERT(argumentIndex >= 0); + + if(pSubroutineDeclaration->getType().getParameterCount() <= argumentIndex) + { + return NULL; + } + + OPS::Reprise::TypeBase* pResult = &pSubroutineDeclaration->getType().getParameter(argumentIndex).getType(); + while(pResult->is_a<PtrType>()) + { + pResult = &pResult->cast_ptr<PtrType>()->getPointedType(); + } + + return pResult; + } + + SubroutineDeclaration* getSubroutineDeclarationByStatement(StatementBase* pStatement) + { + OPS_ASSERT(pStatement != NULL); + + BlockStatement& rootBlock = pStatement->getRootBlock(); + return rootBlock.getParent()->cast_ptr<SubroutineDeclaration>(); + } + + OPS::Reprise::TypeBase* findDeclaredTypeByName( OPS::Reprise::TranslationUnit* pTranslationUnit, std::string typeName ) + { + OPS_ASSERT(pTranslationUnit != NULL); + + FindTypesDeclarationsByNameDeepWalker deepWalker(typeName); + deepWalker.visit(*pTranslationUnit); + + FindTypesDeclarationsByNameDeepWalker::TypesContainer dwResult = deepWalker.getTypes(); + if(dwResult.size() > 0) + { + return *(dwResult.begin()); + } + + return NULL; + } + } +} diff --git a/pool/shard007/C++/0094164_SystemHelper.cpp b/pool/shard007/C++/0094164_SystemHelper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e9956432975151e05d06ab4783574efddbfc6d50 --- /dev/null +++ b/pool/shard007/C++/0094164_SystemHelper.cpp @@ -0,0 +1,115 @@ +/// +/// Talk is cheap. Show me the code. - Linus Torvalds +/// +/// Author: WiNGC (wingc@wingc.net) +/// All rights reserved +/// + +#include "SystemHelper.h" + +#include <codecvt> +#include <string> +#include <mutex> + +#include <XmlLite.h> +#include <Wrl\Client.h> + +#include <AutoResource.h> +#include <ErrorThrows.h> + +#pragma comment(lib, "XmlLite") + +using namespace std; +using namespace Microsoft::WRL; + +static std::once_flag s_manifestFileReaderLoaded; +static unique_Heap s_manifestFileBuffer; +static ComPtr<IXmlReader> s_manifestFileReader; + +void _GetManifestFileReader(ComPtr<IXmlReader>& outFileReader) +{ + std::call_once( + s_manifestFileReaderLoaded, + []() + { + ComPtr<IStream> fileReaderStream; + ComPtr<IXmlReaderInput> fileReaderInput; + unqiue_FileHandle manifestFile; + FILE_STANDARD_INFO fileInfo = {}; + + manifestFile = ::CreateFile2( + L"WMAppManifest.xml", + GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + OPEN_EXISTING, + nullptr); + CHECK_WIN32ERR(manifestFile.is_valid()); + CHECK(::GetFileInformationByHandleEx( + manifestFile.get(), + FILE_INFO_BY_HANDLE_CLASS::FileStandardInfo, + &fileInfo, + sizeof(fileInfo))); + ASSERT(fileInfo.EndOfFile.LowPart > 0 && fileInfo.EndOfFile.HighPart == 0); + + s_manifestFileBuffer = ::HeapAlloc(::GetProcessHeap(), 0, fileInfo.EndOfFile.LowPart); + CHECK_WIN32ERR(s_manifestFileBuffer.is_valid()); + + CHECK(::ReadFile(manifestFile.get(), s_manifestFileBuffer.get(), fileInfo.EndOfFile.LowPart, nullptr, nullptr)); + CHECK(::CreateStreamOnHGlobal(reinterpret_cast<HGLOBAL>(s_manifestFileBuffer.get()), FALSE, fileReaderStream.GetAddressOf())); + CHECK(::CreateXmlReader( + __uuidof(IXmlReader), + reinterpret_cast<PVOID*>(s_manifestFileReader.GetAddressOf()), + nullptr)); + CHECK(::CreateXmlReaderInputWithEncodingName( + fileReaderStream.Get(), + nullptr, + L"UTF-8", + TRUE, + nullptr, + fileReaderInput.GetAddressOf())); + CHECK(s_manifestFileReader->SetInput(fileReaderInput.Get())); + }); + + CHECK(s_manifestFileReader.CopyTo(outFileReader.ReleaseAndGetAddressOf())); +} + +string SystemHelper::getVersionInfo() +{ + ComPtr<IXmlReader> xmlReader; + XmlNodeType nodeType = XmlNodeType_None; + + wstring version; + string prefix("Version:"); + + _GetManifestFileReader(xmlReader); + + bool foundVersion = false; + while (!foundVersion) + { + CHECK(xmlReader->Read(&nodeType)); + + switch (nodeType) + { + case XmlNodeType_Element: + { + PCWSTR pElementName = nullptr; + PCWSTR pValue = nullptr; + CHECK(xmlReader->GetLocalName(&pElementName, nullptr)); + if (::wcscmp(pElementName, L"App") == 0) + { + CHECK(xmlReader->MoveToAttributeByName(L"Version", nullptr)); + CHECK(xmlReader->GetValue(&pValue, nullptr)); + version.assign(pValue); + foundVersion = true; + } + break; + } + default: + break; + } + } + + return prefix + SystemHelper::WideStringToNarrower.to_bytes(version); +} + +wstring_convert<codecvt_utf8<wchar_t>, wchar_t> SystemHelper::WideStringToNarrower; \ No newline at end of file diff --git a/pool/shard007/C++/0094167_rpcdump.cpp b/pool/shard007/C++/0094167_rpcdump.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1b3e2b2faecb12e04b87d486e0f78fb17c1e01f --- /dev/null +++ b/pool/shard007/C++/0094167_rpcdump.cpp @@ -0,0 +1,96 @@ +// Copyright (c) 2009-2012 Bitcoin Developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "init.h" // for pwalletMain +#include "cryptographicanomalyrpc.h" +#include "ui_interface.h" +#include "base58.h" + +#include <boost/lexical_cast.hpp> + +#define printf OutputDebugStringF + +using namespace json_spirit; +using namespace std; + +class CTxDump +{ +public: + CBlockIndex *pindex; + int64 nValue; + bool fSpent; + CWalletTx* ptx; + int nOut; + CTxDump(CWalletTx* ptx = NULL, int nOut = -1) + { + pindex = NULL; + nValue = 0; + fSpent = false; + this->ptx = ptx; + this->nOut = nOut; + } +}; + +Value importprivkey(const Array& params, bool fHelp) +{ + if (fHelp || params.size() < 1 || params.size() > 3) + throw runtime_error( + "importprivkey <cryptographicanomalyprivkey> [label] [rescan=true]\n" + "Adds a private key (as returned by dumpprivkey) to your wallet."); + + string strSecret = params[0].get_str(); + string strLabel = ""; + if (params.size() > 1) + strLabel = params[1].get_str(); + + // Whether to perform rescan after import + bool fRescan = true; + if (params.size() > 2) + fRescan = params[2].get_bool(); + + CCryptographicanomalySecret vchSecret; + bool fGood = vchSecret.SetString(strSecret); + + if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); + + CKey key = vchSecret.GetKey(); + CPubKey pubkey = key.GetPubKey(); + CKeyID vchAddress = pubkey.GetID(); + { + LOCK2(cs_main, pwalletMain->cs_wallet); + + pwalletMain->MarkDirty(); + pwalletMain->SetAddressBookName(vchAddress, strLabel); + + if (!pwalletMain->AddKeyPubKey(key, pubkey)) + throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); + + if (fRescan) { + pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); + pwalletMain->ReacceptWalletTransactions(); + } + } + + return Value::null; +} + +Value dumpprivkey(const Array& params, bool fHelp) +{ + if (fHelp || params.size() != 1) + throw runtime_error( + "dumpprivkey <cryptographicanomalyaddress>\n" + "Reveals the private key corresponding to <cryptographicanomalyaddress>."); + + string strAddress = params[0].get_str(); + CCryptographicanomalyAddress address; + if (!address.SetString(strAddress)) + throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Cryptographicanomaly address"); + CKeyID keyID; + if (!address.GetKeyID(keyID)) + throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); + CKey vchSecret; + if (!pwalletMain->GetKey(keyID, vchSecret)) + throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); + return CCryptographicanomalySecret(vchSecret).ToString(); +} diff --git a/pool/shard007/C++/0094172_TheTvDbShowParser.cpp b/pool/shard007/C++/0094172_TheTvDbShowParser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..075b692c00fc054a2b9ff2c00749c426dc765904 --- /dev/null +++ b/pool/shard007/C++/0094172_TheTvDbShowParser.cpp @@ -0,0 +1,117 @@ +#include "TheTvDbShowParser.h" + +#include "scrapers/tv_show/thetvdb/TheTvDbApi.h" +#include "tv_shows/TvShow.h" +#include "tv_shows/TvShowEpisode.h" + +#include <QJsonArray> +#include <QJsonDocument> +#include <QJsonObject> +#include <QJsonParseError> + +#include <chrono> + +namespace mediaelch { +namespace scraper { + +void TheTvDbShowParser::parseInfos(const QJsonObject& json) +{ + const auto showData = json.value("data").toObject(); + + m_show.setTvdbId(TvDbId(showData.value("id").toInt())); + m_show.setImdbId(ImdbId(showData.value("imdbId").toString())); + + m_show.setCertification(Certification(showData.value("rating").toString())); + + // TheTVDb month and day don't have a leading zero + m_show.setFirstAired(QDate::fromString(showData.value("firstAired").toString(), "yyyy-M-d")); + m_show.setNetwork(showData.value("network").toString()); + m_show.setOverview(showData.value("overview").toString()); + + { + Rating rating; + rating.rating = showData.value("siteRating").toDouble(); + rating.voteCount = showData.value("siteRatingCount").toInt(); + rating.source = "tvdb"; + rating.minRating = 0; + rating.maxRating = 10; + m_show.ratings().setOrAddRating(rating); + } + + m_show.setTitle(showData.value("seriesName").toString().trimmed()); + + + const auto runtime = std::chrono::minutes(showData.value("runtime").toString().toInt()); + m_show.setRuntime(runtime); + + m_show.setStatus(showData.value("status").toString()); + + QStringList genres; + const auto jsonGenres = showData.value("genre").toArray(); + for (const auto& jsonGenre : jsonGenres) { + const QString genre = jsonGenre.toString(); + if (!genre.isEmpty()) { + genres << genre; + } + } + m_show.setGenres(genres); +} + +void TheTvDbShowParser::parseActors(const QJsonObject& json) +{ + const auto actors = json.value("data").toArray(); + + for (const auto& actorValue : actors) { + const auto actorObj = actorValue.toObject(); + + Actor actor; + actor.id = QString::number(actorObj.value("id").toInt()); + actor.name = actorObj.value("name").toString(); + actor.role = actorObj.value("role").toString(); + actor.thumb = TheTvDbApi::makeFullAssetUrl("/banners/" + actorObj.value("image").toString()).toString(); + + m_show.addActor(actor); + } +} + +void TheTvDbShowParser::parseImages(const QJsonObject& json) +{ + const auto images = json.value("data").toArray(); + + for (const auto& imageValue : images) { + const auto imageObj = imageValue.toObject(); + const QString keyType = imageObj.value("keyType").toString(); + + Poster p; + p.id = QString::number(imageObj.value("id").toInt()); + p.originalUrl = TheTvDbApi::makeFullAssetUrl("/banners/" + imageObj.value("fileName").toString()); + p.thumbUrl = TheTvDbApi::makeFullAssetUrl("/banners/" + imageObj.value("thumbnail").toString()); + + const QStringList resolution = imageObj.value("resolution").toString().split('x'); + if (resolution.length() == 2) { + p.originalSize.setWidth(resolution[0].toInt()); + p.originalSize.setHeight(resolution[1].toInt()); + } + + if (keyType == "fanart") { + m_show.addBackdrop(p); + + } else if (keyType == "poster") { + m_show.addPoster(p); + + } else if (keyType == "season") { + const auto season = SeasonNumber(imageObj.value("subKey").toString().toInt()); + m_show.addSeasonPoster(season, p); + + } else if (keyType == "seasonwide") { + const auto season = SeasonNumber(imageObj.value("subKey").toString().toInt()); + m_show.addSeasonBanner(season, p); + + } else if (keyType == "series") { + m_show.addBanner(p); + } + } +} + +} // namespace scraper +} // namespace mediaelch diff --git a/pool/shard007/C++/0094176_mutex_time_point.pass.cpp b/pool/shard007/C++/0094176_mutex_time_point.pass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..baf08de559c64b70815554dba5aaded6b53873bf --- /dev/null +++ b/pool/shard007/C++/0094176_mutex_time_point.pass.cpp @@ -0,0 +1,79 @@ +//===----------------------------------------------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is dual licensed under the MIT and the University of Illinois Open +// Source Licenses. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +// <shared_mutex> + +// class shared_timed_mutex; + +// template <class Clock, class Duration> +// shared_lock(mutex_type& m, const chrono::time_point<Clock, Duration>& abs_time); + +#include <shared_mutex> +#include <thread> +#include <vector> +#include <cstdlib> +#include <cassert> + +#if _LIBCPP_STD_VER > 11 + +std::shared_timed_mutex m; + +typedef std::chrono::steady_clock Clock; +typedef Clock::time_point time_point; +typedef Clock::duration duration; +typedef std::chrono::milliseconds ms; +typedef std::chrono::nanoseconds ns; + +void f1() +{ + time_point t0 = Clock::now(); + std::shared_lock<std::shared_timed_mutex> lk(m, Clock::now() + ms(300)); + assert(lk.owns_lock() == true); + time_point t1 = Clock::now(); + ns d = t1 - t0 - ms(250); + assert(d < ns(50000000)); // within 50ms +} + +void f2() +{ + time_point t0 = Clock::now(); + std::shared_lock<std::shared_timed_mutex> lk(m, Clock::now() + ms(250)); + assert(lk.owns_lock() == false); + time_point t1 = Clock::now(); + ns d = t1 - t0 - ms(250); + assert(d < ms(50)); // within 50ms +} + +#endif // _LIBCPP_STD_VER > 11 + +int main() +{ +#if _LIBCPP_STD_VER > 11 + { + m.lock(); + std::vector<std::thread> v; + for (int i = 0; i < 5; ++i) + v.push_back(std::thread(f1)); + std::this_thread::sleep_for(ms(250)); + m.unlock(); + for (auto& t : v) + t.join(); + } + { + m.lock(); + std::vector<std::thread> v; + for (int i = 0; i < 5; ++i) + v.push_back(std::thread(f2)); + std::this_thread::sleep_for(ms(300)); + m.unlock(); + for (auto& t : v) + t.join(); + } +#endif // _LIBCPP_STD_VER > 11 +} diff --git a/pool/shard007/C++/0094177_inviwoapplication-test.cpp b/pool/shard007/C++/0094177_inviwoapplication-test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..053d54c4520861ae46a69a0a590543956211cda5 --- /dev/null +++ b/pool/shard007/C++/0094177_inviwoapplication-test.cpp @@ -0,0 +1,52 @@ +/********************************************************************************* + * + * Inviwo - Interactive Visualization Workshop + * + * Copyright (c) 2013-2015 Inviwo Foundation + * 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. + * + * 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 <warn/push> +#include <warn/ignore/all> +#include <gtest/gtest.h> +#include <warn/pop> + +#include <inviwo/core/common/inviwoapplication.h> + +namespace inviwo{ + +TEST(InviwoApplicationTest,initTest) { + InviwoApplication* app = InviwoApplication::getPtr(); + ASSERT_TRUE(app!=0); + EXPECT_TRUE(app->isInitialized()); +} + + +TEST(InviwoApplicationTest,displayNameTest) { + InviwoApplication* app = InviwoApplication::getPtr(); + ASSERT_TRUE(app!=0); + EXPECT_TRUE(app->getDisplayName().find(IVW_VERSION)!=std::string::npos); +} + +} \ No newline at end of file diff --git a/pool/shard007/C++/0094179_winglob.cpp b/pool/shard007/C++/0094179_winglob.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5d5f195adb23a6cf4bf1b737f9602aac56b3c7a0 --- /dev/null +++ b/pool/shard007/C++/0094179_winglob.cpp @@ -0,0 +1,113 @@ +// **************************************************************************** +// winglob.cpp ELFE project +// **************************************************************************** +// +// File Description: +// +// +// +// +// +// +// +// +// +// +// **************************************************************************** +// This document is released under the GNU General Public License, with the +// following clarification and exception. +// +// Linking this library statically or dynamically with other modules is making +// a combined work based on this library. Thus, the terms and conditions of the +// GNU General Public License cover the whole combination. +// +// As a special exception, the copyright holders of this library give you +// permission to link this library with independent modules to produce an +// executable, regardless of the license terms of these independent modules, +// and to copy and distribute the resulting executable under terms of your +// choice, provided that you also meet, for each linked independent module, +// the terms and conditions of the license of that module. An independent +// module is a module which is not derived from or based on this library. +// If you modify this library, you may extend this exception to your version +// of the library, but you are not obliged to do so. If you do not wish to +// do so, delete this exception statement from your version. +// +// See http://www.gnu.org/copyleft/gpl.html and Matthew 25:22 for details +// (C) 1992-2010 Christophe de Dinechin <christophe@taodyne.com> +// (C) 2010 Taodyne SAS +// **************************************************************************** + +#include "config.h" + +#ifndef HAVE_GLOB + +#include "base.h" +#include "winglob.h" +#include <dirent.h> +#include <string> +#include <windows.h> + + +static void globinternal(text dir, text pattern, globpaths &paths) +// ---------------------------------------------------------------------------- +// Internal variant of glob, where dir is a directory to look into +// ---------------------------------------------------------------------------- +{ + // Check if we are scanning a directory + text subpat = ""; + bool dirmode = false; + + // Transform the regexp into a file-style regexp + size_t pos = pattern.find_first_of("/\\"); + if (pos != pattern.npos) + { + subpat = pattern.substr(pos + 1, pattern.npos); + pattern = pattern.substr(0, pos-1); + dirmode = true; + } + + // Open directory + WIN32_FIND_DATAA fdata; + HANDLE fhandle = FindFirstFileA(dir.c_str(), &fdata); + bool more = fhandle != INVALID_HANDLE_VALUE; + if (more) + { + do + { + std::string entry(fdata.cFileName); + if (dirmode) + globinternal(dir + "\\" + entry, subpat, paths); + else + paths.push_back(entry); + more = FindNextFileA(fhandle, &fdata); + } while (more); + FindClose(fhandle); + } +} + + +int glob(const char *pattern, + int flags, + int (*errfunc)(const char *epath, int errno), + glob_t *pglob) +// ---------------------------------------------------------------------------- +// Simulation of the glob() function on Windows +// ---------------------------------------------------------------------------- +{ + (void)flags; + (void)errfunc; + globinternal("", pattern, pglob->gl_pathv); + pglob->gl_pathc = pglob->gl_pathv.size(); + return 0; +} + + +void globfree(glob_t *pglob) +// ---------------------------------------------------------------------------- +// Simulation of the globfree() function on Windows +// ---------------------------------------------------------------------------- +{ + pglob->gl_pathv.clear(); +} + +#endif // !HAVE_GLOB diff --git a/pool/shard007/C++/0094180_render_handler_ctocpp.cc b/pool/shard007/C++/0094180_render_handler_ctocpp.cc new file mode 100644 index 0000000000000000000000000000000000000000..4d948d1533790900b673b3d54ebd6f575467cc31 --- /dev/null +++ b/pool/shard007/C++/0094180_render_handler_ctocpp.cc @@ -0,0 +1,305 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/drag_data_cpptoc.h" +#include "libcef_dll/ctocpp/render_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefRenderHandlerCToCpp::GetRootScreenRect(CefRefPtr<CefBrowser> browser, + CefRect& rect) { + cef_render_handler_t* _struct = GetStruct(); + if (CEF_MEMBER_MISSING(_struct, get_root_screen_rect)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + + // Execute + int _retval = _struct->get_root_screen_rect(_struct, + CefBrowserCppToC::Wrap(browser), + &rect); + + // Return type: bool + return _retval?true:false; +} + +bool CefRenderHandlerCToCpp::GetViewRect(CefRefPtr<CefBrowser> browser, + CefRect& rect) { + cef_render_handler_t* _struct = GetStruct(); + if (CEF_MEMBER_MISSING(_struct, get_view_rect)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + + // Execute + int _retval = _struct->get_view_rect(_struct, + CefBrowserCppToC::Wrap(browser), + &rect); + + // Return type: bool + return _retval?true:false; +} + +bool CefRenderHandlerCToCpp::GetScreenPoint(CefRefPtr<CefBrowser> browser, + int viewX, int viewY, int& screenX, int& screenY) { + cef_render_handler_t* _struct = GetStruct(); + if (CEF_MEMBER_MISSING(_struct, get_screen_point)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + + // Execute + int _retval = _struct->get_screen_point(_struct, + CefBrowserCppToC::Wrap(browser), + viewX, + viewY, + &screenX, + &screenY); + + // Return type: bool + return _retval?true:false; +} + +bool CefRenderHandlerCToCpp::GetScreenInfo(CefRefPtr<CefBrowser> browser, + CefScreenInfo& screen_info) { + cef_render_handler_t* _struct = GetStruct(); + if (CEF_MEMBER_MISSING(_struct, get_screen_info)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + + // Execute + int _retval = _struct->get_screen_info(_struct, + CefBrowserCppToC::Wrap(browser), + &screen_info); + + // Return type: bool + return _retval?true:false; +} + +void CefRenderHandlerCToCpp::OnPopupShow(CefRefPtr<CefBrowser> browser, + bool show) { + cef_render_handler_t* _struct = GetStruct(); + if (CEF_MEMBER_MISSING(_struct, on_popup_show)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + _struct->on_popup_show(_struct, + CefBrowserCppToC::Wrap(browser), + show); +} + +void CefRenderHandlerCToCpp::OnPopupSize(CefRefPtr<CefBrowser> browser, + const CefRect& rect) { + cef_render_handler_t* _struct = GetStruct(); + if (CEF_MEMBER_MISSING(_struct, on_popup_size)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + _struct->on_popup_size(_struct, + CefBrowserCppToC::Wrap(browser), + &rect); +} + +void CefRenderHandlerCToCpp::OnPaint(CefRefPtr<CefBrowser> browser, + PaintElementType type, const RectList& dirtyRects, const void* buffer, + int width, int height) { + cef_render_handler_t* _struct = GetStruct(); + if (CEF_MEMBER_MISSING(_struct, on_paint)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Verify param: buffer; type: simple_byaddr + DCHECK(buffer); + if (!buffer) + return; + + // Translate param: dirtyRects; type: simple_vec_byref_const + const size_t dirtyRectsCount = dirtyRects.size(); + cef_rect_t* dirtyRectsList = NULL; + if (dirtyRectsCount > 0) { + dirtyRectsList = new cef_rect_t[dirtyRectsCount]; + DCHECK(dirtyRectsList); + if (dirtyRectsList) { + for (size_t i = 0; i < dirtyRectsCount; ++i) { + dirtyRectsList[i] = dirtyRects[i]; + } + } + } + + // Execute + _struct->on_paint(_struct, + CefBrowserCppToC::Wrap(browser), + type, + dirtyRectsCount, + dirtyRectsList, + buffer, + width, + height); + + // Restore param:dirtyRects; type: simple_vec_byref_const + if (dirtyRectsList) + delete [] dirtyRectsList; +} + +void CefRenderHandlerCToCpp::OnCursorChange(CefRefPtr<CefBrowser> browser, + CefCursorHandle cursor, CursorType type, + const CefCursorInfo& custom_cursor_info) { + cef_render_handler_t* _struct = GetStruct(); + if (CEF_MEMBER_MISSING(_struct, on_cursor_change)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + _struct->on_cursor_change(_struct, + CefBrowserCppToC::Wrap(browser), + cursor, + type, + &custom_cursor_info); +} + +bool CefRenderHandlerCToCpp::StartDragging(CefRefPtr<CefBrowser> browser, + CefRefPtr<CefDragData> drag_data, DragOperationsMask allowed_ops, int x, + int y) { + cef_render_handler_t* _struct = GetStruct(); + if (CEF_MEMBER_MISSING(_struct, start_dragging)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: drag_data; type: refptr_diff + DCHECK(drag_data.get()); + if (!drag_data.get()) + return false; + + // Execute + int _retval = _struct->start_dragging(_struct, + CefBrowserCppToC::Wrap(browser), + CefDragDataCppToC::Wrap(drag_data), + allowed_ops, + x, + y); + + // Return type: bool + return _retval?true:false; +} + +void CefRenderHandlerCToCpp::UpdateDragCursor(CefRefPtr<CefBrowser> browser, + DragOperation operation) { + cef_render_handler_t* _struct = GetStruct(); + if (CEF_MEMBER_MISSING(_struct, update_drag_cursor)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + _struct->update_drag_cursor(_struct, + CefBrowserCppToC::Wrap(browser), + operation); +} + +void CefRenderHandlerCToCpp::OnScrollOffsetChanged( + CefRefPtr<CefBrowser> browser, double x, double y) { + cef_render_handler_t* _struct = GetStruct(); + if (CEF_MEMBER_MISSING(_struct, on_scroll_offset_changed)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + _struct->on_scroll_offset_changed(_struct, + CefBrowserCppToC::Wrap(browser), + x, + y); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefRenderHandlerCToCpp::CefRenderHandlerCToCpp() { +} + +template<> cef_render_handler_t* CefCToCpp<CefRenderHandlerCToCpp, + CefRenderHandler, cef_render_handler_t>::UnwrapDerived(CefWrapperType type, + CefRenderHandler* c) { + NOTREACHED() << "Unexpected class type: " << type; + return NULL; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp<CefRenderHandlerCToCpp, + CefRenderHandler, cef_render_handler_t>::DebugObjCt = 0; +#endif + +template<> CefWrapperType CefCToCpp<CefRenderHandlerCToCpp, CefRenderHandler, + cef_render_handler_t>::kWrapperType = WT_RENDER_HANDLER; diff --git a/pool/shard007/C++/0094181_RpcRemoteCall.cpp b/pool/shard007/C++/0094181_RpcRemoteCall.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e85627b6e07155897187ffff635c8b206a6c37a --- /dev/null +++ b/pool/shard007/C++/0094181_RpcRemoteCall.cpp @@ -0,0 +1,83 @@ +/******************************************************************** + * 2014 - + * open source under Apache License Version 2.0 + ********************************************************************/ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "RpcRemoteCall.h" + +#include <google/protobuf/io/coded_stream.h> + +#include "Memory.h" +#include "ProtobufRpcEngine.pb.h" +#include "RpcCall.h" +#include "RpcContentWrapper.h" +#include "RpcHeader.pb.h" +#include "WriteBuffer.h" + +#define PING_CALL_ID -4 + +using namespace google::protobuf::io; + +namespace Hdfs { +namespace Internal { + +void RpcRemoteCall::serialize(const RpcProtocolInfo &protocol, + WriteBuffer &buffer) { + RpcRequestHeaderProto rpcHeader; + rpcHeader.set_callid(identity); + rpcHeader.set_clientid(clientId); + rpcHeader.set_retrycount(-1); + rpcHeader.set_rpckind(RPC_PROTOCOL_BUFFER); + rpcHeader.set_rpcop(RpcRequestHeaderProto_OperationProto_RPC_FINAL_PACKET); + RequestHeaderProto requestHeader; + requestHeader.set_methodname(call.getName()); + requestHeader.set_declaringclassprotocolname(protocol.getProtocol()); + requestHeader.set_clientprotocolversion(protocol.getVersion()); + RpcContentWrapper wrapper(&requestHeader, call.getRequest()); + int rpcHeaderLen = rpcHeader.ByteSize(); + int size = CodedOutputStream::VarintSize32(rpcHeaderLen) + rpcHeaderLen + + wrapper.getLength(); + buffer.writeBigEndian(size); + buffer.writeVarint32(rpcHeaderLen); + rpcHeader.SerializeToArray(buffer.alloc(rpcHeaderLen), rpcHeaderLen); + wrapper.writeTo(buffer); +} + +std::vector<char> RpcRemoteCall::GetPingRequest(const std::string &clientid) { + WriteBuffer buffer; + std::vector<char> retval; + RpcRequestHeaderProto pingHeader; + pingHeader.set_callid(PING_CALL_ID); + pingHeader.set_clientid(clientid); + pingHeader.set_retrycount(INVALID_RETRY_COUNT); + pingHeader.set_rpckind(RpcKindProto::RPC_PROTOCOL_BUFFER); + pingHeader.set_rpcop(RpcRequestHeaderProto_OperationProto_RPC_FINAL_PACKET); + int rpcHeaderLen = pingHeader.ByteSize(); + int size = CodedOutputStream::VarintSize32(rpcHeaderLen) + rpcHeaderLen; + buffer.writeBigEndian(size); + buffer.writeVarint32(rpcHeaderLen); + pingHeader.SerializeWithCachedSizesToArray( + reinterpret_cast<unsigned char *>(buffer.alloc(pingHeader.ByteSize()))); + retval.resize(buffer.getDataSize(0)); + memcpy(&retval[0], buffer.getBuffer(0), retval.size()); + return retval; +} + +} // namespace Internal +} // namespace Hdfs diff --git a/pool/shard007/C++/0094185_test_pool2d_op.cc b/pool/shard007/C++/0094185_test_pool2d_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..ee597f8465c218c0fb6648374c128cabf7b033fb --- /dev/null +++ b/pool/shard007/C++/0094185_test_pool2d_op.cc @@ -0,0 +1,72 @@ +/* Copyright (c) 2018 PaddlePaddle 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 <gtest/gtest.h> +#include <fstream> +#include "paddle/fluid/framework/op_registry.h" +#include "paddle/fluid/inference/tensorrt/convert/ut_helper.h" + +namespace paddle { +namespace inference { +namespace tensorrt { + +void test_pool2d(bool global_pooling, bool ceil_mode) { + framework::Scope scope; + std::unordered_set<std::string> parameters; + TRTConvertValidation validator(5, parameters, scope, 1 << 15); + + // The ITensor's Dims should not contain the batch size. + // So, the ITensor's Dims of input and output should be C * H * W. + validator.DeclInputVar("pool2d-X", nvinfer1::Dims3(3, 13, 14)); + if (global_pooling) + validator.DeclOutputVar("pool2d-Out", nvinfer1::Dims3(3, 1, 1)); + else if (ceil_mode) + validator.DeclOutputVar("pool2d-Out", nvinfer1::Dims3(3, 6, 7)); + else + validator.DeclOutputVar("pool2d-Out", nvinfer1::Dims3(3, 6, 6)); + + // Prepare Op description + framework::OpDesc desc; + desc.SetType("pool2d"); + desc.SetInput("X", {"pool2d-X"}); + desc.SetOutput("Out", {"pool2d-Out"}); + + std::vector<int> ksize({3, 3}); + std::vector<int> strides({2, 2}); + std::vector<int> paddings({0, 0}); + std::string pooling_t = "max"; + + desc.SetAttr("pooling_type", pooling_t); + desc.SetAttr("ksize", ksize); + desc.SetAttr("strides", strides); + desc.SetAttr("paddings", paddings); + desc.SetAttr("global_pooling", global_pooling); + desc.SetAttr("ceil_mode", ceil_mode); + + LOG(INFO) << "set OP"; + validator.SetOp(*desc.Proto()); + LOG(INFO) << "execute"; + + validator.Execute(3); +} + +TEST(Pool2dOpConverter, normal) { test_pool2d(false, false); } +TEST(Pool2dOpConverter, test_global_pooling) { test_pool2d(true, false); } + +TEST(Pool2dOpConverter, test_ceil_mode) { test_pool2d(false, true); } + +} // namespace tensorrt +} // namespace inference +} // namespace paddle + +USE_OP(pool2d); diff --git a/pool/shard007/C++/0094187_AIDistance.cpp b/pool/shard007/C++/0094187_AIDistance.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0c9e6b0ab5398a01221d3f4193aa8839b8eb142d --- /dev/null +++ b/pool/shard007/C++/0094187_AIDistance.cpp @@ -0,0 +1,27 @@ +// +// AIDistance.cpp +// FaceRecognizer +// +// Created by Efrain Astudillo on 1/18/14. +// Copyright (c) 2014 Efrain Astudillo. All rights reserved. +// + +#include "AIDistance.h" + + +_AIDistance::_AIDistance(std::string name){ + _name = name; +} +std::string _AIDistance::get_name(){ + return _name; +} + +// ========================================================================== + +AIEuclideanDistance::AIEuclideanDistance():_AIDistance("Euclidean Distance"){ + // initialize instance concrete +} + +double AIEuclideanDistance::compute(const Eigen::MatrixXd& P, const Eigen::MatrixXd& Q){ + return sqrt((P - Q).array().pow(2).sum()); +} \ No newline at end of file diff --git a/pool/shard007/C++/0094190_OGLConsole.cpp b/pool/shard007/C++/0094190_OGLConsole.cpp new file mode 100644 index 0000000000000000000000000000000000000000..70208807a0ec0a9477971b9b87f47ec11a0fac5c --- /dev/null +++ b/pool/shard007/C++/0094190_OGLConsole.cpp @@ -0,0 +1,274 @@ +#include "OGLConsole.h" + + +OGLConsole::OGLConsole(void) : DBConsole() +{ + //########## WINDOWS ####################### + + srand((int) time(NULL)); + + //########## OPENGL ###################### + + //-- +} + + +OGLConsole::~OGLConsole(void) +{ +} + +void OGLConsole::initOGL() { + int argc = 0; + char *pc = 0; + + glutInit(&argc, &pc); + + glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); + glutInitWindowSize(8 * BUFFER_W, 12 * BUFFER_H); + glutInitWindowPosition((glutGet(GLUT_SCREEN_WIDTH) - 8 * BUFFER_W) / 2, (glutGet(GLUT_SCREEN_HEIGHT) - 12 * BUFFER_H) / 2); + glutCreateWindow("Fight da Snake"); + + glewInit(); + + glOrtho(0, 8 * BUFFER_W, 12 * BUFFER_H, 0, 0, -100); + glEnable(GL_TEXTURE_2D); + + loadTextures(); +} + +void OGLConsole::writeToConsole(int c, int x, int y) +{ + // Do nothing +} + +void OGLConsole::showConsoleCursor(bool bShow) +{ + // Do nothing +} + +unsigned char OGLConsole::getKeyState() +{ + // Do nothing + return 0; +} + +long OGLConsole::getSystemCurrTimeMillis() +{ + auto time = std::chrono::system_clock::now(); + + auto since_epoch = time.time_since_epoch(); + + auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(since_epoch); + + return (long) millis.count(); +} + +void OGLConsole::doSystemSleep(long duration) { + Sleep(duration); +} + +void OGLConsole::setDimensions(short w, short h) +{ + // DO NOTHING ??? +} + +void OGLConsole::clearBuffer() { + DBConsole::clearBuffer(); +} + +void OGLConsole::swap() { + DBConsole::swap(); + + startRenderOGL(); + + //<RENDER OGL> + renderOGL(); + //</RENDER OGL> + + glutSwapBuffers(); +} + +void OGLConsole::startRenderOGL() { + glClearColor(0, 0, 0, 1); + glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); +} + +void OGLConsole::renderOGL() { + for (int x = 0; x < BUFFER_W; x++) { + for (int y = 0; y < BUFFER_H; y++) { + if (display[x][y] != ' ') { + renderOGLPos(x, y, display[x][y]); + } + } + } +} + +void OGLConsole::renderOGLPos(int x, int y, int chr) { + int dchar = chr % 255; + + GLdouble tx = dchar % 80; + GLdouble ty = dchar / 80; + + GLdouble x1 = (x+0) * 8; + GLdouble x2 = (x+1) * 8; + + GLdouble y1 = (y+0) * 12; + GLdouble y2 = (y+1) * 12; + + GLdouble tx1 = (tx+0) / 128.0; + GLdouble tx2 = (tx+1) / 128.0; + + GLdouble ty1 = 64 - (ty+0) / (16/3.0); + GLdouble ty2 = 64 - (ty+1) / (16/3.0); + + glColor3f(1, 1, 1); + glBindTexture(GL_TEXTURE_2D, chartextures); + + glBegin(GL_QUADS); + glTexCoord2d(tx1, ty1); glVertex3d(x1, y1, 0); + glTexCoord2d(tx1, ty2); glVertex3d(x1, y2, 0); + glTexCoord2d(tx2, ty2); glVertex3d(x2, y2, 0); + glTexCoord2d(tx2, ty1); glVertex3d(x2, y1, 0); + glEnd(); +} + +unsigned char* OGLConsole::loadBMPRaw(const unsigned char * rawdata, unsigned int outWidth, unsigned int outHeight, bool flipY){ + unsigned char header[54]; + + unsigned int imageSize = outWidth*outHeight*3; + unsigned char * data; + const unsigned char *datastart = rawdata + 54; + data = new byte[outWidth*outHeight*3]; + memcpy(header, rawdata, 54); + memcpy(data, datastart, imageSize); + + if ( header[0]!='B' || header[1]!='M' ){ printf("Not a correct BMP file\n"); return NULL;} + if ( *(int*)&(header[0x1E])!=0 ) {printf("Not a correct BMP file\n"); return NULL;} + if ( *(int*)&(header[0x1C])!=24 ) {printf("Not a correct BMP file\n"); return NULL;} + + return data; +} + +GLuint OGLConsole::LoadTextureRAW(int id, int w, int h) { + HMODULE hModule = GetModuleHandle(NULL); + HRSRC hResource = FindResource(hModule, MAKEINTRESOURCE(id), RT_RCDATA); + HGLOBAL hMemory = LoadResource(hModule, hResource); + DWORD dwSize = SizeofResource(hModule, hResource); + LPVOID lpAddress = LockResource(hMemory); + + unsigned char *bytes = new unsigned char[dwSize]; + memcpy(bytes, lpAddress, dwSize); + + + GLuint texture; + glGenTextures( 1, &texture ); + + glBindTexture(GL_TEXTURE_2D, texture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_BGR, GL_UNSIGNED_BYTE, loadBMPRaw(bytes, w, h, false)); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + + return texture; +} + +void OGLConsole::loadTextures() { + chartextures = LoadTextureRAW(101, 1024, 64); +} + +ActionListener *ogl_global_looplistener; +KeyEventListener *ogl_global_keylistener; + +void onMainLoopLoopCallback() { + ogl_global_looplistener->actionPerformed(0, -1); +} + +void onMainLoopKeyCallback(int key, int x, int y) { + if (key == (GLUT_KEY_UP)) { + ogl_global_keylistener->keyEventPerformed(KC_UP); + return; + } else if (key == (GLUT_KEY_DOWN)) { + ogl_global_keylistener->keyEventPerformed(KC_DOWN); + return; + } else if (key == (GLUT_KEY_LEFT)) { + ogl_global_keylistener->keyEventPerformed(KC_LEFT); + return; + } else if (key == (GLUT_KEY_RIGHT)) { + ogl_global_keylistener->keyEventPerformed(KC_RIGHT); + return; + } else if (key >= GLUT_KEY_F1 && key <= GLUT_KEY_F12) { + ogl_global_keylistener->keyEventPerformed((key - GLUT_KEY_F1) + KC_F1); + return; + } +} + +void onMainLoopKeyCallbackASCII(unsigned char key, int x, int y) { + if (key == ' ') { + ogl_global_keylistener->keyEventPerformed(KC_SPACE); + return; + } else if (key == 27) { + ogl_global_keylistener->keyEventPerformed(KC_ESCAPE); + return; + } else if (key == 8) { + ogl_global_keylistener->keyEventPerformed(KC_BACKSPACE); + return; + } else if(key >= 'A' && key <= 'Z') { + ogl_global_keylistener->keyEventPerformed(key); + } else if(key >= 'a' && key <= 'z'){ + ogl_global_keylistener->keyEventPerformed(key - 'a' + 'A'); + } else if(key == 13){ + ogl_global_keylistener->keyEventPerformed(KC_ENTER); + } +} + +void OGLConsole::startLoop(ActionListener *looplistener, KeyEventListener *keyListener) { + ogl_global_looplistener = looplistener; + ogl_global_keylistener = keyListener; + + glutSpecialFunc(onMainLoopKeyCallback); + glutKeyboardFunc(onMainLoopKeyCallbackASCII); + glutIdleFunc(onMainLoopLoopCallback); + glutMainLoop(); +} + + +bool* OGLConsole::getBoolImageResource(int id) { + HMODULE hModule = GetModuleHandle(NULL); + HRSRC hResource = FindResource(hModule, MAKEINTRESOURCE(id), RT_RCDATA); + HGLOBAL hMemory = LoadResource(hModule, hResource); + DWORD dwSize = SizeofResource(hModule, hResource); + LPVOID lpAddress = LockResource(hMemory); + + unsigned char *bytes = new unsigned char[dwSize]; + memcpy(bytes, lpAddress, dwSize); + + unsigned char header[54]; + memcpy(header, bytes, 54); + + int width = *(int*)&(header[0x12]); + int height = *(int*)&(header[0x16]); + + unsigned int imageSize = width*height*3; + unsigned char * data; + const unsigned char *datastart = bytes + 54; + data = new byte[width*height*3]; + memcpy(data, datastart, imageSize); + + bool* result = (bool*)malloc(width*height); + + for (int i = 0; i < width*height; i++) + { + result[i] = (data[i*3] == 0); + } + + if ( header[0]!='B' || header[1]!='M' ){ printf("Not a correct BMP file\n"); return NULL;} + if ( *(int*)&(header[0x1E])!=0 ) {printf("Not a correct BMP file\n"); return NULL;} + if ( *(int*)&(header[0x1C])!=24 ) {printf("Not a correct BMP file\n"); return NULL;} + + return result; +} + +void OGLConsole::hideConsole() { + HWND hWnd = GetConsoleWindow(); + ShowWindow( hWnd, SW_HIDE ); +} \ No newline at end of file diff --git a/pool/shard007/C++/0094191_cros_disks_client_unittest.cc b/pool/shard007/C++/0094191_cros_disks_client_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..e52eba08341611b8ddf284d4e30eb319821788f3 --- /dev/null +++ b/pool/shard007/C++/0094191_cros_disks_client_unittest.cc @@ -0,0 +1,202 @@ +// Copyright 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 "chromeos/dbus/cros_disks/cros_disks_client.h" + +#include <stdint.h> + +#include <memory> + +#include "dbus/message.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/cros_system_api/dbus/service_constants.h" + +namespace chromeos { + +namespace { + +const char kMountLabel[] = "/tmp/cros-disks-test"; + +// Appends a boolean entry to a dictionary of type "a{sv}" +void AppendBoolDictEntry(dbus::MessageWriter* array_writer, + const std::string& key, + bool value) { + dbus::MessageWriter entry_writer(NULL); + array_writer->OpenDictEntry(&entry_writer); + entry_writer.AppendString(key); + entry_writer.AppendVariantOfBool(value); + array_writer->CloseContainer(&entry_writer); +} + +// Appends a string entry to a dictionary of type "a{sv}" +void AppendStringDictEntry(dbus::MessageWriter* array_writer, + const std::string& key, + const std::string& value) { + dbus::MessageWriter entry_writer(NULL); + array_writer->OpenDictEntry(&entry_writer); + entry_writer.AppendString(key); + entry_writer.AppendVariantOfString(value); + array_writer->CloseContainer(&entry_writer); +} + +} // namespace + +TEST(CrosDisksClientTest, DiskInfo) { + const std::string kDeviceFile = "/dev/sdb1"; + const bool kDeviceIsDrive = true; + const bool kDeviceIsMediaAvailable = true; + const bool kDeviceIsMounted = true; + const bool kDeviceIsOnBootDevice = true; + const bool kDeviceIsOnRemovableDevice = true; + const bool kDeviceIsReadOnly = true; + const uint32_t kDeviceMediaType = cros_disks::DEVICE_MEDIA_SD; + const std::string kMountPath = "/media/removable/UNTITLED"; + const bool kDevicePresentationHide = false; + const uint64_t kDeviceSize = 16005464064; + const std::string kDriveModel = "DriveModel"; + const std::string kIdLabel = "UNTITLED"; + const std::string kIdUuid = "XXXX-YYYY"; + const std::string kProductId = "1234"; + const std::string kProductName = "Product Name"; + const std::string kVendorId = "0000"; + const std::string kVendorName = "Vendor Name"; + const std::string kFileSystemType = "exfat"; + const bool kIsAutoMountable = true; + + // Construct a fake response of GetDeviceProperties(). + std::unique_ptr<dbus::Response> response(dbus::Response::CreateEmpty()); + { + dbus::MessageWriter writer(response.get()); + dbus::MessageWriter array_writer(NULL); + writer.OpenArray("{sv}", &array_writer); + + AppendStringDictEntry(&array_writer, cros_disks::kDeviceFile, kDeviceFile); + AppendBoolDictEntry(&array_writer, cros_disks::kDeviceIsDrive, + kDeviceIsDrive); + AppendBoolDictEntry(&array_writer, cros_disks::kDeviceIsMediaAvailable, + kDeviceIsMediaAvailable); + AppendBoolDictEntry(&array_writer, cros_disks::kDeviceIsMounted, + kDeviceIsMounted); + AppendBoolDictEntry(&array_writer, cros_disks::kDeviceIsOnBootDevice, + kDeviceIsOnBootDevice); + AppendBoolDictEntry(&array_writer, cros_disks::kDeviceIsOnRemovableDevice, + kDeviceIsOnRemovableDevice); + AppendBoolDictEntry(&array_writer, cros_disks::kDeviceIsReadOnly, + kDeviceIsReadOnly); + AppendBoolDictEntry(&array_writer, cros_disks::kIsAutoMountable, + kIsAutoMountable); + { + dbus::MessageWriter entry_writer(NULL); + array_writer.OpenDictEntry(&entry_writer); + entry_writer.AppendString(cros_disks::kDeviceMediaType); + entry_writer.AppendVariantOfUint32(kDeviceMediaType); + array_writer.CloseContainer(&entry_writer); + } + { + std::vector<std::string> mounted_paths; + mounted_paths.push_back(kMountPath); + + dbus::MessageWriter entry_writer(NULL); + array_writer.OpenDictEntry(&entry_writer); + entry_writer.AppendString(cros_disks::kDeviceMountPaths); + dbus::MessageWriter variant_writer(NULL); + entry_writer.OpenVariant("as", &variant_writer); + variant_writer.AppendArrayOfStrings(mounted_paths); + entry_writer.CloseContainer(&variant_writer); + array_writer.CloseContainer(&entry_writer); + } + AppendBoolDictEntry(&array_writer, cros_disks::kDevicePresentationHide, + kDevicePresentationHide); + { + dbus::MessageWriter entry_writer(NULL); + array_writer.OpenDictEntry(&entry_writer); + entry_writer.AppendString(cros_disks::kDeviceSize); + entry_writer.AppendVariantOfUint64(kDeviceSize); + array_writer.CloseContainer(&entry_writer); + } + AppendStringDictEntry(&array_writer, cros_disks::kDriveModel, kDriveModel); + AppendStringDictEntry(&array_writer, cros_disks::kIdLabel, kIdLabel); + AppendStringDictEntry(&array_writer, cros_disks::kIdUuid, kIdUuid); + AppendStringDictEntry(&array_writer, cros_disks::kProductId, kProductId); + AppendStringDictEntry(&array_writer, cros_disks::kProductName, + kProductName); + AppendStringDictEntry(&array_writer, cros_disks::kVendorId, kVendorId); + AppendStringDictEntry(&array_writer, cros_disks::kVendorName, kVendorName); + AppendStringDictEntry(&array_writer, cros_disks::kFileSystemType, + kFileSystemType); + + writer.CloseContainer(&array_writer); + } + + // Construct DiskInfo. + DiskInfo result(kDeviceFile, response.get()); + EXPECT_EQ(kDeviceFile, result.device_path()); + EXPECT_EQ(kDeviceIsDrive, result.is_drive()); + EXPECT_EQ(kDeviceIsReadOnly, result.is_read_only()); + // Use EXPECT_TRUE(kDevicePresentationHide == result.is_hidden()) instead of + // EXPECT_EQ(kDevicePresentationHide, result.is_hidden()) as gcc 4.7 issues + // the following warning on EXPECT_EQ(false, x), which is turned into an error + // with -Werror=conversion-null: + // + // converting 'false' to pointer type for argument 1 of + // 'char testing::internal::IsNullLiteralHelper(testing::internal::Secret*)' + EXPECT_TRUE(kDevicePresentationHide == result.is_hidden()); + EXPECT_EQ(kDeviceIsMediaAvailable, result.has_media()); + EXPECT_EQ(kDeviceIsOnBootDevice, result.on_boot_device()); + EXPECT_EQ(kDeviceIsOnRemovableDevice, result.on_removable_device()); + EXPECT_EQ(kDeviceFile, result.file_path()); + EXPECT_EQ(kVendorId, result.vendor_id()); + EXPECT_EQ(kVendorName, result.vendor_name()); + EXPECT_EQ(kProductId, result.product_id()); + EXPECT_EQ(kProductName, result.product_name()); + EXPECT_EQ(kDriveModel, result.drive_label()); + EXPECT_EQ(kIdLabel, result.label()); + EXPECT_EQ(kIdUuid, result.uuid()); + EXPECT_EQ(kDeviceSize, result.total_size_in_bytes()); + EXPECT_EQ(DEVICE_TYPE_SD, result.device_type()); + EXPECT_EQ(kMountPath, result.mount_path()); + EXPECT_EQ(kFileSystemType, result.file_system_type()); + EXPECT_EQ(kIsAutoMountable, result.is_auto_mountable()); +} + +TEST(CrosDisksClientTest, ComposeMountOptions) { + std::string kExpectedMountLabelOption = + std::string("mountlabel=") + kMountLabel; + std::vector<std::string> rw_mount_options = + CrosDisksClient::ComposeMountOptions({}, kMountLabel, + MOUNT_ACCESS_MODE_READ_WRITE, + REMOUNT_OPTION_MOUNT_NEW_DEVICE); + ASSERT_EQ(2U, rw_mount_options.size()); + EXPECT_EQ("rw", rw_mount_options[0]); + EXPECT_EQ(kExpectedMountLabelOption, rw_mount_options[1]); + + std::vector<std::string> ro_mount_options = + CrosDisksClient::ComposeMountOptions({}, kMountLabel, + MOUNT_ACCESS_MODE_READ_ONLY, + REMOUNT_OPTION_MOUNT_NEW_DEVICE); + ASSERT_EQ(2U, ro_mount_options.size()); + EXPECT_EQ("ro", ro_mount_options[0]); + EXPECT_EQ(kExpectedMountLabelOption, ro_mount_options[1]); + + std::vector<std::string> remount_mount_options = + CrosDisksClient::ComposeMountOptions( + {}, kMountLabel, MOUNT_ACCESS_MODE_READ_WRITE, + REMOUNT_OPTION_REMOUNT_EXISTING_DEVICE); + ASSERT_EQ(3U, remount_mount_options.size()); + EXPECT_EQ("rw", remount_mount_options[0]); + EXPECT_EQ("remount", remount_mount_options[1]); + EXPECT_EQ(kExpectedMountLabelOption, remount_mount_options[2]); + + std::vector<std::string> custom_mount_options = + CrosDisksClient::ComposeMountOptions({"foo", "bar=baz"}, kMountLabel, + MOUNT_ACCESS_MODE_READ_WRITE, + REMOUNT_OPTION_MOUNT_NEW_DEVICE); + ASSERT_EQ(4U, custom_mount_options.size()); + EXPECT_EQ("foo", custom_mount_options[0]); + EXPECT_EQ("bar=baz", custom_mount_options[1]); + EXPECT_EQ("rw", custom_mount_options[2]); + EXPECT_EQ(kExpectedMountLabelOption, custom_mount_options[3]); +} + +} // namespace chromeos diff --git a/pool/shard007/C++/0094206_berryUtil.cpp b/pool/shard007/C++/0094206_berryUtil.cpp new file mode 100644 index 0000000000000000000000000000000000000000..61581c3668f6e1920b6c63a24742458a7d1e043a --- /dev/null +++ b/pool/shard007/C++/0094206_berryUtil.cpp @@ -0,0 +1,35 @@ +/*=================================================================== + +BlueBerry Platform + +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 "berryUtil.h" + +#include "berryShell.h" +#include "berryPlatformUI.h" + +namespace berry { + +SmartPointer<Shell> Util::GetShellToParentOn() +{ + IWorkbench* workbench = PlatformUI::GetWorkbench(); + IWorkbenchWindow::Pointer activeWindow = workbench->GetActiveWorkbenchWindow(); + IWorkbenchWindow::Pointer windowToParentOn = activeWindow.IsNull() ? + (workbench->GetWorkbenchWindowCount() > 0 ? + workbench->GetWorkbenchWindows()[0] : IWorkbenchWindow::Pointer(nullptr)) + : activeWindow; + return windowToParentOn.IsNull() ? Shell::Pointer(nullptr) : activeWindow->GetShell(); +} + +} diff --git a/pool/shard007/C++/0094207_ReturnKickBall.cpp b/pool/shard007/C++/0094207_ReturnKickBall.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6076208fb4153b831e06cdcce5399649111b4862 --- /dev/null +++ b/pool/shard007/C++/0094207_ReturnKickBall.cpp @@ -0,0 +1,119 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * +* BSD 3-Clause License +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * +Code by Cassius Fiorin - cafiorin@gmail.com +http://pinballhomemade.blogspot.com.br +* * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "ReturnKickBall.h" +#include "Pinball.h" +#include "PinballObject.h" +#include "Input.h" +#include "Output.h" +#include "Timer.h" +#include "LedControl.h" + +//-------------------------------------------------------// +ReturnKickBall::ReturnKickBall(uint8_t portNumberInput, uint8_t portNumberOutput,uint8_t led) : PinballObject() +//-------------------------------------------------------// +{ + #ifdef DEBUGMESSAGESCREATION + LogMessage(F("ReturnKickBall Constructor")); + #endif + + m_led = led; + + m_input1 = new Input(portNumberInput,this); + m_output = new Output(portNumberOutput); + + m_returnBallOn = true; + m_timerBlinkLed = new Timer(400, this, TimerType::continuous); + m_timerBlinkLed->Disable(); +} + +//-------------------------------------------------------// +bool ReturnKickBall::Init() +//-------------------------------------------------------// +{ + if (m_Pinball->GetStatus() == StatusPinball::playingmode) + { + m_returnBallOn = true; + m_timerBlinkLed->Disable(); + LedControl *ledControl = m_Pinball->GetLedControl(); + if (ledControl != NULL) + { + ledControl->TurnOn(m_led); + } + } + return true; +} + +//-------------------------------------------------------// +ReturnKickBall::~ReturnKickBall() +//-------------------------------------------------------// +{ + #ifdef DEBUGMESSAGESCREATION + LogMessage(F("ReturnKickBall Destructor")); + #endif + /* + delete m_timerBlinkLed; + delete m_input1; + delete m_output; + */ +} + +//-------------------------------------------------------// +void ReturnKickBall::SetReturnBall(bool returnBallOn) +//-------------------------------------------------------// +{ + m_returnBallOn = returnBallOn; + if (!m_returnBallOn) + { + m_timerBlinkLed->Start(); + } + else + { + m_timerBlinkLed->Disable(); + LedControl *ledControl = m_Pinball->GetLedControl(); + if (ledControl != NULL) + { + ledControl->TurnOn(m_led); + } + } +} + +//-------------------------------------------------------// +bool ReturnKickBall::NotifyEvent(Object *sender, uint8_t event, uint8_t value) +//-------------------------------------------------------// +{ + #ifdef DEBUGMESSAGES + LogMessage(F("ReturnKickBall::NotifyEvent")); + #endif + + if (event == EVENT_EDGEPOSITIVE) + { + if (m_returnBallOn) + { + m_output->TurnOnByTimer(TIME_COIL_ON); + } + m_Pinball->NotifyEvent(sender, event, value); + return true; + } + else if (event == EVENT_TIMEISOVER) + { + if (m_Pinball->IsPlaying()) + { + LedControl *ledControl = m_Pinball->GetLedControl(); + if (ledControl != NULL) + { + if (ledControl->IsTurn(m_led)) + ledControl->TurnOff(m_led); + else + ledControl->TurnOn(m_led); + } + } + + return true; + } + return false; +} diff --git a/pool/shard007/C++/0094208_pop.pass.cpp b/pool/shard007/C++/0094208_pop.pass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..40b09f1e79a990918d325d2ac9faf688607de249 --- /dev/null +++ b/pool/shard007/C++/0094208_pop.pass.cpp @@ -0,0 +1,93 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// UNSUPPORTED: c++03 + +// <filesystem> + +// class recursive_directory_iterator + +// void pop(); +// void pop(error_code& ec); + +#include "filesystem_include.h" +#include <set> +#include <cassert> + +#include "test_macros.h" +#include "rapid-cxx-test.h" +#include "filesystem_test_helper.h" + +using namespace fs; + +TEST_SUITE(recursive_directory_iterator_pop_tests) + +TEST_CASE(signature_tests) +{ + recursive_directory_iterator it{}; ((void)it); + std::error_code ec; ((void)ec); + ASSERT_NOT_NOEXCEPT(it.pop()); + ASSERT_NOT_NOEXCEPT(it.pop(ec)); // may require allocation or other things +} + +// NOTE: Since the order of iteration is unspecified we use a list of +// seen files at each depth to determine the new depth after a 'pop()' operation. +TEST_CASE(test_depth) +{ + static_test_env static_env; + const recursive_directory_iterator endIt{}; + + auto& DE0 = static_env.DirIterationList; + std::set<path> notSeenDepth0(DE0.begin(), DE0.end()); + + auto& DE1 = static_env.DirIterationListDepth1; + std::set<path> notSeenDepth1(DE1.begin(), DE1.end()); + + std::error_code ec; + recursive_directory_iterator it(static_env.Dir, ec); + TEST_REQUIRE(it != endIt); + TEST_CHECK(it.depth() == 0); + + while (it.depth() != 2) { + if (it.depth() == 0) + notSeenDepth0.erase(it->path()); + else + notSeenDepth1.erase(it->path()); + ++it; + TEST_REQUIRE(it != endIt); + } + + while (true) { + auto set_ec = std::make_error_code(std::errc::address_in_use); + it.pop(set_ec); + TEST_REQUIRE(!set_ec); + + if (it == endIt) { + // We must have seen every entry at depth 0 and 1. + TEST_REQUIRE(notSeenDepth0.empty() && notSeenDepth1.empty()); + break; + } + else if (it.depth() == 1) { + // If we popped to depth 1 then there must be unseen entries + // at this level. + TEST_REQUIRE(!notSeenDepth1.empty()); + TEST_CHECK(notSeenDepth1.count(it->path())); + notSeenDepth1.clear(); + } + else if (it.depth() == 0) { + // If we popped to depth 0 there must be unseen entries at this + // level. There should also be no unseen entries at depth 1. + TEST_REQUIRE(!notSeenDepth0.empty()); + TEST_REQUIRE(notSeenDepth1.empty()); + TEST_CHECK(notSeenDepth0.count(it->path())); + notSeenDepth0.clear(); + } + } +} + +TEST_SUITE_END() diff --git a/pool/shard007/C++/0094213_validate_code_test.cc b/pool/shard007/C++/0094213_validate_code_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..b7f1594f8beeb602ce3e7707c11b450d9518efab --- /dev/null +++ b/pool/shard007/C++/0094213_validate_code_test.cc @@ -0,0 +1,69 @@ +// +// Copyright 2019 WebAssembly Community Group participants +// +// 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 "gtest/gtest.h" +#include "test/binary/constants.h" +#include "test/valid/test_utils.h" +#include "wasp/base/features.h" +#include "wasp/valid/valid_ctx.h" +#include "wasp/valid/validate.h" + +using namespace ::wasp; +using namespace ::wasp::binary; +using namespace ::wasp::binary::test; +using namespace ::wasp::valid; +using namespace ::wasp::valid::test; + +TEST(ValidateCodeTest, BeginCode) { + TestErrors errors; + ValidCtx ctx{errors}; + ctx.types.push_back(DefinedType{FunctionType{}}); + ctx.defined_type_count = 1; + ctx.functions.push_back(Function{0}); + EXPECT_TRUE(BeginCode(ctx, Location{})); +} + +TEST(ValidateCodeTest, BeginCode_CodeIndexOOB) { + TestErrors errors; + ValidCtx ctx{errors}; + ctx.types.push_back(DefinedType{FunctionType{}}); + ctx.functions.push_back(Function{0}); + ctx.code_count = 1; + EXPECT_FALSE(BeginCode(ctx, Location{})); +} + +TEST(ValidateCodeTest, BeginCode_TypeIndexOOB) { + TestErrors errors; + ValidCtx ctx{errors}; + ctx.types.push_back(DefinedType{FunctionType{}}); + ctx.functions.push_back(Function{1}); + EXPECT_FALSE(BeginCode(ctx, Location{})); +} + +TEST(ValidateCodeTest, BeginCode_NonFunctionType) { + TestErrors errors; + ValidCtx ctx{errors}; + ctx.types.push_back(DefinedType{StructType{}}); + ctx.defined_type_count = 1; + ctx.functions.push_back(Function{0}); + EXPECT_FALSE(BeginCode(ctx, Location{})); +} + +TEST(ValidateCodeTest, Locals) { + TestErrors errors; + ValidCtx ctx{errors}; + EXPECT_TRUE(Validate(ctx, Locals{10, VT_I32}, RequireDefaultable::Yes)); +} diff --git a/pool/shard007/C++/0094215_unittest.eventhandler.cpp b/pool/shard007/C++/0094215_unittest.eventhandler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ad446ae70f805271adcd3a86d894996362d4761c --- /dev/null +++ b/pool/shard007/C++/0094215_unittest.eventhandler.cpp @@ -0,0 +1,60 @@ +#include "gtest/gtest.h" + +#include "engine.core/event_handler.h" + +class EventHandlerTest : public testing::Test +{ +public: + + EventHandlerTest() + { + } + + void Callback(void* /*sender*/, int& d) + { + d = 0x2; + } +}; + +void staticTest(void* /*s*/, int& d) +{ + d = 0x4; +} + +TEST_F(EventHandlerTest, Events) +{ + // Lambda + event_handler<int&> handler; + auto lambda = [](void*, int& d) { d = 0x6; }; + auto functionHandle = handler += lambda; + + int value = 0; + handler.Invoke(this, value); + EXPECT_EQ(value, 0x6); + + handler -= functionHandle; + + // Member function + using namespace std::placeholders; + + auto memberFunction = std::bind(&EventHandlerTest::Callback, this, _1, _2); + functionHandle = handler += memberFunction; + + value = 0; + handler.Invoke(this, value); + EXPECT_EQ(value, 0x2); + + handler -= functionHandle; + + + // Static function + functionHandle = handler += &staticTest; + + value = 0; + handler.Invoke(this, value); + + EXPECT_EQ(value, 0x4); + + handler -= functionHandle; + +} diff --git a/pool/shard007/C++/0094217_pace.cpp b/pool/shard007/C++/0094217_pace.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9e8679a1d050e13da53738f2ebbdb070d6d26d7c --- /dev/null +++ b/pool/shard007/C++/0094217_pace.cpp @@ -0,0 +1,226 @@ + +#include "id_func.h" +#include "list_graph.h" +#include "multi_arc.h" +#include "sort_arc.h" +#include "chain.h" +#include "flow_cutter.h" +#include "greedy_order.h" + +#include "node_flow_cutter.h" +#include "contraction_graph.h" +#include "cch_order.h" +#include "tree_decomposition.h" +#include "separator.h" +#include <iostream> +#include <limits> +#include <signal.h> +#include <stdlib.h> +#include <string.h> +#include <string> +#include <sstream> +#ifdef PARALLELIZE +#include <omp.h> +#include <atomic> +#endif + +#include <sys/time.h> +#include <unistd.h> +using namespace std; + +ArrayIDIDFunc tail, head; +const char*volatile best_decomposition = 0; +int best_bag_size = numeric_limits<int>::max(); + +void ignore_return_value(int){} + +int compute_max_bag_size(const ArrayIDIDFunc&order){ + auto inv_order = inverse_permutation(order); + int current_tail = -1; + int current_tail_up_deg = 0; + int max_up_deg = 0; + compute_chordal_supergraph( + chain(tail, inv_order), chain(head, inv_order), + [&](int x, int y){ + if(current_tail != x){ + current_tail = x; + max_to(max_up_deg, current_tail_up_deg); + current_tail_up_deg = 0; + } + ++current_tail_up_deg; + } + ); + return max_up_deg+1; +} + +unsigned long long get_milli_time(){ + struct timeval tv; + gettimeofday(&tv, NULL); + return (unsigned long long)(tv.tv_sec) * 1000 + + (unsigned long long)(tv.tv_usec) / 1000; +} + +const char*compute_decomposition(const ArrayIDIDFunc&order){ + ostringstream out; + print_tree_decompostion(out, tail, head, move(order)); + char*buf = new char[out.str().length()+1]; + memcpy(buf, out.str().c_str(), out.str().length()+1); + return buf; +} + +void test_new_order(ArrayIDIDFunc order){ + int x = compute_max_bag_size(order); + #ifdef PARALLELIZE + #pragma omp critical + #endif + { + if(x < best_bag_size){ + best_bag_size = x; + const char*old_decomposition = best_decomposition; + best_decomposition = compute_decomposition(move(order)); + delete[]old_decomposition; + { + string msg = "c status "+to_string(best_bag_size)+" "+to_string(get_milli_time())+"\n"; + ignore_return_value(write(STDOUT_FILENO, msg.data(), msg.length())); + } + } + } +} + +char no_decomposition_message[] = "c info programm was aborted before any decomposition was computed\n"; + +#ifdef PARALLELIZE +volatile atomic_flag only_one_thread_in_signal_handler = ATOMIC_FLAG_INIT; +#endif + +void signal_handler(int) +{ + #ifdef PARALLELIZE + while (only_one_thread_in_signal_handler.test_and_set()) {} + #endif + + const char*x = best_decomposition; + if(x != 0) + ignore_return_value(write(STDOUT_FILENO, x, strlen(x))); + else + ignore_return_value(write(STDOUT_FILENO, no_decomposition_message, sizeof(no_decomposition_message))); + + _Exit(EXIT_SUCCESS); +} + +/* +int main(int argc, char * argv[]){ + string file_name = "-"; + if(argc == 2) + file_name = argv[1]; + auto g = uncached_load_pace_graph(file_name); + tail = std::move(g.tail); + head = std::move(g.head); + + int random_seed = 0; + + if(argc == 3){ + if(string(argv[1]) == "-s"){ + random_seed = atoi(argv[2]); + } + } + std::minstd_rand rand_gen; + rand_gen.seed( + random_seed + ); + + flow_cutter::Config config; + config.cutter_count = 1; + config.random_seed = rand_gen(); + + ++config.cutter_count; + test_new_order(cch_order::compute_cch_graph_order(tail, head, flow_cutter::ComputeSeparator(config))); + */ + /* + for(int i=0;i<2;++i){ + config.random_seed = rand_gen(); + if(i % 32 == 0) + ++config.cutter_count; + test_new_order(cch_order::compute_cch_graph_order(tail, head, flow_cutter::ComputeSeparator(config))); + cout << "step3" << endl; + } + */ + /* + const char*x = best_decomposition; + if(x != 0) + ignore_return_value(write(STDOUT_FILENO, x, strlen(x))); + else + ignore_return_value(write(STDOUT_FILENO, no_decomposition_message, sizeof(no_decomposition_message))); +} +*/ + + +int main(int argc, char*argv[]){ + signal(SIGTERM, signal_handler); + signal(SIGINT, signal_handler); + + signal(SIGSEGV, signal_handler); + try{ + { + string file_name = "-"; + if(argc == 2) + file_name = argv[1]; + auto g = uncached_load_pace_graph(file_name); + tail = std::move(g.tail); + head = std::move(g.head); + } + + int random_seed = 0; + + if(argc == 3){ + if(string(argv[1]) == "-s"){ + random_seed = atoi(argv[2]); + } + } + + #ifdef PARALLELIZE + #pragma omp parallel + #endif + { + try{ + #ifdef PARALLELIZE + #pragma omp sections nowait + #endif + + { + test_new_order(compute_greedy_min_degree_order(tail, head)); + #ifdef PARALLELIZE + #pragma omp section + #endif + test_new_order(compute_greedy_min_shortcut_order(tail, head)); + } + + std::minstd_rand rand_gen; + rand_gen.seed( + random_seed + #ifdef PARALLELIZE + + omp_get_thread_num() + #endif + ); + + flow_cutter::Config config; + config.cutter_count = 1; + config.random_seed = rand_gen(); + + for(int i=0;;++i){ + config.random_seed = rand_gen(); + if(i % 32 == 0) + ++config.cutter_count; + + test_new_order(cch_order::compute_cch_graph_order(tail, head, flow_cutter::ComputeSeparator(config))); + + } + }catch(...){ + signal_handler(0); + } + } + }catch(...){ + signal_handler(0); + } +} + diff --git a/pool/shard007/C++/0094220_TestLemmatizerCOM.cpp b/pool/shard007/C++/0094220_TestLemmatizerCOM.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f087603f27f8b675fdf4f67db84447453c3fc517 --- /dev/null +++ b/pool/shard007/C++/0094220_TestLemmatizerCOM.cpp @@ -0,0 +1,51 @@ +//================================================================ +// ===== COM Test Example for Dialing Lemmatizer (www.aot.ru) == +// ===== Author: Alexey Sokirko, sokirko@yandex.ru, 2003 ======= +//================================================================ + +#include <stdio.h> +#include <comdef.h> +#import "../../bin/Lemmatizer.tlb" + +int main(int argc, char *argv[]) +{ + ::CoInitialize(NULL); + + // creating and loading Russian dictionary + LEMMATIZERLib::ILemmatizerPtr piLemmatizer; + HRESULT hr = piLemmatizer.CreateInstance(__uuidof(LEMMATIZERLib::LemmatizerRussian)); + if (FAILED(hr)) + { + fprintf(stderr, "Fatal Error: Lemmatizer creation failed"); + return 1; + } + // loading dictionary into the memory + hr = piLemmatizer->LoadDictionariesRegistry(); + if (FAILED(hr)) + { + printf("Fatal Error: Lemmatizer loading failed"); + return false; + } + + + // lemmatizing a word + { + LEMMATIZERLib::IParadigmCollectionPtr piParadigmCollection = piLemmatizer->CreateParadigmCollectionFromForm("ìàìà", FALSE, FALSE); + + // print possible lemmas + for (int j=0; j < piParadigmCollection->Count; j++) + { + _bstr_t Lemma = _bstr_t(piParadigmCollection->Item[j]->Norm); + printf ("Lemma %i = \"%s\"\n", j+1, (const char*)Lemma); + }; + } + + + + + // destroy the dictionary + piLemmatizer = 0; + + ::CoUninitialize(); + +} diff --git a/pool/shard007/C++/0094227_runtimeService.cpp b/pool/shard007/C++/0094227_runtimeService.cpp new file mode 100644 index 0000000000000000000000000000000000000000..be2108a86c7ff74117fa76871660394c29c90887 --- /dev/null +++ b/pool/shard007/C++/0094227_runtimeService.cpp @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "precompiled.hpp" +#include "classfile/classLoader.hpp" +#include "logging/log.hpp" +#include "logging/logStream.hpp" +#include "runtime/vm_version.hpp" +#include "services/attachListener.hpp" +#include "services/management.hpp" +#include "services/runtimeService.hpp" +#include "utilities/dtrace.hpp" +#include "utilities/exceptions.hpp" +#include "utilities/macros.hpp" + +#if INCLUDE_MANAGEMENT +PerfCounter* RuntimeService::_sync_time_ticks = NULL; +PerfCounter* RuntimeService::_total_safepoints = NULL; +PerfCounter* RuntimeService::_safepoint_time_ticks = NULL; +PerfCounter* RuntimeService::_application_time_ticks = NULL; + +void RuntimeService::init() { + if (UsePerfData) { + EXCEPTION_MARK; + + _sync_time_ticks = + PerfDataManager::create_counter(SUN_RT, "safepointSyncTime", + PerfData::U_Ticks, CHECK); + + _total_safepoints = + PerfDataManager::create_counter(SUN_RT, "safepoints", + PerfData::U_Events, CHECK); + + _safepoint_time_ticks = + PerfDataManager::create_counter(SUN_RT, "safepointTime", + PerfData::U_Ticks, CHECK); + + _application_time_ticks = + PerfDataManager::create_counter(SUN_RT, "applicationTime", + PerfData::U_Ticks, CHECK); + + + // create performance counters for jvm_version and its capabilities + PerfDataManager::create_constant(SUN_RT, "jvmVersion", PerfData::U_None, + (jlong) VM_Version::jvm_version(), CHECK); + + // The capabilities counter is a binary representation of the VM capabilities in string. + // This string respresentation simplifies the implementation of the client side + // to parse the value. + char capabilities[65]; + size_t len = sizeof(capabilities); + memset((void*) capabilities, '0', len); + capabilities[len-1] = '\0'; + capabilities[0] = AttachListener::is_attach_supported() ? '1' : '0'; +#if INCLUDE_SERVICES + capabilities[1] = '1'; +#endif // INCLUDE_SERVICES + PerfDataManager::create_string_constant(SUN_RT, "jvmCapabilities", + capabilities, CHECK); + } +} + +void RuntimeService::record_safepoint_begin(jlong app_ticks) { + HS_PRIVATE_SAFEPOINT_BEGIN(); + if (UsePerfData) { + _total_safepoints->inc(); + _application_time_ticks->inc(app_ticks); + } +} + +void RuntimeService::record_safepoint_synchronized(jlong sync_ticks) { + if (UsePerfData) { + _sync_time_ticks->inc(sync_ticks); + } +} + +void RuntimeService::record_safepoint_end(jlong safepoint_ticks) { + HS_PRIVATE_SAFEPOINT_END(); + if (UsePerfData) { + _safepoint_time_ticks->inc(safepoint_ticks); + } +} + +jlong RuntimeService::safepoint_sync_time_ms() { + return UsePerfData ? + Management::ticks_to_ms(_sync_time_ticks->get_value()) : -1; +} + +jlong RuntimeService::safepoint_count() { + return UsePerfData ? + _total_safepoints->get_value() : -1; +} +jlong RuntimeService::safepoint_time_ms() { + return UsePerfData ? + Management::ticks_to_ms(_safepoint_time_ticks->get_value()) : -1; +} + +jlong RuntimeService::application_time_ms() { + return UsePerfData ? + Management::ticks_to_ms(_application_time_ticks->get_value()) : -1; +} + +#endif // INCLUDE_MANAGEMENT diff --git a/pool/shard007/C++/0094228_ShaderProgramCatalog.cpp b/pool/shard007/C++/0094228_ShaderProgramCatalog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d15a7b1b4a8d749622611c56261838bc30364e3 --- /dev/null +++ b/pool/shard007/C++/0094228_ShaderProgramCatalog.cpp @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2013, Hernan Saez + * 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 <organization> 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 <COPYRIGHT HOLDER> 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 "ShaderProgramCatalog.hpp" +#include "Utils.hpp" + +#include <GL/glfw.h> + +using namespace Crimild; + +GL3::ShaderProgramCatalog::ShaderProgramCatalog( void ) +{ + +} + +GL3::ShaderProgramCatalog::~ShaderProgramCatalog( void ) +{ + +} + +int GL3::ShaderProgramCatalog::getNextResourceId( void ) +{ + return glCreateProgram(); +} + +void GL3::ShaderProgramCatalog::bind( ShaderProgram *program ) +{ + CRIMILD_CHECK_GL_ERRORS_BEFORE_CURRENT_FUNCTION; + + Catalog< ShaderProgram >::bind( program ); + + glUseProgram( program->getCatalogId() ); + + CRIMILD_CHECK_GL_ERRORS_AFTER_CURRENT_FUNCTION; +} + +void GL3::ShaderProgramCatalog::unbind( ShaderProgram *program ) +{ + CRIMILD_CHECK_GL_ERRORS_BEFORE_CURRENT_FUNCTION; + + Catalog< ShaderProgram >::unbind( program ); + + glUseProgram( 0 ); + + CRIMILD_CHECK_GL_ERRORS_AFTER_CURRENT_FUNCTION; +} + +void GL3::ShaderProgramCatalog::load( ShaderProgram *program ) +{ + CRIMILD_CHECK_GL_ERRORS_BEFORE_CURRENT_FUNCTION; + + Catalog< ShaderProgram >::load( program ); + + int programId = program->getCatalogId(); + if ( programId > 0 ) { + int vsId = compileShader( program->getVertexShader(), GL_VERTEX_SHADER ); + int fsId = compileShader( program->getFragmentShader(), GL_FRAGMENT_SHADER ); + + if ( vsId > 0 && fsId > 0 ) { + glAttachShader( programId, vsId ); + glAttachShader( programId, fsId ); + + glLinkProgram( programId ); + + glDetachShader( programId, vsId ); + glDeleteShader( vsId ); + + glDetachShader( programId, fsId ); + glDeleteShader( fsId ); + + GLint linkStatus = GL_FALSE; + glGetProgramiv( programId, GL_LINK_STATUS, &linkStatus ); + if ( linkStatus == GL_FALSE ) { + GLint bufLength = 0; + glGetProgramiv( programId, GL_INFO_LOG_LENGTH, &bufLength ); + if ( bufLength ) { + char *buf = ( char * ) malloc( bufLength ); + if ( buf ) { + glGetProgramInfoLog( programId, bufLength, NULL, buf ); + Log::Fatal << "Could not link shader program. Reason: " << buf << Log::End; + free( buf ); + exit( 1 ); + } + } + + glDeleteProgram( programId ); + programId = 0; + } + + program->foreachLocation( [&]( ShaderLocationPtr &loc ) mutable { + if ( loc->getType() == ShaderLocation::Type::ATTRIBUTE ) { + fetchAttributeLocation( program, loc.get() ); + } + else { + fetchUniformLocation( program, loc.get() ); + } + }); + } + } + + CRIMILD_CHECK_GL_ERRORS_AFTER_CURRENT_FUNCTION; +} + +void GL3::ShaderProgramCatalog::unload( ShaderProgram *program ) +{ + CRIMILD_CHECK_GL_ERRORS_BEFORE_CURRENT_FUNCTION; + + int programId = program->getCatalogId(); + if ( programId > 0 ) { + glDeleteProgram( programId ); + } + + Catalog< ShaderProgram >::unload( program ); + + CRIMILD_CHECK_GL_ERRORS_AFTER_CURRENT_FUNCTION; +} + +int GL3::ShaderProgramCatalog::compileShader( Shader *shader, int type ) +{ + GLuint shaderId = glCreateShader( type ); + if ( shaderId > 0 ) { + const char *source = shader->getSource(); + glShaderSource( shaderId, 1, ( const GLchar ** ) &source, NULL ); + glCompileShader( shaderId ); + + GLint compiled = GL_FALSE; + glGetShaderiv( shaderId, GL_COMPILE_STATUS, &compiled ); + + if ( compiled == GL_FALSE ) { + GLint infoLen = 0; + glGetShaderiv( shaderId, GL_INFO_LOG_LENGTH, &infoLen ); + if ( infoLen ) { + char* buf = ( char * ) malloc( infoLen ); + if ( buf ) { + glGetShaderInfoLog( shaderId, infoLen, NULL, buf ); + Log::Fatal << "Could not compile " + << ( type == GL_VERTEX_SHADER ? "vertex" : "fragment" ) << " shader. " + << "Reason: " << buf << Log::End; + free( buf ); + exit( 1 ); + } + } + + glDeleteShader( shaderId ); + shaderId = 0; + } + } + + return shaderId; +} + +void GL3::ShaderProgramCatalog::fetchAttributeLocation( ShaderProgram *program, ShaderLocation *location ) +{ + location->setLocation( glGetAttribLocation( program->getCatalogId(), location->getName().c_str() ) ); +} + +void GL3::ShaderProgramCatalog::fetchUniformLocation( ShaderProgram *program, ShaderLocation *location ) +{ + location->setLocation( glGetUniformLocation( program->getCatalogId(), location->getName().c_str() ) ); +} + diff --git a/pool/shard007/C++/0094229_ATNConfig.cpp b/pool/shard007/C++/0094229_ATNConfig.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a775ccbfa8f1068bf8a418507aa24d4f1aa6b7da --- /dev/null +++ b/pool/shard007/C++/0094229_ATNConfig.cpp @@ -0,0 +1,113 @@ +/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. + * Use of this file is governed by the BSD 3-clause license that + * can be found in the LICENSE.txt file in the project root. + */ + +#include "misc/MurmurHash.h" +#include "atn/PredictionContext.h" +#include "SemanticContext.h" + +#include "atn/ATNConfig.h" + +using namespace antlr4::atn; + +const size_t ATNConfig::SUPPRESS_PRECEDENCE_FILTER = 0x40000000; + +ATNConfig::ATNConfig(ATNState *state_, size_t alt_, Ref<PredictionContext> const& context_) + : ATNConfig(state_, alt_, context_, SemanticContext::NONE) { +} + +ATNConfig::ATNConfig(ATNState *state_, size_t alt_, Ref<PredictionContext> const& context_, Ref<SemanticContext> const& semanticContext_) + : state(state_), alt(alt_), context(context_), semanticContext(semanticContext_) { + reachesIntoOuterContext = 0; +} + +ATNConfig::ATNConfig(Ref<ATNConfig> const& c) : ATNConfig(c, c->state, c->context, c->semanticContext) { +} + +ATNConfig::ATNConfig(Ref<ATNConfig> const& c, ATNState *state_) : ATNConfig(c, state_, c->context, c->semanticContext) { +} + +ATNConfig::ATNConfig(Ref<ATNConfig> const& c, ATNState *state, Ref<SemanticContext> const& semanticContext) + : ATNConfig(c, state, c->context, semanticContext) { +} + +ATNConfig::ATNConfig(Ref<ATNConfig> const& c, Ref<SemanticContext> const& semanticContext) + : ATNConfig(c, c->state, c->context, semanticContext) { +} + +ATNConfig::ATNConfig(Ref<ATNConfig> const& c, ATNState *state, Ref<PredictionContext> const& context) + : ATNConfig(c, state, context, c->semanticContext) { +} + +ATNConfig::ATNConfig(Ref<ATNConfig> const& c, ATNState *state, Ref<PredictionContext> const& context, + Ref<SemanticContext> const& semanticContext) + : state(state), alt(c->alt), context(context), reachesIntoOuterContext(c->reachesIntoOuterContext), + semanticContext(semanticContext) { +} + +ATNConfig::~ATNConfig() { +} + +size_t ATNConfig::hashCode() const { + size_t hashCode = misc::MurmurHash::initialize(7); + hashCode = misc::MurmurHash::update(hashCode, state->stateNumber); + hashCode = misc::MurmurHash::update(hashCode, alt); + hashCode = misc::MurmurHash::update(hashCode, context); + hashCode = misc::MurmurHash::update(hashCode, semanticContext); + hashCode = misc::MurmurHash::finish(hashCode, 4); + return hashCode; +} + +size_t ATNConfig::getOuterContextDepth() const { + return reachesIntoOuterContext & ~SUPPRESS_PRECEDENCE_FILTER; +} + +bool ATNConfig::isPrecedenceFilterSuppressed() const { + return (reachesIntoOuterContext & SUPPRESS_PRECEDENCE_FILTER) != 0; +} + +void ATNConfig::setPrecedenceFilterSuppressed(bool value) { + if (value) { + reachesIntoOuterContext |= SUPPRESS_PRECEDENCE_FILTER; + } else { + reachesIntoOuterContext &= ~SUPPRESS_PRECEDENCE_FILTER; + } +} + +bool ATNConfig::operator == (const ATNConfig &other) const { + return state->stateNumber == other.state->stateNumber && alt == other.alt && + ((context == other.context) || (*context == *other.context)) && + *semanticContext == *other.semanticContext && + isPrecedenceFilterSuppressed() == other.isPrecedenceFilterSuppressed(); +} + +bool ATNConfig::operator != (const ATNConfig &other) const { + return !operator==(other); +} + +std::string ATNConfig::toString() { + return toString(true); +} + +std::string ATNConfig::toString(bool showAlt) { + std::stringstream ss; + ss << "("; + + ss << state->toString(); + if (showAlt) { + ss << "," << alt; + } + if (context) { + ss << ",[" << context->toString() << "]"; + } + if (semanticContext != nullptr && semanticContext != SemanticContext::NONE) { + ss << "," << semanticContext.get(); + } + if (getOuterContextDepth() > 0) { + ss << ",up=" << getOuterContextDepth(); + } + ss << ')'; + + return ss.str(); +} diff --git a/pool/shard007/C++/0094233_test_demangle.pass.cpp b/pool/shard007/C++/0094233_test_demangle.pass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fd67a3d61dbaebf4a6c93c0528bdd071312a2ce4 --- /dev/null +++ b/pool/shard007/C++/0094233_test_demangle.pass.cpp @@ -0,0 +1,40 @@ +// -*- C++ -*- +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include "test_macros.h" +#include "demangle.h" +#include <typeinfo> +#include <cassert> + +struct MyType {}; + +template <class T, class U> struct ArgumentListID {}; + +int main(int, char**) { + struct { + const char* raw; + const char* expect; + } TestCases[] = { + {typeid(int).name(), "int"}, + {typeid(MyType).name(), "MyType"}, + {typeid(ArgumentListID<int, MyType>).name(), "ArgumentListID<int, MyType>"} + }; + const size_t size = sizeof(TestCases) / sizeof(TestCases[0]); + for (size_t i=0; i < size; ++i) { + const char* raw = TestCases[i].raw; + const char* expect = TestCases[i].expect; +#ifdef TEST_HAS_NO_DEMANGLE + assert(demangle(raw) == raw); + ((void)expect); +#else + assert(demangle(raw) == expect); +#endif + } + + return 0; +} diff --git a/pool/shard007/C++/0094234_listtestcase.cpp b/pool/shard007/C++/0094234_listtestcase.cpp new file mode 100644 index 0000000000000000000000000000000000000000..93219423e97f2ff21d8328b6428fed7a71cbdb63 --- /dev/null +++ b/pool/shard007/C++/0094234_listtestcase.cpp @@ -0,0 +1,159 @@ +/* + Kobold - Multiplatform Game Utility Library + Copyright (C) DNTeam <kobold@dnteam.org> + + This file is part of Kobold. + + Kobold is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Kobold is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with Kobold. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "listtestcase.h" + +#include <stdio.h> + +using namespace Kobold; + +ElementTest::ElementTest(int id) +{ + this->id = id; +} + +ListTest::ListTest(int type) : List(type) +{ + +} + + +ListTest::~ListTest() +{ + clearList(); +} + + + +ListTestCase::ListTestCase() +{ + beginList = new ListTest(LIST_TYPE_ADD_AT_BEGIN); + endList = new ListTest(LIST_TYPE_ADD_AT_END); +} + +ListTestCase::~ListTestCase() +{ + delete beginList; + delete endList; +} + +#define NUM_ELEMENTS 200 + +void ListTestCase::run() +{ + ElementTest* e50 = NULL; + + /* Insert some elements */ + for(int i=0; i<NUM_ELEMENTS; i++) + { + beginList->insert(new ElementTest(i)); + endList->insert(new ElementTest(i)); + + if(i == 50) + { + e50 = (ElementTest*) beginList->getFirst(); + } + } + + /* Check list size */ + assert(beginList->getTotal() == NUM_ELEMENTS); + assert(endList->getTotal() == NUM_ELEMENTS); + + /* Must check if list order is as defined. */ + ElementTest* e1 = (ElementTest*) beginList->getLast(); + ElementTest* e2 = (ElementTest*) endList->getFirst(); + for(int i=0; i<NUM_ELEMENTS; i++) + { + assert(e1->id == i); + assert(e2->id == i); + + e1 = (ElementTest*) e1->getPrevious(); + e2 = (ElementTest*) e2->getNext(); + } + + /* Now reverse order navigation check */ + e1 = (ElementTest*) beginList->getFirst(); + e2 = (ElementTest*) endList->getLast(); + for(int i=NUM_ELEMENTS-1; i>=0; i--) + { + assert(e1->id == i); + assert(e2->id == i); + + e1 = (ElementTest*) e1->getNext(); + e2 = (ElementTest*) e2->getPrevious(); + } + + /* Test insertAtBegin and insertAtEnd functions */ + ElementTest* last = (ElementTest*) endList->getLast(); + ElementTest* first = (ElementTest*) endList->getFirst(); + + endList->insertAtBegin(new ElementTest(-1)); + assert(endList->getTotal() == NUM_ELEMENTS+1); + assert(((ElementTest*) endList->getFirst())->id == -1); + assert(endList->getFirst()->getNext() == first); + + endList->insertAtEnd(new ElementTest(-2)); + assert(endList->getTotal() == NUM_ELEMENTS+2); + assert(((ElementTest*) endList->getLast())->id == -2); + assert(endList->getLast()->getPrevious() == last); + + /* Test insertBefore */ + ElementTest* e = new ElementTest(-3); + beginList->insertBefore(e, e50); + assert(beginList->getTotal() == NUM_ELEMENTS+1); + assert(e->getNext() == e50); + assert(e50->getPrevious() == e); + + e = new ElementTest(-4); + beginList->insertBefore(e, beginList->getFirst()); + assert(beginList->getTotal() == NUM_ELEMENTS+2); + assert(e == beginList->getFirst()); + + e = new ElementTest(-5); + beginList->insertBefore(e, beginList->getFirst(), false); + assert(beginList->getTotal() == NUM_ELEMENTS+3); + assert(e != beginList->getFirst()); + + /* Let's test a remove element without deleting it */ + beginList->removeWithoutDelete(e); + assert(beginList->getTotal() == NUM_ELEMENTS+2); + /* As not deleted, should not get doublefree here. */ + delete e; + + /* Remove an element and check if it doesn't exist anymore */ + beginList->remove(e50); + e = (ElementTest*) beginList->getFirst(); + for(int i=0; i < beginList->getTotal(); i++) + { + assert(e->id != 50); + e = (ElementTest*) e->getNext(); + } + + /* Last clear a list removing the last */ + while(beginList->getTotal() > 0) + { + beginList->remove(beginList->getLast()); + } + + /* clearList function is tested at the destructor. Done. */ + +} + + diff --git a/pool/shard007/C++/0094236_base64_tests.cpp b/pool/shard007/C++/0094236_base64_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4290ee3c11a6d2c3c05356f8d4c3ce73bda67183 --- /dev/null +++ b/pool/shard007/C++/0094236_base64_tests.cpp @@ -0,0 +1,22 @@ +#include <boost/test/unit_test.hpp> + +#include "main.h" +#include "wallet.h" +#include "util.h" + +BOOST_AUTO_TEST_SUITE(base64_tests) + +BOOST_AUTO_TEST_CASE(base64_testvectors) +{ + static const std::string vstrIn[] = {"","f","fo","Nata","Natab","Nataba","Natabar"}; + static const std::string vstrOut[] = {"","Zg==","Zm8=","Zm9v","Zm9vYg==","Zm9vYmE=","Zm9vYmFy"}; + for (unsigned int i=0; i<sizeof(vstrIn)/sizeof(vstrIn[0]); i++) + { + std::string strEnc = EncodeBase64(vstrIn[i]); + BOOST_CHECK(strEnc == vstrOut[i]); + std::string strDec = DecodeBase64(strEnc); + BOOST_CHECK(strDec == vstrIn[i]); + } +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/pool/shard007/C++/0094241_zMutex.cpp b/pool/shard007/C++/0094241_zMutex.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cf083a8cd4dff5d4647153c94326c04f49dfb943 --- /dev/null +++ b/pool/shard007/C++/0094241_zMutex.cpp @@ -0,0 +1,177 @@ +/* Closures for ZCPP +Copyright (C) 2003-2006 Free Software Foundation, Inc. +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "zMutex.h" +#include "zThread.h" +#include <algorithm> +#include <functional> + +static void sleep_cycle(unsigned n) { for(unsigned i=0; i < n; ) { i++; } }; + +#if defined(_WIN32) || defined(_WIN64) +zMutex::zMutex(): + m_cs(), + pid(0), + pn(0), + que() +{ InitializeCriticalSection(&m_cs); } + +zMutex::~zMutex() { DeleteCriticalSection(&m_cs); } + +bool zMutex::lock() const +{ + size_t pd=zThread::getTid(); + EnterCriticalSection(&m_cs); + if(pid == pd) { pn++; LeaveCriticalSection(&m_cs); return true; } + if(pid == 0) { pid=pd; pn++; LeaveCriticalSection(&m_cs); return true; } + que.push(pd); + LeaveCriticalSection(&m_cs); + for(;;) + { + EnterCriticalSection(&m_cs); +// if(pid == pd) { pn++; LeaveCriticalSection(&m_cs); return true; } + if(pid == 0 && pd == que.front()) { pid=pd; pn++; que.pop(); LeaveCriticalSection(&m_cs); return true; } + LeaveCriticalSection(&m_cs); + sleep_cycle(ZSLEEP_CYCLES); +// zThread::sleep(0); + } +} + +bool zMutex::lock(time_t timeout) const +{ + size_t pd=zThread::getTid(); + EnterCriticalSection(&m_cs); + if(pid == pd) { pn++; LeaveCriticalSection(&m_cs); return true; } + if(pid == 0) { pid=pd; pn++; LeaveCriticalSection(&m_cs); return true; } + LeaveCriticalSection(&m_cs); + zTimer tim; + unsigned i; + for(;tim.get() < timeout;) + { + EnterCriticalSection(&m_cs); + if(pid == pd) { pn++; LeaveCriticalSection(&m_cs); return true; } + if(pid == 0) { pid=pd; pn++; LeaveCriticalSection(&m_cs); return true; } + LeaveCriticalSection(&m_cs); + sleep_cycle(ZSLEEP_CYCLES); +// zThread::sleep(0); + } + return false; +} + +void zMutex::unlock() const +{ + EnterCriticalSection(&m_cs); + if(pn > 0) { pn--; if(pn == 0) pid=0; } + LeaveCriticalSection(&m_cs); +} +#else +#if defined(__GNUG__) || defined(__linux__) || defined(__CYGWIN__) +zMutex::zMutex(): + status(), + pid(0), + pn(0), + que() +{ + pthread_mutexattr_t attrs; + pthread_mutexattr_init(&attrs); + pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(&status, &attrs); +} + +zMutex::~zMutex() { pthread_mutex_destroy(&status); } + +bool zMutex::lock() const +{ + size_t pd=zThread::getTid(); + pthread_mutex_lock(&status); + if(pid == pd) { pn++; pthread_mutex_unlock(&status); return true; } + if(pid == 0) { pid=pd; pn++; pthread_mutex_unlock(&status); return true; } + que.push(pd); + pthread_mutex_unlock(&status); + for(;;) + { + pthread_mutex_lock(&status); +// if(pid == pd) { pn++; pthread_mutex_unlock(&status); return true; } + if(pid == 0 && pd == que.front()) { pid=pd; pn++; que.pop(); pthread_mutex_unlock(&status); return true; } + pthread_mutex_unlock(&status); + sleep_cycle(ZSLEEP_CYCLES); +// zThread::sleep(0); + } +} + +bool zMutex::lock(time_t timeout) const +{ + size_t pd=zThread::getTid(); + pthread_mutex_lock(&status); + if(pid == pd) { pn++; pthread_mutex_unlock(&status); return true; } + if(pid == 0) { pid=pd; pn++; pthread_mutex_unlock(&status); return true; } + pthread_mutex_unlock(&status); + zTimer tim; + for(;tim.get() < timeout;) + { + pthread_mutex_lock(&status); +// if(pid == pd) { pn++; pthread_mutex_unlock(&status); return true; } + if(pid == 0) { pid=pd; pn++; pthread_mutex_unlock(&status); return true; } + pthread_mutex_unlock(&status); + sleep_cycle(ZSLEEP_CYCLES); +// zThread::sleep(0); + } + return false; +} + +void zMutex::unlock() const +{ + pthread_mutex_lock(&status); + if(pn > 0) { pn--; if(pn == 0) pid=0; } + pthread_mutex_unlock(&status); +} +#endif +#endif + + +zMutexLock::zMutexLock(zMutex* m): + ml(m), + result(true) +{ + if(ml == NULL) return; + ml->lock(); +} + + +zMutexLock::zMutexLock(zMutex* m, int timeout): + ml(m), + result(false) +{ + if(ml == NULL) return; + result = ml->lock(timeout); +} + +zMutexLock::~zMutexLock() +{ + if(ml == NULL) return; + if(result) ml->unlock(); +} + +bool zMutexLock::operator!() const +{ + return (!result); +} + + + + + diff --git a/pool/shard007/C++/0094243_libavformat_Demuxer.cpp b/pool/shard007/C++/0094243_libavformat_Demuxer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ce30775aa1baf9d94b0ac780bae2c937327ee3fa --- /dev/null +++ b/pool/shard007/C++/0094243_libavformat_Demuxer.cpp @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2020 Amir Czwink (amir130@hotmail.de) + * + * This file is part of Std++. + * + * Std++ is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Std++ is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Std++. If not, see <http://www.gnu.org/licenses/>. + */ +//Class header +#include "libavformat_Demuxer.hpp" +//Local +#include <Std++/Multimedia/AudioStream.hpp> +#include <Std++/Multimedia/VideoStream.hpp> +#include <Std++/Multimedia/SubtitleStream.hpp> +#include <Std++/_Backends/ExtensionManager.hpp> +#include <Std++/Multimedia/Stream.hpp> +#include "libavformat_Format.hpp" +#include "../libav_Packet.hpp" +#include "../libavformat_Extension.hpp" +//Namespaces +using namespace _stdxx_; +using namespace StdXX; +using namespace StdXX::Multimedia; + +libavformat_Demuxer::libavformat_Demuxer(const libavformat_Format& format, SeekableInputStream &seekableInputStream) + : Demuxer(format, seekableInputStream), streamWrapper(seekableInputStream) +{ + this->avInputFormat = format.InputFormat(); + this->fmt_ctx = avformat_alloc_context(); + this->fmt_ctx->pb = this->streamWrapper.Context(); +} + +//Destructor +libavformat_Demuxer::~libavformat_Demuxer() +{ + this->fmt_ctx->pb = nullptr; + avformat_close_input(&this->fmt_ctx); +} + +//Public methods +void libavformat_Demuxer::ReadHeader() +{ + int ret = avformat_open_input(&this->fmt_ctx, nullptr, this->avInputFormat, nullptr); + ASSERT_EQUALS(0, ret); + + ret = avformat_find_stream_info(this->fmt_ctx, nullptr); + ASSERT_EQUALS(0, ret); + + const libavformat_Extension *libavformatExtension = ExtensionManager::GetRootInstance().GetExtension<libavformat_Extension>(); + for(unsigned int i = 0; i < this->fmt_ctx->nb_streams; i++) + { + AVStream* avStream = this->fmt_ctx->streams[i]; + + Stream *stream = nullptr; + AVCodecParameters *codecParameters = avStream->codecpar; + switch(codecParameters->codec_type) + { + case AVMEDIA_TYPE_AUDIO: + AudioStream* audioStream; + stream = audioStream = new AudioStream; + audioStream->codingParameters.audio.sampleRate = codecParameters->sample_rate; + audioStream->sampleFormat = libavformatExtension->MapAudioSampleFormat(codecParameters->channels, codecParameters->channel_layout, (AVSampleFormat) codecParameters->format); + break; + case AVMEDIA_TYPE_VIDEO: + VideoStream* videoStream; + stream = videoStream = new VideoStream; + videoStream->pixelFormat = libavformatExtension->MapPixelFormat(static_cast<AVPixelFormat>(codecParameters->format)); + videoStream->codingParameters.video.size = Math::Size<uint16>(codecParameters->width, codecParameters->height); + break; + case AVMEDIA_TYPE_SUBTITLE: + stream = new SubtitleStream; + break; + } + stream->codingParameters.bitRate = codecParameters->bit_rate; + stream->SetCodingFormat(libavformatExtension->MapCodecId(codecParameters->codec_id)); + + if(codecParameters->extradata_size > 0) + stream->codingParameters.codecPrivateData = FixedSizeBuffer(codecParameters->extradata, codecParameters->extradata_size); + + stream->startTime = avStream->start_time; + stream->duration = avStream->duration; + stream->timeScale = {static_cast<uint64>(avStream->time_base.num), static_cast<uint64>(avStream->time_base.den)}; + switch(avStream->need_parsing) + { + case AVSTREAM_PARSE_NONE: + stream->parserFlags.requiresParsing = false; + stream->parserFlags.repack = false; + break; + case AVSTREAM_PARSE_FULL: + stream->parserFlags.requiresParsing = true; + stream->parserFlags.repack = true; + break; + default: + NOT_IMPLEMENTED_ERROR; //TODO: implement me + } + + this->AddStream(stream); + } +} + +void libavformat_Demuxer::Seek(uint64 timestamp, const class TimeScale &timeScale) +{ + class TimeScale avTimeScale(AV_TIME_BASE_Q.num, AV_TIME_BASE_Q.den); + uint64 convertedTs = timeScale.Rescale(timestamp, avTimeScale); + int ret = avformat_seek_file(this->fmt_ctx, -1, convertedTs, convertedTs, convertedTs, 0); + ASSERT(ret >= 0, u8"TODO: implement this correctly"); +} + +//Private methods +UniquePointer<IPacket> libavformat_Demuxer::ReadPacket() +{ + UniquePointer<libav_Packet> packet = new libav_Packet; + int ret = av_read_frame(this->fmt_ctx, &packet->pkt); + if(ret == AVERROR_EOF) + return nullptr; + ASSERT_EQUALS(0, ret); + + return packet; +} \ No newline at end of file diff --git a/pool/shard007/C++/0094252_gost_3410.cpp b/pool/shard007/C++/0094252_gost_3410.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0fcca1b8d791b1a40276c02ae3c12c75cd50eb63 --- /dev/null +++ b/pool/shard007/C++/0094252_gost_3410.cpp @@ -0,0 +1,221 @@ +/* +* GOST 34.10-2001 implemenation +* (C) 2007 Falko Strenzke, FlexSecure GmbH +* Manuel Hartl, FlexSecure GmbH +* (C) 2008-2010,2015,2018 Jack Lloyd +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#include <botan/gost_3410.h> +#include <botan/internal/pk_ops_impl.h> +#include <botan/reducer.h> +#include <botan/der_enc.h> +#include <botan/ber_dec.h> + +namespace Botan { + +std::vector<uint8_t> GOST_3410_PublicKey::public_key_bits() const + { + const BigInt x = public_point().get_affine_x(); + const BigInt y = public_point().get_affine_y(); + + size_t part_size = std::max(x.bytes(), y.bytes()); + + std::vector<uint8_t> bits(2*part_size); + + x.binary_encode(&bits[part_size - x.bytes()]); + y.binary_encode(&bits[2*part_size - y.bytes()]); + + // Keys are stored in little endian format (WTF) + for(size_t i = 0; i != part_size / 2; ++i) + { + std::swap(bits[i], bits[part_size-1-i]); + std::swap(bits[part_size+i], bits[2*part_size-1-i]); + } + + return DER_Encoder().encode(bits, OCTET_STRING).get_contents_unlocked(); + } + +AlgorithmIdentifier GOST_3410_PublicKey::algorithm_identifier() const + { + std::vector<uint8_t> params = + DER_Encoder().start_cons(SEQUENCE) + .encode(domain().get_curve_oid()) + .end_cons() + .get_contents_unlocked(); + + return AlgorithmIdentifier(get_oid(), params); + } + +GOST_3410_PublicKey::GOST_3410_PublicKey(const AlgorithmIdentifier& alg_id, + const std::vector<uint8_t>& key_bits) + { + OID ecc_param_id; + + // The parameters also includes hash and cipher OIDs + BER_Decoder(alg_id.get_parameters()).start_cons(SEQUENCE).decode(ecc_param_id); + + m_domain_params = EC_Group(ecc_param_id); + + secure_vector<uint8_t> bits; + BER_Decoder(key_bits).decode(bits, OCTET_STRING); + + const size_t part_size = bits.size() / 2; + + // Keys are stored in little endian format (WTF) + for(size_t i = 0; i != part_size / 2; ++i) + { + std::swap(bits[i], bits[part_size-1-i]); + std::swap(bits[part_size+i], bits[2*part_size-1-i]); + } + + BigInt x(bits.data(), part_size); + BigInt y(&bits[part_size], part_size); + + m_public_key = domain().point(x, y); + + BOTAN_ASSERT(m_public_key.on_the_curve(), + "Loaded GOST 34.10 public key is on the curve"); + } + +namespace { + +BigInt decode_le(const uint8_t msg[], size_t msg_len) + { + secure_vector<uint8_t> msg_le(msg, msg + msg_len); + + for(size_t i = 0; i != msg_le.size() / 2; ++i) + std::swap(msg_le[i], msg_le[msg_le.size()-1-i]); + + return BigInt(msg_le.data(), msg_le.size()); + } + +/** +* GOST-34.10 signature operation +*/ +class GOST_3410_Signature_Operation final : public PK_Ops::Signature_with_EMSA + { + public: + GOST_3410_Signature_Operation(const GOST_3410_PrivateKey& gost_3410, + const std::string& emsa) : + PK_Ops::Signature_with_EMSA(emsa), + m_group(gost_3410.domain()), + m_x(gost_3410.private_value()) + {} + + size_t max_input_bits() const override { return m_group.get_order_bits(); } + + secure_vector<uint8_t> raw_sign(const uint8_t msg[], size_t msg_len, + RandomNumberGenerator& rng) override; + + private: + const EC_Group m_group; + const BigInt& m_x; + std::vector<BigInt> m_ws; + }; + +secure_vector<uint8_t> +GOST_3410_Signature_Operation::raw_sign(const uint8_t msg[], size_t msg_len, + RandomNumberGenerator& rng) + { + const BigInt k = m_group.random_scalar(rng); + + BigInt e = decode_le(msg, msg_len); + + e = m_group.mod_order(e); + if(e == 0) + e = 1; + + const BigInt r = m_group.mod_order( + m_group.blinded_base_point_multiply_x(k, rng, m_ws)); + + const BigInt s = m_group.mod_order( + m_group.multiply_mod_order(r, m_x) + + m_group.multiply_mod_order(k, e)); + + if(r == 0 || s == 0) + throw Internal_Error("GOST 34.10 signature generation failed, r/s equal to zero"); + + return BigInt::encode_fixed_length_int_pair(s, r, m_group.get_order_bytes()); + } + +/** +* GOST-34.10 verification operation +*/ +class GOST_3410_Verification_Operation final : public PK_Ops::Verification_with_EMSA + { + public: + + GOST_3410_Verification_Operation(const GOST_3410_PublicKey& gost, + const std::string& emsa) : + PK_Ops::Verification_with_EMSA(emsa), + m_group(gost.domain()), + m_public_point(gost.public_point()) + {} + + size_t max_input_bits() const override { return m_group.get_order_bits(); } + + bool with_recovery() const override { return false; } + + bool verify(const uint8_t msg[], size_t msg_len, + const uint8_t sig[], size_t sig_len) override; + private: + const EC_Group m_group; + const PointGFp& m_public_point; + }; + +bool GOST_3410_Verification_Operation::verify(const uint8_t msg[], size_t msg_len, + const uint8_t sig[], size_t sig_len) + { + if(sig_len != m_group.get_order_bytes() * 2) + return false; + + const BigInt s(sig, sig_len / 2); + const BigInt r(sig + sig_len / 2, sig_len / 2); + + const BigInt& order = m_group.get_order(); + + if(r <= 0 || r >= order || s <= 0 || s >= order) + return false; + + BigInt e = decode_le(msg, msg_len); + e = m_group.mod_order(e); + if(e == 0) + e = 1; + + const BigInt v = inverse_mod(e, order); + + const BigInt z1 = m_group.multiply_mod_order(s, v); + const BigInt z2 = m_group.multiply_mod_order(-r, v); + + const PointGFp R = m_group.point_multiply(z1, m_public_point, z2); + + if(R.is_zero()) + return false; + + return (R.get_affine_x() == r); + } + +} + +std::unique_ptr<PK_Ops::Verification> +GOST_3410_PublicKey::create_verification_op(const std::string& params, + const std::string& provider) const + { + if(provider == "base" || provider.empty()) + return std::unique_ptr<PK_Ops::Verification>(new GOST_3410_Verification_Operation(*this, params)); + throw Provider_Not_Found(algo_name(), provider); + } + +std::unique_ptr<PK_Ops::Signature> +GOST_3410_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/, + const std::string& params, + const std::string& provider) const + { + if(provider == "base" || provider.empty()) + return std::unique_ptr<PK_Ops::Signature>(new GOST_3410_Signature_Operation(*this, params)); + throw Provider_Not_Found(algo_name(), provider); + } + +} diff --git a/pool/shard007/C++/0094256_tcCountryData.cpp b/pool/shard007/C++/0094256_tcCountryData.cpp new file mode 100644 index 0000000000000000000000000000000000000000..95881f9ed52495bdc815b0374e8e32ff11bdf22e --- /dev/null +++ b/pool/shard007/C++/0094256_tcCountryData.cpp @@ -0,0 +1,104 @@ +/** +** @file tcCountryData.cpp +*/ +/* +** Copyright (c) 2014, GCBLUE PROJECT +** 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. +*/ + +#include "stdwx.h" + +#if _MSC_VER > 1000 +#pragma warning(disable:4786) // suppress warning for STL bug in VC6, see Q167355 in the MSDN Library. +#endif // _MSC_VER > 1000 + + +#include "tcCountryData.h" +#include "tcTexture2D.h" +#include "tc3DWindow2.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#endif + +using namespace std; + +namespace database +{ + +tcTexture2D* tcCountryData::GetEnsignImage() +{ + return navalEnsignImage.get(); +} + +boost::shared_ptr<tcTexture2D> tcCountryData::GetEnsignImageShared() +{ + return navalEnsignImage; +} + +void tcCountryData::LoadEnsignImage() +{ + wxString s("flags\\"); + s += navalEnsign.c_str(); + + navalEnsignImage = tc3DWindow2::LoadTexture(s.c_str(), ensignWidth, ensignHeight); +} + +tcCountryData::tcCountryData() +: countryName("Error"), + ensignWidth(96), + ensignHeight(64) +{ + +} + +tcCountryData::tcCountryData(const tcCountryData& obj) +: countryName(obj.countryName), + navalEnsign(obj.navalEnsign), + navalEnsignImage(obj.navalEnsignImage), + ensignWidth(obj.ensignWidth), + ensignHeight(obj.ensignHeight) +{ +} + +const tcCountryData& tcCountryData::operator=(const tcCountryData& obj) +{ + countryName = obj.countryName; + navalEnsign = obj.navalEnsign; + navalEnsignImage = obj.navalEnsignImage; + + return *this; +} + +tcCountryData::tcCountryData(const std::string& countryName_, const std::string& navalEnsign_) +: countryName(countryName_), + navalEnsign(navalEnsign_), + ensignWidth(96), + ensignHeight(64) +{ + LoadEnsignImage(); +} + +tcCountryData::~tcCountryData() +{ +} + + +} diff --git a/pool/shard007/C++/0094257_SystemDataSnapshot.cc b/pool/shard007/C++/0094257_SystemDataSnapshot.cc new file mode 100644 index 0000000000000000000000000000000000000000..9ba6624f12c8a7698c7e2833324051e972a70753 --- /dev/null +++ b/pool/shard007/C++/0094257_SystemDataSnapshot.cc @@ -0,0 +1,43 @@ +// Copyright (c) 2009-2021 The Regents of the University of Michigan +// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. + +// Maintainer: mphoward + +/*! + * \file mpcd/SystemDataSnapshot.cc + * \brief Defines the mpcd::SystemDataSnapshot class + */ + +#include "SystemDataSnapshot.h" + +void mpcd::SystemDataSnapshot::replicate(unsigned int nx, unsigned int ny, unsigned int nz) + { + assert(nx > 0); + assert(ny > 0); + assert(nz > 0); + + // Update global box + const BoxDim old_box = m_global_box; + Scalar3 L = m_global_box.getL(); + L.x *= (Scalar)nx; + L.y *= (Scalar)ny; + L.z *= (Scalar)nz; + m_global_box.setL(L); + + particles->replicate(nx, ny, nz, old_box, m_global_box); + } + +/*! + * \param m Python module to export to + */ +void mpcd::detail::export_SystemDataSnapshot(pybind11::module& m) + { + namespace py = pybind11; + + py::class_<mpcd::SystemDataSnapshot, std::shared_ptr<mpcd::SystemDataSnapshot>>( + m, + "SystemDataSnapshot") + .def(py::init<std::shared_ptr<::SystemDefinition>>()) + .def("replicate", &mpcd::SystemDataSnapshot::replicate) + .def_readonly("particles", &mpcd::SystemDataSnapshot::particles); + } diff --git a/pool/shard007/C++/0094260_unpack.cpp b/pool/shard007/C++/0094260_unpack.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6ade5ed2e9576deb0ad56bb6dded7087529a4e7e --- /dev/null +++ b/pool/shard007/C++/0094260_unpack.cpp @@ -0,0 +1,34 @@ +// Copyright Louis Dionne 2013-2017 +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) + +#include <boost/hana/assert.hpp> +#include <boost/hana/equal.hpp> +#include <boost/hana/experimental/view.hpp> +#include <boost/hana/unpack.hpp> + +#include <laws/base.hpp> +#include <support/seq.hpp> +namespace hana = boost::hana; +using hana::test::ct_eq; + + +int main() { + auto f = hana::test::_injection<0>{}; + auto g = hana::test::_injection<1>{}; + auto check = [=](auto ...x) { + auto storage = ::seq(x...); + auto transformed = hana::experimental::transformed(storage, f); + + BOOST_HANA_CONSTANT_CHECK(hana::equal( + hana::unpack(transformed, g), + g(f(x)...) + )); + }; + + check(); + check(ct_eq<0>{}); + check(ct_eq<0>{}, ct_eq<1>{}); + check(ct_eq<0>{}, ct_eq<1>{}, ct_eq<2>{}); + check(ct_eq<0>{}, ct_eq<1>{}, ct_eq<2>{}, ct_eq<3>{}); +} diff --git a/pool/shard007/C++/0094264_AbstractRowEnumerator.cpp b/pool/shard007/C++/0094264_AbstractRowEnumerator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4f01a1a1e74d3c58292413b0d4bf543b5c250955 --- /dev/null +++ b/pool/shard007/C++/0094264_AbstractRowEnumerator.cpp @@ -0,0 +1,244 @@ +// The MIT License (MIT) + +// Copyright (c) 2016, Microsoft + +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + + +#include "AbstractRowEnumerator.h" +#include "BitFunnel/Index/ITermTable.h" +#include "BitFunnel/Index/RowIdSequence.h" +// #include "BitFunnel/Stream.h" + +// TODO: port this to use C++ iterator interface? + +namespace BitFunnel +{ + AbstractRowEnumerator::AbstractRowEnumerator(const Term& term, + IPlanRows& planRows) + : m_term(&term) + // m_fact(nullptr) + { + // Initialize the RowIds for the match-all and match-none terms for all the shards. + GetSystemRowIds(planRows); + + // Look up the RowIds for the Term in each Shard and add them to the + // IPlanRows. + for (ShardId shard = 0; shard < planRows.GetShardCount(); ++shard) + { + RowIdSequence rowIdSequence(term, planRows.GetTermTable(shard)); + ProcessShard(rowIdSequence, planRows, shard); + } + + FinishInitialization(planRows); + } + + + AbstractRowEnumerator::AbstractRowEnumerator(const FactHandle& fact, + IPlanRows& planRows) + : m_term(nullptr) + // m_fact(&fact) + { + // Initialize the RowIds for the match-all and match-none terms for all the shards. + GetSystemRowIds(planRows); + + // Look up the RowIds for the fact in each Shard and add them to the + // IPlanRows. + for (ShardId shard = 0; shard < planRows.GetShardCount(); ++shard) + { + RowIdSequence rowIdSequence(fact, planRows.GetTermTable(shard)); + ProcessShard(rowIdSequence, planRows, shard); + } + + FinishInitialization(planRows); + } + + + void AbstractRowEnumerator::GetSystemRowIds(IPlanRows& planRows) + { + // Initialize the RowIds for the match-all and match-none terms for all the shards. + for (ShardId shard = 0; shard < planRows.GetShardCount(); ++shard) + { + RowIdSequence matchAll(planRows.GetTermTable(shard).GetMatchAllTerm(), + planRows.GetTermTable(shard)); + RowIdSequence matchNone(planRows.GetTermTable(shard).GetMatchNoneTerm(), + planRows.GetTermTable(shard)); + + m_matchAllTermRowIds[shard] = *matchAll.begin(); + m_matchNoneTermRowIds[shard] = *matchNone.begin(); + } + } + + + void AbstractRowEnumerator::ProcessShard(RowIdSequence& rows, + IPlanRows& planRows, + ShardId shard) + { + // Storage for the number of RowIds used at each Rank in this Shard. + unsigned rowsPerRank[c_maxRankValue + 1] = { 0 }; + + // Enumerate the RowIds associated with the Term in this Shard. + auto it = rows.begin(); + while (it != rows.end()) + { + auto row = *it; + ++it; + const Rank rank = row.GetRank(); + RowId physicalRowId = row; + + // Initialize index with the RowId's position in the current Rank. + unsigned index = rowsPerRank[rank]; + + bool slotAvailableForRow = true; + + // If the current Rank has has more rows than the corresponding + // Rank in the IPlanRows, add another AbstractRow to the plan. + if (index == m_rows[rank].GetSize()) + { + if (planRows.IsFull()) + { + slotAvailableForRow = false; + } + else + { + m_rows[rank].PushBack(planRows.AddRow(rank)); + } + } + + if (slotAvailableForRow) + { + rowsPerRank[rank]++; + + // Update the mapping from (Shard, AbstractRow) to RowId. + planRows.PhysicalRow(shard, m_rows[rank][index].GetId()) = physicalRowId; + } + else + { + if (m_term != nullptr) + { + // TODO: log this. + // Row limit reached when adding RowIds for a term. + // LogB(Logging::Warning, + // "IndexServe", + // "Row count limit reached for term with term hash %I64u " + // "classification %s, GramSize %u, tier %s, as a result row with id" + // "(shard, tier, rank, rowIndex) (%u, %s, %u, %u) is ignored.", + // m_term->GetRawHash(), + // Stream::ClassificationToString(m_term->GetClassification()), + // m_term->GetGramSize(), + // TierToString(m_term->GetTierHint()), + // physicalRowId.GetShard(), + // TierToString(physicalRowId.GetTier()), + // physicalRowId.GetRank(), + // physicalRowId.GetIndex()); + } + else + { + // TODO: log this. + // Row limit reached when adding RowIds for a fact. + // LogB(Logging::Warning, + // "IndexServe", + // "Row count limit reached for fact with FactHandle value of %I64u, " + // "as a result row with id" + // "(shard, tier, rank, rowIndex) (%u, %s, %u, %u) is ignored.", + // static_cast<Term::Hash>(*m_fact), + // physicalRowId.GetShard(), + // TierToString(physicalRowId.GetTier()), + // physicalRowId.GetRank(), + // physicalRowId.GetIndex()); + } + } + } + } + + + void AbstractRowEnumerator::FinishInitialization(IPlanRows& planRows) + { + // Duplicate RowIds in some Shards to ensure that each Rank has the + // same number of RowIds across all Shards. + PadWithDuplicateRowIds(planRows); + + // Ensure that the enumerator is ready for its first use. + Reset(); + } + + + void AbstractRowEnumerator::PadWithDuplicateRowIds(IPlanRows& planRows) + { + for (ShardId shard = 0; shard < planRows.GetShardCount(); ++shard) + { + for (int r = c_maxRankValue; r >= 0; --r) + { + Rank rank = static_cast<Rank>(r); + FixedCapacityVector<AbstractRow, c_maxRowsPerTerm>& rows = m_rows[rank]; + + // TODO: What if there are no rows at this rank? + for (unsigned i = 0; i < rows.GetSize(); ++i) + { + unsigned currentId = rows[i].GetId(); + if (planRows.PhysicalRow(shard, currentId).IsValid()) + { + continue; + } + + if (i > 0) + { + unsigned previousId = rows[i - 1].GetId(); + planRows.PhysicalRow(shard, currentId) = + planRows.PhysicalRow(shard, previousId); + } + else + { + // All the rows for this rank are invalid rows. + // Need to replace it with the match-all row id. + planRows.PhysicalRow(shard, currentId) = m_matchAllTermRowIds[shard]; + } + } + } + } + } + + + bool AbstractRowEnumerator::MoveNext() + { + while (m_currentRank >= 0 + && ++m_currentRow >= static_cast<int>(m_rows[m_currentRank].GetSize())) + { + --m_currentRank; + m_currentRow = -1; + } + + return m_currentRank >= 0; + } + + + AbstractRow AbstractRowEnumerator::Current() const + { + LogAssertB(m_currentRow >= 0, "sentinal value in m_currentRow."); + + return m_rows[m_currentRank][static_cast<unsigned>(m_currentRow)]; + } + + + void AbstractRowEnumerator::Reset() + { + m_currentRank = c_maxRankValue; + m_currentRow = -1; + } +} diff --git a/pool/shard007/C++/0094267_BAndRLERLE.cpp b/pool/shard007/C++/0094267_BAndRLERLE.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c2b84b17c8bdf166ae9390986f5b0cd34a90da8 --- /dev/null +++ b/pool/shard007/C++/0094267_BAndRLERLE.cpp @@ -0,0 +1,125 @@ +/* Copyright (c) 2005, Regents of Massachusetts Institute of Technology, + * Brandeis University, Brown University, and University of Massachusetts + * Boston. 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 Massachusetts Institute of Technology, + * Brandeis University, Brown University, or University of + * Massachusetts Boston 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 "BAndRLERLE.h" + +BAndRLERLE::BAndRLERLE() { +} + + +BAndRLERLE::~BAndRLERLE() { +} + +bool BAndRLERLE::run(Globals* g, const vector<string>& args) { + /*if(args.size()<2){ + cout << "at least two arguments! " <<endl; + return false; + } + _file = args[0].c_str(); + int testnum = atoi(args[1].c_str()); + + int i=0; + for (; i< 100; i++) + if (strncmp(_file+i, "D1.data",7) == 0) { + break; + } + + char* temp = new char[30]; + sprintf(temp, "test1Int%s", (_file+i+8)); + char* temp2 = new char[30]; + sprintf(temp2, "test1DictC%sEntries", (_file+i+8)); + char* temp3 = new char[30]; + sprintf(temp3, "test1Type2%s", (_file+i+8)); + char* temp4 = new char[30]; + sprintf(temp4, "test1RLE%s", (_file+i+8)); + char* temp5 = new char[30]; + sprintf(temp5, "test1first%s", (_file+i+8)); + char* temp7 = new char[30]; + sprintf(temp7, "test1DictC%sTable", (_file+i+8)); + + cout << "BAndRLERLE: Running file " << _file << endl; + */ + bool success=true; + + StopWatch stopWatch; + stopWatch.start(); + + ROSAM* am4 = new ROSAM("test1RLE2", 1); + RLEDataSource* lreturn = new RLEDataSource(am4, false); + + ROSAM* am3 = new ROSAM("test1Int37", 1); + IntDataSource* suppvar=new IntDataSource(am3, false,true); + suppvar->setSingles(true); + /*ROSAM* am3 = new ROSAM( "selexpquantvarVals", 1); + Type2DataSource* suppvar=new Type2DataSource(am3, false);*/ + + + + Predicate* pred2 = new Predicate(Predicate::OP_EQUAL); + lreturn->setPredicate(pred2); + lreturn->changeRHSBinding(1); + + Predicate* pred3 = new Predicate(Predicate::OP_EQUAL); + suppvar->setPredicate(pred3); + suppvar->changeRHSBinding(15); + + BAndOperator* band = new BAndOperator(lreturn, 0, suppvar, 0); + + + //HashCount* hashAgg = new HashCount((Operator*) suppvar, 0, (Operator*) suppvar, 0); + //hashAgg->setHashFunction(new IdentityHashFunction(100001)); + //hashAgg->setHashTableSize(100001); + Operator* srcs[1]={band}; + //Operator* srcs[2]={suppvar2,suppkey2}; + int numCols[1]={1}; + //int numCols[2]={1,1}; + + char* temp6 = new char[30]; + sprintf(temp6, "BAndRLERLE"); + char* temp8 = new char[30]; + sprintf(temp8, "%s.out", temp6); + BlockPrinter* bPrint=new BlockPrinter(srcs, numCols, 1, temp8); + bPrint->printColumns(); + + + /* sprintf(temp8, "test%dRLE.dat", testnum); + ofstream flStream; + flStream.open(temp8, ios::out | ios::app); + flStream.seekp(ios::end); + flStream << "xval: " << (_file+i+8) << endl; + stopWatch.stopToFile(temp8); + flStream.close(); + */ + cout << "Query took: " << stopWatch.stop() << " ms" << endl; + + return success; +} diff --git a/pool/shard007/C++/0094271_Timer.cpp b/pool/shard007/C++/0094271_Timer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..266752eb3f8a5e847dbf3890c1a4fb810cabfc6d --- /dev/null +++ b/pool/shard007/C++/0094271_Timer.cpp @@ -0,0 +1,34 @@ +#include <Switch/Switch> + +using namespace System; +using namespace System::Threading; + +namespace Examples { + class Program { + public: + static void Main() { + int counter = 0; + TimerCallback callback = delegate_(object & state) { + Console::WriteLine("counter -> {0}", ++counter); + }; + + Timer timer(callback, 0, 10); + Thread::Sleep(100); + } + }; +} + +startup_(Examples::Program); + +// The example displays the following output: +// +// counter -> 1 +// counter -> 2 +// counter -> 3 +// counter -> 4 +// counter -> 5 +// counter -> 6 +// counter -> 7 +// counter -> 8 +// counter -> 9 +// counter -> 10 diff --git a/pool/shard007/C++/0094273_sslidentity.cc b/pool/shard007/C++/0094273_sslidentity.cc new file mode 100644 index 0000000000000000000000000000000000000000..bade0ae118df2427739823a2ca52c6c9120a42ec --- /dev/null +++ b/pool/shard007/C++/0094273_sslidentity.cc @@ -0,0 +1,262 @@ +/* + * Copyright 2004 The WebRTC Project Authors. All rights reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +// Handling of certificates and keypairs for SSLStreamAdapter's peer mode. +#include BOSS_WEBRTC_U_rtc_base__sslidentity_h //original-code:"rtc_base/sslidentity.h" + +#include <ctime> +#include <string> +#include <utility> + +#include BOSS_ABSEILCPP_U_absl__memory__memory_h //original-code:"absl/memory/memory.h" +#include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h" +#include BOSS_WEBRTC_U_rtc_base__logging_h //original-code:"rtc_base/logging.h" +#include BOSS_WEBRTC_U_rtc_base__opensslidentity_h //original-code:"rtc_base/opensslidentity.h" +#include BOSS_WEBRTC_U_rtc_base__sslfingerprint_h //original-code:"rtc_base/sslfingerprint.h" +#include BOSS_WEBRTC_U_rtc_base__third_party__base64__base64_h //original-code:"rtc_base/third_party/base64/base64.h" + +namespace rtc { + +////////////////////////////////////////////////////////////////////// +// KeyParams +////////////////////////////////////////////////////////////////////// + +const char kPemTypeCertificate[] = "CERTIFICATE"; +const char kPemTypeRsaPrivateKey[] = "RSA PRIVATE KEY"; +const char kPemTypeEcPrivateKey[] = "EC PRIVATE KEY"; + +KeyParams::KeyParams(KeyType key_type) { + if (key_type == KT_ECDSA) { + type_ = KT_ECDSA; + params_.curve = EC_NIST_P256; + } else if (key_type == KT_RSA) { + type_ = KT_RSA; + params_.rsa.mod_size = kRsaDefaultModSize; + params_.rsa.pub_exp = kRsaDefaultExponent; + } else { + RTC_NOTREACHED(); + } +} + +// static +KeyParams KeyParams::RSA(int mod_size, int pub_exp) { + KeyParams kt(KT_RSA); + kt.params_.rsa.mod_size = mod_size; + kt.params_.rsa.pub_exp = pub_exp; + return kt; +} + +// static +KeyParams KeyParams::ECDSA(ECCurve curve) { + KeyParams kt(KT_ECDSA); + kt.params_.curve = curve; + return kt; +} + +bool KeyParams::IsValid() const { + if (type_ == KT_RSA) { + return (params_.rsa.mod_size >= kRsaMinModSize && + params_.rsa.mod_size <= kRsaMaxModSize && + params_.rsa.pub_exp > params_.rsa.mod_size); + } else if (type_ == KT_ECDSA) { + return (params_.curve == EC_NIST_P256); + } + return false; +} + +RSAParams KeyParams::rsa_params() const { + RTC_DCHECK(type_ == KT_RSA); + return params_.rsa; +} + +ECCurve KeyParams::ec_curve() const { + RTC_DCHECK(type_ == KT_ECDSA); + return params_.curve; +} + +KeyType IntKeyTypeFamilyToKeyType(int key_type_family) { + return static_cast<KeyType>(key_type_family); +} + +////////////////////////////////////////////////////////////////////// +// SSLIdentity +////////////////////////////////////////////////////////////////////// + +bool SSLIdentity::PemToDer(const std::string& pem_type, + const std::string& pem_string, + std::string* der) { + // Find the inner body. We need this to fulfill the contract of + // returning pem_length. + size_t header = pem_string.find("-----BEGIN " + pem_type + "-----"); + if (header == std::string::npos) + return false; + + size_t body = pem_string.find("\n", header); + if (body == std::string::npos) + return false; + + size_t trailer = pem_string.find("-----END " + pem_type + "-----"); + if (trailer == std::string::npos) + return false; + + std::string inner = pem_string.substr(body + 1, trailer - (body + 1)); + + *der = Base64::Decode(inner, Base64::DO_PARSE_WHITE | Base64::DO_PAD_ANY | + Base64::DO_TERM_BUFFER); + return true; +} + +std::string SSLIdentity::DerToPem(const std::string& pem_type, + const unsigned char* data, + size_t length) { + std::stringstream result; + + result << "-----BEGIN " << pem_type << "-----\n"; + + std::string b64_encoded; + Base64::EncodeFromArray(data, length, &b64_encoded); + + // Divide the Base-64 encoded data into 64-character chunks, as per + // 4.3.2.4 of RFC 1421. + static const size_t kChunkSize = 64; + size_t chunks = (b64_encoded.size() + (kChunkSize - 1)) / kChunkSize; + for (size_t i = 0, chunk_offset = 0; i < chunks; + ++i, chunk_offset += kChunkSize) { + result << b64_encoded.substr(chunk_offset, kChunkSize); + result << "\n"; + } + + result << "-----END " << pem_type << "-----\n"; + + return result.str(); +} + +// static +SSLIdentity* SSLIdentity::GenerateWithExpiration(const std::string& common_name, + const KeyParams& key_params, + time_t certificate_lifetime) { + return OpenSSLIdentity::GenerateWithExpiration(common_name, key_params, + certificate_lifetime); +} + +// static +SSLIdentity* SSLIdentity::Generate(const std::string& common_name, + const KeyParams& key_params) { + return OpenSSLIdentity::GenerateWithExpiration( + common_name, key_params, kDefaultCertificateLifetimeInSeconds); +} + +// static +SSLIdentity* SSLIdentity::Generate(const std::string& common_name, + KeyType key_type) { + return OpenSSLIdentity::GenerateWithExpiration( + common_name, KeyParams(key_type), kDefaultCertificateLifetimeInSeconds); +} + +SSLIdentity* SSLIdentity::GenerateForTest(const SSLIdentityParams& params) { + return OpenSSLIdentity::GenerateForTest(params); +} + +// static +SSLIdentity* SSLIdentity::FromPEMStrings(const std::string& private_key, + const std::string& certificate) { + return OpenSSLIdentity::FromPEMStrings(private_key, certificate); +} + +// static +SSLIdentity* SSLIdentity::FromPEMChainStrings( + const std::string& private_key, + const std::string& certificate_chain) { + return OpenSSLIdentity::FromPEMChainStrings(private_key, certificate_chain); +} + +bool operator==(const SSLIdentity& a, const SSLIdentity& b) { + return static_cast<const OpenSSLIdentity&>(a) == + static_cast<const OpenSSLIdentity&>(b); +} +bool operator!=(const SSLIdentity& a, const SSLIdentity& b) { + return !(a == b); +} + +////////////////////////////////////////////////////////////////////// +// Helper Functions +////////////////////////////////////////////////////////////////////// + +// Read |n| bytes from ASN1 number string at *|pp| and return the numeric value. +// Update *|pp| and *|np| to reflect number of read bytes. +static inline int ASN1ReadInt(const unsigned char** pp, size_t* np, size_t n) { + const unsigned char* p = *pp; + int x = 0; + for (size_t i = 0; i < n; i++) + x = 10 * x + p[i] - '0'; + *pp = p + n; + *np = *np - n; + return x; +} + +int64_t ASN1TimeToSec(const unsigned char* s, size_t length, bool long_format) { + size_t bytes_left = length; + + // Make sure the string ends with Z. Doing it here protects the strspn call + // from running off the end of the string in Z's absense. + if (length == 0 || s[length - 1] != 'Z') + return -1; + + // Make sure we only have ASCII digits so that we don't need to clutter the + // code below and ASN1ReadInt with error checking. + size_t n = strspn(reinterpret_cast<const char*>(s), "0123456789"); + if (n + 1 != length) + return -1; + + int year; + + // Read out ASN1 year, in either 2-char "UTCTIME" or 4-char "GENERALIZEDTIME" + // format. Both format use UTC in this context. + if (long_format) { + // ASN1 format: yyyymmddhh[mm[ss[.fff]]]Z where the Z is literal, but + // RFC 5280 requires us to only support exactly yyyymmddhhmmssZ. + + if (bytes_left < 11) + return -1; + + year = ASN1ReadInt(&s, &bytes_left, 4); + year -= 1900; + } else { + // ASN1 format: yymmddhhmm[ss]Z where the Z is literal, but RFC 5280 + // requires us to only support exactly yymmddhhmmssZ. + + if (bytes_left < 9) + return -1; + + year = ASN1ReadInt(&s, &bytes_left, 2); + if (year < 50) // Per RFC 5280 4.1.2.5.1 + year += 100; + } + + std::tm tm; + tm.tm_year = year; + + // Read out remaining ASN1 time data and store it in |tm| in documented + // std::tm format. + tm.tm_mon = ASN1ReadInt(&s, &bytes_left, 2) - 1; + tm.tm_mday = ASN1ReadInt(&s, &bytes_left, 2); + tm.tm_hour = ASN1ReadInt(&s, &bytes_left, 2); + tm.tm_min = ASN1ReadInt(&s, &bytes_left, 2); + tm.tm_sec = ASN1ReadInt(&s, &bytes_left, 2); + + if (bytes_left != 1) { + // Now just Z should remain. Its existence was asserted above. + return -1; + } + + return TmToSeconds(tm); +} + +} // namespace rtc diff --git a/pool/shard007/C++/0094274_1099.cpp b/pool/shard007/C++/0094274_1099.cpp new file mode 100644 index 0000000000000000000000000000000000000000..576f99c0d735e76e7c25cde76849849ef631d701 --- /dev/null +++ b/pool/shard007/C++/0094274_1099.cpp @@ -0,0 +1,60 @@ +#include<cstdio> +#include<cstring> +#include<cmath> +#include<iostream> +#include<vector> +#include<queue> +#include<algorithm> +#include<string> +#define pf(i,s,t) for (int (i)=s;(i)<(t);(i)++) +#define mf(i,s,t) for (int (i)=s;(i)>(t);(i)--) +#define mt(a,d) memset((a),(d),sizeof(a)) +using namespace std; +const int maxn=16; +const int maxw=100+10; +int A[maxn],sum[1<<maxn],f[1<<maxn][maxw],vis[1<<maxn][maxw]; +int bitcount(int x) {return x==0?0:bitcount(x/2)+(x&1);} +int dp(int S,int x) +{ + if (vis[S][x]) return f[S][x]; + vis[S][x]=1; + int &ans=f[S][x]; + if (bitcount(S)==1) return ans=1; + int y=sum[S]/x; + for (int S0=(S-1)&S;S0;S0=(S0-1)&S) + { + int S1=S-S0; + /* printf("%d %d %d %d\n",sum[S1],sum[S0],x,y); + if (sum[S1]==3 && sum[S0]==9) + printf("aaa\n");*/ + if (sum[S0]%x==0&&dp(S0,min(x,sum[S0]/x))&&sum[S1]%x==0 && dp(S1,min(sum[S1]/x,x))) + return ans=1; + if (sum[S0]%y==0&&dp(S0,min(y,sum[S0]/y))&&sum[S1]%y==0 && dp(S1,min(sum[S1]/y,y))) + return ans=1; + } + return ans=0; +} +main() +{ + int N; + int ck=0; + while (scanf("%d",&N)==1) + { + int x,y; + if (N==0) break; + scanf("%d%d",&x,&y); + pf(i,0,N) + scanf("%d",&A[i]); + memset(sum,0,sizeof(sum)); + for (int S=0;S<(1<<N);S++) + for (int i=0;i<N;i++) + if (S&(1<<i)) sum[S]+=A[i]; + memset(vis,0,sizeof(vis)); + int ALL=(1<<N)-1; + int ans; + if (sum[ALL]!=x*y || sum[ALL]%x!=0) ans=0; + else ans=dp(ALL,min(x,y)); + printf("Case %d: %s\n",++ck,ans==1?"Yes":"No"); + } + return 0; +} diff --git a/pool/shard007/C++/0094275_ApacheConnector.cpp b/pool/shard007/C++/0094275_ApacheConnector.cpp new file mode 100644 index 0000000000000000000000000000000000000000..725cffd23f056c51a738315baa61141b61000caf --- /dev/null +++ b/pool/shard007/C++/0094275_ApacheConnector.cpp @@ -0,0 +1,289 @@ +// +// ApacheConnector.cpp +// +// $Id: //poco/1.4/ApacheConnector/src/ApacheConnector.cpp#2 $ +// +// Copyright (c) 2006-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "ApacheConnector.h" +#include "ApacheApplication.h" +#include "ApacheServerRequest.h" +#include "ApacheServerResponse.h" +#include "ApacheRequestHandlerFactory.h" +#include "Poco/Net/HTTPRequestHandler.h" +#include <memory> +#include "httpd.h" +#include "http_connection.h" +#include "http_config.h" +#include "http_core.h" +#include "http_protocol.h" +#include "http_log.h" +#include "apr.h" +#include "apr_lib.h" +#include "apr_strings.h" +#include "apr_buckets.h" +#include "apr_file_info.h" +#include "apr_hash.h" +#define APR_WANT_STRFUNC +#include "apr_want.h" +#include "http_request.h" +#include "util_filter.h" + + +using Poco::Net::HTTPServerRequest; +using Poco::Net::HTTPServerResponse; +using Poco::Net::HTTPRequestHandler; +using Poco::Net::HTTPResponse; + + +extern "C" module AP_MODULE_DECLARE_DATA poco_module; + + +ApacheRequestRec::ApacheRequestRec(request_rec* pRec): + _pRec(pRec) +{ +} + + +bool ApacheRequestRec::haveRequestBody() +{ + return ap_should_client_block(_pRec) != 0; +} + + +int ApacheRequestRec::readRequest(char* buffer, int length) +{ + return ap_get_client_block(_pRec, buffer, length); +} + + +void ApacheRequestRec::writeResponse(const char* buffer, int length) +{ + ap_rwrite(buffer, length, _pRec); +} + + +void ApacheRequestRec::redirect(const std::string& uri, int status) +{ + apr_table_set(_pRec->headers_out, "Location", uri.c_str()); + _pRec->connection->keepalive = AP_CONN_CLOSE; + _pRec->status = status; + ap_set_keepalive(_pRec); + ap_send_error_response(_pRec, 0); +} + + +void ApacheRequestRec::sendErrorResponse(int status) +{ + _pRec->connection->keepalive = AP_CONN_CLOSE; + _pRec->status = status; + ap_set_keepalive(_pRec); + + ap_send_error_response(_pRec, 0); +} + + +void ApacheRequestRec::addHeader(const std::string& key, const std::string& value) +{ + const apr_array_header_t *arr = apr_table_elts(_pRec->headers_out); + apr_table_add(const_cast<apr_table_t*>(reinterpret_cast<const apr_table_t*>(arr)), key.c_str(), value.c_str()); +} + + +void ApacheRequestRec::setContentType(const std::string& mediaType) +{ + ap_set_content_type(_pRec, mediaType.c_str()); +} + + +int ApacheRequestRec::sendFile(const std::string& path, unsigned int fileSize, const std::string& mediaType) +{ + apr_file_t *thefile = 0; + apr_finfo_t finfo; + apr_size_t nBytes; + + // setting content-type + ap_set_content_type(_pRec, mediaType.c_str()); + + // opening file + if (apr_file_open(&thefile, path.c_str(), APR_READ, APR_UREAD | APR_GREAD, _pRec->pool) == APR_SUCCESS) + { + // getting fileinfo + apr_file_info_get(&finfo, APR_FINFO_NORM, thefile); + + // setting last-updated & co + ap_update_mtime(_pRec, finfo.mtime); + ap_set_last_modified(_pRec); + ap_set_content_length(_pRec, fileSize); + + // sending file + ap_send_fd(thefile, _pRec, 0, fileSize, &nBytes); + + // well done + return 0; + } + + // file not opened successfully -> produce an exception in C++ code + return 1; +} + + +void ApacheRequestRec::copyHeaders(ApacheServerRequest& request) +{ + const apr_array_header_t* arr = apr_table_elts(_pRec->headers_in); + const apr_table_entry_t* elts = (const apr_table_entry_t *)arr->elts; + + request.setMethod(_pRec->method); + request.setURI(_pRec->unparsed_uri); + + // iterating over raw-headers and printing them + for (int i = 0; i < arr->nelts; i++) + { + request.add(elts[i].key, elts[i].val); + } +} + + +void ApacheConnector::log(const char* file, int line, int level, int status, const char *text) +{ + ap_log_error(file, line, level, 0, NULL, "%s", text); +} + + +extern "C" int ApacheConnector_handler(request_rec *r) +{ + ApacheRequestRec rec(r); + ApacheApplication& app(ApacheApplication::instance()); + + try + { + // ensure application is ready + app.setup(); + + // if the ApacheRequestHandler declines handling - we stop + // request handling here and let other modules do their job! + if (!app.factory().mustHandle(r->uri)) + return DECLINED; + + apr_status_t rv; + if ((rv = ap_setup_client_block(r, REQUEST_CHUNKED_DECHUNK))) + return rv; + + std::auto_ptr<ApacheServerRequest> pRequest(new ApacheServerRequest( + &rec, + r->connection->local_ip, + r->connection->local_addr->port, + r->connection->remote_ip, + r->connection->remote_addr->port)); + + std::auto_ptr<ApacheServerResponse> pResponse(new ApacheServerResponse(pRequest.get())); + + // add header information to request + rec.copyHeaders(*pRequest); + + try + { + std::auto_ptr<HTTPRequestHandler> pHandler(app.factory().createRequestHandler(*pRequest)); + + if (pHandler.get()) + { + pHandler->handleRequest(*pRequest, *pResponse); + } + else + { + pResponse->sendErrorResponse(HTTP_NOT_IMPLEMENTED); + } + } + catch (...) + { + pResponse->sendErrorResponse(HTTP_INTERNAL_SERVER_ERROR); + throw; + } + } + catch (Poco::Exception& exc) + { + ApacheConnector::log(__FILE__, __LINE__, ApacheConnector::PRIO_ERROR, 0, exc.displayText().c_str()); + } + catch (...) + { + ApacheConnector::log(__FILE__, __LINE__, ApacheConnector::PRIO_ERROR, 0, "Unknown exception"); + } + return OK; +} + + +extern "C" void ApacheConnector_register_hooks(apr_pool_t *p) +{ + ap_hook_handler(ApacheConnector_handler, NULL, NULL, APR_HOOK_MIDDLE); +} + + +extern "C" const char* ApacheConnector_uris(cmd_parms *cmd, void *in_dconf, const char *in_str) +{ + try + { + ApacheApplication::instance().factory().handleURIs(in_str); + } + catch (Poco::Exception& exc) + { + ApacheConnector::log(__FILE__, __LINE__, ApacheConnector::PRIO_ERROR, 0, exc.displayText().c_str()); + } + catch (...) + { + ApacheConnector::log(__FILE__, __LINE__, ApacheConnector::PRIO_ERROR, 0, "Unknown exception"); + } + return 0; +} + + +extern "C" const char* ApacheConnector_config(cmd_parms *cmd, void *in_dconf, const char *in_str) +{ + try + { + ApacheApplication::instance().loadConfiguration(in_str); + } + catch (Poco::Exception& exc) + { + ApacheConnector::log(__FILE__, __LINE__, ApacheConnector::PRIO_ERROR, 0, exc.displayText().c_str()); + } + catch (...) + { + ApacheConnector::log(__FILE__, __LINE__, ApacheConnector::PRIO_ERROR, 0, "Unknown exception"); + } + return 0; +} + + +extern "C" const command_rec ApacheConnector_cmds[] = +{ + AP_INIT_RAW_ARGS( + "AddPocoRequestHandler", + reinterpret_cast<cmd_func>(ApacheConnector_uris), + NULL, + RSRC_CONF, + "POCO RequestHandlerFactory class name followed by shared library path followed by a list of ' ' separated URIs that must be handled by this module."), + AP_INIT_RAW_ARGS( + "AddPocoConfig", + reinterpret_cast<cmd_func>(ApacheConnector_config), + NULL, + RSRC_CONF, + "Path of the POCO configuration file."), + { NULL } +}; + + +module AP_MODULE_DECLARE_DATA poco_module = +{ + STANDARD20_MODULE_STUFF, + NULL, + NULL, + NULL, + NULL, + ApacheConnector_cmds, + ApacheConnector_register_hooks +}; diff --git a/pool/shard007/C++/0094278_Amidar.cpp b/pool/shard007/C++/0094278_Amidar.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e7db06ceb1a5e6b9b0767b02357bd8df78fc9acf --- /dev/null +++ b/pool/shard007/C++/0094278_Amidar.cpp @@ -0,0 +1,129 @@ +/* ***************************************************************************** + * Xitari + * + * Copyright 2014 Google Inc. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * ***************************************************************************** + * A.L.E (Arcade Learning Environment) + * Copyright (c) 2009-2013 by Yavar Naddaf, Joel Veness, Marc G. Bellemare and + * the Reinforcement Learning and Artificial Intelligence Laboratory + * Released under the GNU General Public License; see License.txt for details. + * + * Based on: Stella -- "An Atari 2600 VCS Emulator" + * Copyright (c) 1995-2007 by Bradford W. Mott and the Stella team + * + * ***************************************************************************** + */ +#include "Amidar.hpp" + +#include "../RomUtils.hpp" + +using namespace ale; + + +AmidarSettings::AmidarSettings() { + + reset(); +} + + +/* create a new instance of the rom */ +RomSettings* AmidarSettings::clone() const { + + RomSettings* rval = new AmidarSettings(); + *rval = *this; + return rval; +} + + +/* process the latest information from ALE */ +void AmidarSettings::step(const System& system) { + + // update the reward + reward_t score = getDecimalScore(0xD9, 0xDA, 0xDB, &system); + m_reward = score - m_score; + m_score = score; + + // update terminal status + int livesByte = readRam(&system, 0xD6); + + // MGB it takes one step for the system to reset; this assumes we've + // reset + m_terminal = (livesByte == 0x80); + m_lives = (livesByte & 0xF); +} + + +/* is end of game */ +bool AmidarSettings::isTerminal() const { + + return m_terminal; +}; + + +/* get the most recently observed reward */ +reward_t AmidarSettings::getReward() const { + + return m_reward; +} + + +/* is an action part of the minimal set? */ +bool AmidarSettings::isMinimal(const Action &a) const { + + switch (a) { + case PLAYER_A_NOOP: + case PLAYER_A_FIRE: + case PLAYER_A_UP: + case PLAYER_A_RIGHT: + case PLAYER_A_LEFT: + case PLAYER_A_DOWN: + case PLAYER_A_UPFIRE: + case PLAYER_A_RIGHTFIRE: + case PLAYER_A_LEFTFIRE: + case PLAYER_A_DOWNFIRE: + return true; + default: + return false; + } +} + + +/* reset the state of the game */ +void AmidarSettings::reset() { + + m_reward = 0; + m_score = 0; + m_terminal = false; + m_lives = 3; +} + + +/* saves the state of the rom settings */ +void AmidarSettings::saveState(Serializer & ser) { + ser.putInt(m_reward); + ser.putInt(m_score); + ser.putBool(m_terminal); + ser.putInt(m_lives); +} + +// loads the state of the rom settings +void AmidarSettings::loadState(Deserializer & ser) { + m_reward = ser.getInt(); + m_score = ser.getInt(); + m_terminal = ser.getBool(); + m_lives = ser.getInt(); +} + diff --git a/pool/shard007/C++/0094282_keyword_matcher.cpp b/pool/shard007/C++/0094282_keyword_matcher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..68d20980f00fd215dc1cce71713ac1a996d99b8e --- /dev/null +++ b/pool/shard007/C++/0094282_keyword_matcher.cpp @@ -0,0 +1,173 @@ +#include "search/keyword_matcher.hpp" + +#include "indexer/search_delimiters.hpp" +#include "indexer/search_string_utils.hpp" + +#include "base/assert.hpp" +#include "base/buffer_vector.hpp" +#include "base/stl_add.hpp" + +#include <algorithm> +#include <sstream> + +using namespace std; + +namespace search +{ +KeywordMatcher::KeywordMatcher() +{ + Clear(); +} + +void KeywordMatcher::Clear() +{ + m_keywords.clear(); + m_prefix.clear(); +} + +void KeywordMatcher::SetKeywords(strings::UniString const * keywords, size_t count, + strings::UniString const & prefix) +{ + m_keywords.assign(keywords, keywords + count); + m_prefix = prefix; +} + +KeywordMatcher::Score KeywordMatcher::CalcScore(string const & name) const +{ + return CalcScore(NormalizeAndSimplifyString(name)); +} + +KeywordMatcher::Score KeywordMatcher::CalcScore(strings::UniString const & name) const +{ + buffer_vector<strings::UniString, kMaxNumTokens> tokens; + SplitUniString(name, MakeBackInsertFunctor(tokens), Delimiters()); + + return CalcScore(tokens.data(), tokens.size()); +} + +KeywordMatcher::Score KeywordMatcher::CalcScore(strings::UniString const * tokens, + size_t count) const +{ + // Some names can have too many tokens. Trim them. + count = min(count, kMaxNumTokens); + + vector<bool> isQueryTokenMatched(m_keywords.size()); + vector<bool> isNameTokenMatched(count); + uint32_t sumTokenMatchDistance = 0; + int8_t prevTokenMatchDistance = 0; + bool prefixMatched = true; + + for (int i = 0; i < m_keywords.size(); ++i) + { + for (int j = 0; j < count && !isQueryTokenMatched[i]; ++j) + { + if (!isNameTokenMatched[j] && m_keywords[i] == tokens[j]) + { + isQueryTokenMatched[i] = isNameTokenMatched[j] = true; + int8_t const tokenMatchDistance = i - j; + sumTokenMatchDistance += abs(tokenMatchDistance - prevTokenMatchDistance); + prevTokenMatchDistance = tokenMatchDistance; + } + } + } + + if (!m_prefix.empty()) + { + prefixMatched = false; + for (int j = 0; j < count && !prefixMatched; ++j) + { + if (!isNameTokenMatched[j] && + strings::StartsWith(tokens[j].begin(), tokens[j].end(), m_prefix.begin(), m_prefix.end())) + { + isNameTokenMatched[j] = prefixMatched = true; + int8_t const tokenMatchDistance = int(m_keywords.size()) - j; + sumTokenMatchDistance += abs(tokenMatchDistance - prevTokenMatchDistance); + } + } + } + + uint8_t numQueryTokensMatched = 0; + for (size_t i = 0; i < isQueryTokenMatched.size(); ++i) + { + if (isQueryTokenMatched[i]) + ++numQueryTokensMatched; + } + + Score score; + score.m_fullQueryMatched = prefixMatched && (numQueryTokensMatched == isQueryTokenMatched.size()); + score.m_prefixMatched = prefixMatched; + score.m_numQueryTokensAndPrefixMatched = numQueryTokensMatched + (prefixMatched ? 1 : 0); + + score.m_nameTokensMatched = 0; + score.m_nameTokensLength = 0; + for (size_t i = 0; i < count; ++i) + { + if (isNameTokenMatched[i]) + score.m_nameTokensMatched |= (1 << (kMaxNumTokens - 1 - i)); + score.m_nameTokensLength += tokens[i].size(); + } + + score.m_sumTokenMatchDistance = sumTokenMatchDistance; + return score; +} + +KeywordMatcher::Score::Score() + : m_sumTokenMatchDistance(0) + , m_nameTokensMatched(0) + , m_nameTokensLength(0) + , m_numQueryTokensAndPrefixMatched(0) + , m_fullQueryMatched(false) + , m_prefixMatched(false) +{ +} + +bool KeywordMatcher::Score::operator<(KeywordMatcher::Score const & s) const +{ + if (m_fullQueryMatched != s.m_fullQueryMatched) + return m_fullQueryMatched < s.m_fullQueryMatched; + if (m_numQueryTokensAndPrefixMatched != s.m_numQueryTokensAndPrefixMatched) + return m_numQueryTokensAndPrefixMatched < s.m_numQueryTokensAndPrefixMatched; + if (m_prefixMatched != s.m_prefixMatched) + return m_prefixMatched < s.m_prefixMatched; + if (m_nameTokensMatched != s.m_nameTokensMatched) + return m_nameTokensMatched < s.m_nameTokensMatched; + if (m_sumTokenMatchDistance != s.m_sumTokenMatchDistance) + return m_sumTokenMatchDistance > s.m_sumTokenMatchDistance; + + return false; +} + +bool KeywordMatcher::Score::operator==(KeywordMatcher::Score const & s) const +{ + return m_sumTokenMatchDistance == s.m_sumTokenMatchDistance + && m_nameTokensMatched == s.m_nameTokensMatched + && m_numQueryTokensAndPrefixMatched == s.m_numQueryTokensAndPrefixMatched + && m_fullQueryMatched == s.m_fullQueryMatched + && m_prefixMatched == s.m_prefixMatched; +} + +bool KeywordMatcher::Score::LessInTokensLength(Score const & s) const +{ + if (m_fullQueryMatched) + { + ASSERT(s.m_fullQueryMatched, ()); + return m_nameTokensLength > s.m_nameTokensLength; + } + return false; +} + +string DebugPrint(KeywordMatcher::Score const & score) +{ + ostringstream out; + out << "KeywordMatcher::Score("; + out << "FQM=" << score.m_fullQueryMatched; + out << ",nQTM=" << static_cast<int>(score.m_numQueryTokensAndPrefixMatched); + out << ",PM=" << score.m_prefixMatched; + out << ",NTM="; + for (int i = static_cast<int>(kMaxNumTokens) - 1; i >= 0; --i) + out << ((score.m_nameTokensMatched >> i) & 1); + out << ",STMD=" << score.m_sumTokenMatchDistance; + out << ")"; + return out.str(); +} +} // namespace search diff --git a/pool/shard007/C++/0094283_slp-pr50819.cc b/pool/shard007/C++/0094283_slp-pr50819.cc new file mode 100644 index 0000000000000000000000000000000000000000..96f82c302185e4cf4275578f917234c755180ac7 --- /dev/null +++ b/pool/shard007/C++/0094283_slp-pr50819.cc @@ -0,0 +1,53 @@ +/* { dg-do compile } */ +/* { dg-require-effective-target vect_float } */ + +typedef float Value; + +struct LorentzVector +{ + + LorentzVector(Value x=0, Value y=0, Value z=0, Value t=0) : +theX(x),theY(y),theZ(z),theT(t){} + LorentzVector & operator+=(const LorentzVector & a) { + theX += a.theX; + theY += a.theY; + theZ += a.theZ; + theT += a.theT; + return *this; + } + + Value theX; + Value theY; + Value theZ; + Value theT; +} __attribute__ ((aligned(16))); + +inline LorentzVector +operator+(LorentzVector const & a, LorentzVector const & b) { + return +LorentzVector(a.theX+b.theX,a.theY+b.theY,a.theZ+b.theZ,a.theT+b.theT); +} + +inline LorentzVector +operator*(LorentzVector const & a, Value s) { + return LorentzVector(a.theX*s,a.theY*s,a.theZ*s,a.theT*s); +} + +inline LorentzVector +operator*(Value s, LorentzVector const & a) { + return a*s; +} + + +void sum1(LorentzVector & res, Value s, LorentzVector const & v1, LorentzVector +const & v2) { + res += s*(v1+v2); +} + +void sum2(LorentzVector & res, Value s, LorentzVector const & v1, LorentzVector +const & v2) { + res = res + s*(v1+v2); +} + +/* { dg-final { scan-tree-dump-times "Vectorized basic-block" 2 "slp" } } */ +/* { dg-final { cleanup-tree-dump "slp" } } */ diff --git a/pool/shard007/C++/0094287_filterByRegion.cpp b/pool/shard007/C++/0094287_filterByRegion.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e56402373472b563674bef269b43a985ab6f41b --- /dev/null +++ b/pool/shard007/C++/0094287_filterByRegion.cpp @@ -0,0 +1,43 @@ +#include <string> +#include <vector> + +#include "bode/intervalReader.h" +#include "bode/writer.h" +#include "bode/locationFilter.h" +#include "bode/flags.h" + +int main(int argc,char **argv) { + int total,kept; + bode::Flags *flagset; + std::vector<std::string> args; + bool invert; + + flagset = new bode::Flags(); + flagset->add("invert",bode::BOOL,"exclude reads in regions of interest"); + flagset->parse(argc,argv); + args = flagset->positionalArgs(); + + invert = flagset->getBool("invert"); + std::string regionFN(args[1]); + std::string inFN(args[2]); + std::string outFN(args[3]); + + bode::IntervalReader *regions = bode::IntervalReader::open(regionFN); + bode::LocationFilter *f = new bode::LocationFilter(regions,invert); + regions->close(); + + bode::IntervalReader *input = bode::IntervalReader::open(inFN); + bode::Writer *output = input->getWriter(); + output->open(outFN,input->header()); + f->filter(input,output,kept,total); + input->close(); + output->close(); + fprintf(stderr,"kept %d / %d\n",kept,total); + + delete regions; + delete f; + delete input; + delete output; + + return 0; +} diff --git a/pool/shard007/C++/0094292_persistent_buffer_test.cc b/pool/shard007/C++/0094292_persistent_buffer_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..38c4fe9f882eae417e39d1d1b83e4c44bf5b511a --- /dev/null +++ b/pool/shard007/C++/0094292_persistent_buffer_test.cc @@ -0,0 +1,164 @@ +// Copyright 2021 The Pigweed Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may not +// use this file except in compliance with the License. You may obtain a copy of +// the License at +// +// https://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 "pw_persistent_ram/persistent_buffer.h" + +#include <cstddef> +#include <span> +#include <type_traits> + +#include "gtest/gtest.h" +#include "pw_bytes/span.h" +#include "pw_random/xor_shift.h" + +namespace pw::persistent_ram { +namespace { + +class PersistentTest : public ::testing::Test { + protected: + static constexpr size_t kBufferSize = 256; + PersistentTest() { ZeroPersistentMemory(); } + + // Emulate invalidation of persistent section(s). + void ZeroPersistentMemory() { memset(buffer_, 0, sizeof(buffer_)); } + void RandomFillMemory() { + random::XorShiftStarRng64 rng(0x9ad75); + StatusWithSize sws = rng.Get(buffer_); + ASSERT_TRUE(sws.ok()); + ASSERT_EQ(sws.size(), sizeof(buffer_)); + } + + PersistentBuffer<kBufferSize>& GetPersistentBuffer() { + return *(new (buffer_) PersistentBuffer<kBufferSize>()); + } + + // Allocate a chunk of aligned storage that can be independently controlled. + alignas(PersistentBuffer<kBufferSize>) + std::byte buffer_[sizeof(PersistentBuffer<kBufferSize>)]; +}; + +TEST_F(PersistentTest, DefaultConstructionAndDestruction) { + constexpr uint32_t kExpectedNumber = 0x6C2C6582; + { + // Emulate a boot where the persistent sections were invalidated. + // Although the fixture always does this, we do this an extra time to be + // 100% confident that an integrity check cannot be accidentally selected + // which results in reporting there is valid data when zero'd. + ZeroPersistentMemory(); + auto& persistent = GetPersistentBuffer(); + auto writer = persistent.GetWriter(); + EXPECT_EQ(persistent.size(), 0u); + + writer.Write(std::as_bytes(std::span(&kExpectedNumber, 1))) + .IgnoreError(); // TODO(pwbug/387): Handle Status properly + ASSERT_TRUE(persistent.has_value()); + + persistent.~PersistentBuffer(); // Emulate shutdown / global destructors. + } + + { // Emulate a boot where persistent memory was kept as is. + auto& persistent = GetPersistentBuffer(); + ASSERT_TRUE(persistent.has_value()); + EXPECT_EQ(persistent.size(), sizeof(kExpectedNumber)); + + uint32_t temp = 0; + memcpy(&temp, persistent.data(), sizeof(temp)); + EXPECT_EQ(temp, kExpectedNumber); + } +} + +TEST_F(PersistentTest, LongData) { + constexpr std::string_view kTestString( + "A nice string should remain valid even if written incrementally!"); + constexpr size_t kWriteSize = 5; + + { // Initialize the buffer. + RandomFillMemory(); + auto& persistent = GetPersistentBuffer(); + ASSERT_FALSE(persistent.has_value()); + + auto writer = persistent.GetWriter(); + for (size_t i = 0; i < kTestString.length(); i += kWriteSize) { + writer + .Write(kTestString.data() + i, + std::min(kWriteSize, kTestString.length() - i)) + .IgnoreError(); // TODO(pwbug/387): Handle Status properly + } + // Need to manually write a null terminator since std::string_view doesn't + // include one in the string length. + writer.Write(std::byte(0)) + .IgnoreError(); // TODO(pwbug/387): Handle Status properly + + persistent.~PersistentBuffer(); // Emulate shutdown / global destructors. + } + + { // Ensure data is valid. + auto& persistent = GetPersistentBuffer(); + ASSERT_TRUE(persistent.has_value()); + ASSERT_STREQ(kTestString.data(), + reinterpret_cast<const char*>(persistent.data())); + } +} + +TEST_F(PersistentTest, ZeroDataIsNoValue) { + ZeroPersistentMemory(); + auto& persistent = GetPersistentBuffer(); + EXPECT_FALSE(persistent.has_value()); +} + +TEST_F(PersistentTest, RandomDataIsInvalid) { + RandomFillMemory(); + auto& persistent = GetPersistentBuffer(); + ASSERT_FALSE(persistent.has_value()); +} + +TEST_F(PersistentTest, AppendingData) { + constexpr std::string_view kTestString("Test string one!"); + constexpr uint32_t kTestNumber = 42; + + { // Initialize the buffer. + RandomFillMemory(); + auto& persistent = GetPersistentBuffer(); + auto writer = persistent.GetWriter(); + EXPECT_EQ(persistent.size(), 0u); + + // Write an integer. + writer.Write(std::as_bytes(std::span(&kTestNumber, 1))) + .IgnoreError(); // TODO(pwbug/387): Handle Status properly + ASSERT_TRUE(persistent.has_value()); + + persistent.~PersistentBuffer(); // Emulate shutdown / global destructors. + } + + { // Get a pointer to the buffer and validate the contents. + auto& persistent = GetPersistentBuffer(); + ASSERT_TRUE(persistent.has_value()); + EXPECT_EQ(persistent.size(), sizeof(kTestNumber)); + + // Write more data. + auto writer = persistent.GetWriter(); + EXPECT_EQ(persistent.size(), sizeof(kTestNumber)); + writer.Write(std::as_bytes(std::span<const char>(kTestString))) + .IgnoreError(); // TODO(pwbug/387): Handle Status properly + + persistent.~PersistentBuffer(); // Emulate shutdown / global destructors. + } + { // Ensure data was appended. + auto& persistent = GetPersistentBuffer(); + ASSERT_TRUE(persistent.has_value()); + EXPECT_EQ(persistent.size(), sizeof(kTestNumber) + kTestString.length()); + } +} + +} // namespace +} // namespace pw::persistent_ram diff --git a/pool/shard007/C++/0094293_serialize_test.cpp b/pool/shard007/C++/0094293_serialize_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..554f6038fdd2c667a3308638b63476b15fc61037 --- /dev/null +++ b/pool/shard007/C++/0094293_serialize_test.cpp @@ -0,0 +1,46 @@ +/* +This file is part of Baxter Pick and Learn. + +Baxter Pick and Learn is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Nagen is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see <http://www.gnu.org/licenses/>. + +Copyright 2014 Charles Hubain <charles.hubain@haxelion.eu> +*/ + +#include <iostream> +#include <opencv2/imgproc/imgproc.hpp> +#include <vector> +#include "piece.h" + +using namespace std; + +int main(int argc, char **argv) +{ + vector<cv::Point> shape; + shape.push_back(cv::Point(0,0)); + shape.push_back(cv::Point(1,0)); + shape.push_back(cv::Point(1,1)); + shape.push_back(cv::Point(0,1)); + float height = 0.8, drop_position[3], drop_orientation[4], picking_orientation[4]; + std::string name("Serialization test piece"); + for(int i = 0; i<3; i++) + drop_position[i] = 0.2*(i+1); + for(int i = 0; i<4; i++) + { + drop_orientation[i] = 0.3*(i+1); + picking_orientation[i] = 0.5*(i+1); + } + Piece piece(shape, height, picking_orientation, name); + piece.setDropPosition(drop_position, drop_orientation); + cout << piece.serialize(); +} diff --git a/pool/shard007/C++/0094294_UnitFormPrimeExpert.cpp b/pool/shard007/C++/0094294_UnitFormPrimeExpert.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b8fb1825143e61519602fbc16bd1844d2e83aaf7 --- /dev/null +++ b/pool/shard007/C++/0094294_UnitFormPrimeExpert.cpp @@ -0,0 +1,90 @@ +//--------------------------------------------------------------------------- +/* + PrimeExpert, tool to calculate whether a number is prime + Copyright (C) 2008 Richel Bilderbeek + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ +//--------------------------------------------------------------------------- +// From http://www.richelbilderbeek.nl +//--------------------------------------------------------------------------- +#include <boost/shared_ptr.hpp> +#include <boost/timer.hpp> +#include <boost/lexical_cast.hpp> +#include <vcl.h> +#pragma hdrstop + +#include "UnitFormPrimeExpert.h" +#include "UnitFormPrimeExpertAbout.h" +//--------------------------------------------------------------------------- +#pragma package(smart_init) +#pragma resource "*.dfm" +TFormPrimeExpert *FormPrimeExpert; +//--------------------------------------------------------------------------- +__fastcall TFormPrimeExpert::TFormPrimeExpert(TComponent* Owner) + : TForm(Owner) +{ + RichEdit1->Clear(); +} +//--------------------------------------------------------------------------- +void __fastcall TFormPrimeExpert::EditValueChange(TObject *Sender) +{ + { + int temp = 0; + if ( IsInt(EditValue->Text.c_str(),temp) == false) + { + RichEdit1->Lines->Insert(0,"NaN"); + return; + } + } + const int value = boost::lexical_cast<int>( EditValue->Text.c_str() ); + if (value < 2) + { + RichEdit1->Lines->Insert(0,"Not prime"); + return; + } + if (value == 2) + { + RichEdit1->Lines->Insert(0,"Prime"); + return; + } + const boost::timer t; + const bool isPrime = mPrimeExpert.IsPrime(value); + const double time = t.elapsed(); + const String text + = String(isPrime == true ? "Prime" : "Not prime") + + String(" (") + + FloatToStr(time) + + String(" sec)"); + RichEdit1->Lines->Insert(0,text); +} +//--------------------------------------------------------------------------- +//From http://www.richelbilderbeek.nl/CppStrIsInt.htm +bool IsInt(const std::string& s, int& rInt) +{ + std::istringstream i(s); + if (!(i >> rInt)) + { + rInt = 0; + return false; + } + return true; +} +//--------------------------------------------------------------------------- + +void __fastcall TFormPrimeExpert::ButtonAboutClick(TObject *Sender) +{ + boost::shared_ptr<TFormPrimeExpertAbout> form(new TFormPrimeExpertAbout(0)); + form->ShowModal(); +} +//--------------------------------------------------------------------------- diff --git a/pool/shard007/C++/0094297_Shortest_Word_Distance_II.cpp b/pool/shard007/C++/0094297_Shortest_Word_Distance_II.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a151f42b53e7e5127439c1e58becdcf0ef01f4d4 --- /dev/null +++ b/pool/shard007/C++/0094297_Shortest_Word_Distance_II.cpp @@ -0,0 +1,33 @@ +class WordDistance { + + unordered_map<string, vector<int>> m; + +public: + WordDistance(vector<string>& words) { + for(int i = 0;i < words.size();i++) + m[words[i]].push_back(i); + } + + int shortest(string word1, string word2) { + vector<int> v1 = m[word1]; + vector<int> v2 = m[word2]; + int i(0),j(0),res(INT_MAX); + while(i < v1.size() && j < v2.size()) + { + int i1 = v1[i]; + int i2 = v2[j]; + res = min(abs(i1-i2), res); + if(i1 > i2) + j++; + else + i++; + } + return res; + } +}; + + +// Your WordDistance object will be instantiated and called as such: +// WordDistance wordDistance(words); +// wordDistance.shortest("word1", "word2"); +// wordDistance.shortest("anotherWord1", "anotherWord2"); \ No newline at end of file diff --git a/pool/shard007/C++/0094298_QXmppRpcManager.cpp b/pool/shard007/C++/0094298_QXmppRpcManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..636e13ae71c5381df31f1250b50409504b02cccb --- /dev/null +++ b/pool/shard007/C++/0094298_QXmppRpcManager.cpp @@ -0,0 +1,181 @@ +/* + * Copyright (C) 2008-2019 The QXmpp developers + * + * Author: + * Jeremy Lainé + * + * Source: + * https://github.com/qxmpp-project/qxmpp + * + * This file is a part of QXmpp library. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + */ + +#include "QXmppClient.h" +#include "QXmppConstants_p.h" +#include "QXmppInvokable.h" +#include "QXmppRemoteMethod.h" +#include "QXmppRpcIq.h" +#include "QXmppRpcManager.h" + +/// Constructs a QXmppRpcManager. + +QXmppRpcManager::QXmppRpcManager() +{ +} + +/// Adds a local interface which can be queried using RPC. +/// +/// \param interface + +void QXmppRpcManager::addInvokableInterface( QXmppInvokable *interface ) +{ + m_interfaces[ interface->metaObject()->className() ] = interface; +} + +/// Invokes a remote interface using RPC. +/// +/// \param iq + +void QXmppRpcManager::invokeInterfaceMethod( const QXmppRpcInvokeIq &iq ) +{ + QXmppStanza::Error error; + + const QStringList methodBits = iq.method().split('.'); + if (methodBits.size() != 2) + return; + const QString interface = methodBits.first(); + const QString method = methodBits.last(); + QXmppInvokable *iface = m_interfaces.value(interface); + if (iface) + { + if ( iface->isAuthorized( iq.from() ) ) + { + + if ( iface->interfaces().contains(method) ) + { + QVariant result = iface->dispatch(method.toLatin1(), + iq.arguments() ); + QXmppRpcResponseIq resultIq; + resultIq.setId(iq.id()); + resultIq.setTo(iq.from()); + resultIq.setValues(QVariantList() << result); + client()->sendPacket( resultIq ); + return; + } + else + { + error.setType(QXmppStanza::Error::Cancel); + error.setCondition(QXmppStanza::Error::ItemNotFound); + } + } + else + { + error.setType(QXmppStanza::Error::Auth); + error.setCondition(QXmppStanza::Error::Forbidden); + } + } + else + { + error.setType(QXmppStanza::Error::Cancel); + error.setCondition(QXmppStanza::Error::ItemNotFound); + } + QXmppRpcErrorIq errorIq; + errorIq.setId(iq.id()); + errorIq.setTo(iq.from()); + errorIq.setQuery(iq); + errorIq.setError(error); + client()->sendPacket(errorIq); +} + +/// Calls a remote method using RPC with the specified arguments. +/// +/// \note This method blocks until the response is received, and it may +/// cause XMPP stanzas to be lost! + +QXmppRemoteMethodResult QXmppRpcManager::callRemoteMethod( const QString &jid, + const QString &interface, + const QVariant &arg1, + const QVariant &arg2, + const QVariant &arg3, + const QVariant &arg4, + const QVariant &arg5, + const QVariant &arg6, + const QVariant &arg7, + const QVariant &arg8, + const QVariant &arg9, + const QVariant &arg10 ) +{ + QVariantList args; + if( arg1.isValid() ) args << arg1; + if( arg2.isValid() ) args << arg2; + if( arg3.isValid() ) args << arg3; + if( arg4.isValid() ) args << arg4; + if( arg5.isValid() ) args << arg5; + if( arg6.isValid() ) args << arg6; + if( arg7.isValid() ) args << arg7; + if( arg8.isValid() ) args << arg8; + if( arg9.isValid() ) args << arg9; + if( arg10.isValid() ) args << arg10; + + QXmppRemoteMethod method( jid, interface, args, client() ); + connect(this, SIGNAL(rpcCallResponse(QXmppRpcResponseIq)), + &method, SLOT(gotResult(QXmppRpcResponseIq))); + connect(this, SIGNAL(rpcCallError(QXmppRpcErrorIq)), + &method, SLOT(gotError(QXmppRpcErrorIq))); + + return method.call(); +} + +/// \cond +QStringList QXmppRpcManager::discoveryFeatures() const +{ + // XEP-0009: Jabber-RPC + return QStringList() << ns_rpc; +} + +QList<QXmppDiscoveryIq::Identity> QXmppRpcManager::discoveryIdentities() const +{ + QXmppDiscoveryIq::Identity identity; + identity.setCategory("automation"); + identity.setType("rpc"); + return QList<QXmppDiscoveryIq::Identity>() << identity; +} + +bool QXmppRpcManager::handleStanza(const QDomElement &element) +{ + // XEP-0009: Jabber-RPC + if (QXmppRpcInvokeIq::isRpcInvokeIq(element)) + { + QXmppRpcInvokeIq rpcIqPacket; + rpcIqPacket.parse(element); + invokeInterfaceMethod(rpcIqPacket); + return true; + } + else if(QXmppRpcResponseIq::isRpcResponseIq(element)) + { + QXmppRpcResponseIq rpcResponseIq; + rpcResponseIq.parse(element); + emit rpcCallResponse(rpcResponseIq); + return true; + } + else if(QXmppRpcErrorIq::isRpcErrorIq(element)) + { + QXmppRpcErrorIq rpcErrorIq; + rpcErrorIq.parse(element); + emit rpcCallError(rpcErrorIq); + return true; + } + return false; +} +/// \endcond diff --git a/pool/shard007/C++/0094299_MorphTools.cpp b/pool/shard007/C++/0094299_MorphTools.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1443b780675aae88d600e55e004bf1ac29ee5574 --- /dev/null +++ b/pool/shard007/C++/0094299_MorphTools.cpp @@ -0,0 +1,342 @@ +// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. + +/*============================================================================= + MorphTools.cpp: Morph target creation helper classes. +=============================================================================*/ + +#include "EnginePrivate.h" +#include "RawIndexBuffer.h" +#include "MeshBuild.h" +#include "PhysicsEngine/PhysXSupport.h" +#include "Animation/VertexAnim/MorphTarget.h" + + +/** compare based on base mesh source vertex indices */ +struct FCompareVertexAnimDeltas +{ + FORCEINLINE bool operator()( const FVertexAnimDelta& A, const FVertexAnimDelta& B ) const + { + return ((int32)A.SourceIdx - (int32)B.SourceIdx) < 0 ? true : false; + } +}; + +FVertexAnimDelta* UMorphTarget::GetDeltasAtTime(float Time, int32 LODIndex, FVertexAnimEvalStateBase* State, int32& OutNumDeltas) +{ + if(LODIndex < MorphLODModels.Num()) + { + FMorphTargetLODModel& MorphModel = MorphLODModels[LODIndex]; + OutNumDeltas = MorphModel.Vertices.Num(); + return MorphModel.Vertices.GetData(); + } + + return NULL; +} + +bool UMorphTarget::HasDataForLOD(int32 LODIndex) +{ + // If we have an entry for this LOD, and it has verts + return (MorphLODModels.IsValidIndex(LODIndex) && MorphLODModels[LODIndex].Vertices.Num() > 0); +} + + +void UMorphTarget::PostProcess( USkeletalMesh * NewMesh, const FMorphMeshRawSource& BaseSource, const FMorphMeshRawSource& TargetSource, int32 LODIndex, bool bCompareNormal ) +{ + // @todo anim: update BaseSkelMesh with my information + NewMesh->RegisterMorphTarget(this); + + CreateMorphMeshStreams( BaseSource, TargetSource, LODIndex, bCompareNormal ); + + MarkPackageDirty(); +} + + +void UMorphTarget::CreateMorphMeshStreams( const FMorphMeshRawSource& BaseSource, const FMorphMeshRawSource& TargetSource, int32 LODIndex, bool bCompareNormal ) +{ + check(BaseSource.IsValidTarget(TargetSource)); + + // create the LOD entry if it doesn't already exist + if( LODIndex == MorphLODModels.Num() ) + { + new(MorphLODModels) FMorphTargetLODModel(); + } + + // morph mesh data to modify + FMorphTargetLODModel& MorphModel = MorphLODModels[LODIndex]; + // copy the wedge point indices + // for now just keep every thing + + // set the original number of vertices + MorphModel.NumBaseMeshVerts = BaseSource.Vertices.Num(); + + // empty morph mesh vertices first + MorphModel.Vertices.Empty(); + + // array to mark processed base vertices + TArray<bool> WasProcessed; + WasProcessed.Empty(BaseSource.Vertices.Num()); + WasProcessed.AddZeroed(BaseSource.Vertices.Num()); + + + TMap<uint32,uint32> WedgePointToVertexIndexMap; + // Build a mapping of wedge point indices to vertex indices for fast lookup later. + for( int32 Idx=0; Idx < TargetSource.WedgePointIndices.Num(); Idx++ ) + { + WedgePointToVertexIndexMap.Add( TargetSource.WedgePointIndices[Idx], Idx ); + } + + // iterate over all the base mesh indices + for( int32 Idx=0; Idx < BaseSource.Indices.Num(); Idx++ ) + { + uint32 BaseVertIdx = BaseSource.Indices[Idx]; + + // check for duplicate processing + if( !WasProcessed[BaseVertIdx] ) + { + // mark this base vertex as already processed + WasProcessed[BaseVertIdx] = true; + + // get base mesh vertex using its index buffer + const FMorphMeshVertexRaw& VBase = BaseSource.Vertices[BaseVertIdx]; + + // clothing can add extra verts, and we won't have source point, so we ignore those + if (BaseSource.WedgePointIndices.IsValidIndex(BaseVertIdx)) + { + // get the base mesh's original wedge point index + uint32 BasePointIdx = BaseSource.WedgePointIndices[BaseVertIdx]; + + // find the matching target vertex by searching for one + // that has the same wedge point index + uint32* TargetVertIdx = WedgePointToVertexIndexMap.Find( BasePointIdx ); + + // only add the vertex if the source point was found + if( TargetVertIdx != NULL ) + { + // get target mesh vertex using its index buffer + const FMorphMeshVertexRaw& VTarget = TargetSource.Vertices[*TargetVertIdx]; + + // change in position from base to target + FVector PositionDelta( VTarget.Position - VBase.Position ); + FVector NormalDeltaZ (VTarget.TanZ - VBase.TanZ); + + // check if position actually changed much + if( PositionDelta.Size() > THRESH_POINTS_ARE_NEAR || + // since we can't get imported morphtarget normal from FBX + // we can't compare normal unless it's calculated + // this is special flag to ignore normal diff + ( bCompareNormal && NormalDeltaZ.Size() > 0.1f) ) + { + // create a new entry + FVertexAnimDelta NewVertex; + // position delta + NewVertex.PositionDelta = PositionDelta; + // normal delta + NewVertex.TangentZDelta = NormalDeltaZ; + // index of base mesh vert this entry is to modify + NewVertex.SourceIdx = BaseVertIdx; + + // add it to the list of changed verts + MorphModel.Vertices.Add( NewVertex ); + } + } + } + } + } + + // sort the array of vertices for this morph target based on the base mesh indices + // that each vertex is associated with. This allows us to sequentially traverse the list + // when applying the morph blends to each vertex. + MorphModel.Vertices.Sort(FCompareVertexAnimDeltas()); + + // remove array slack + MorphModel.Vertices.Shrink(); +} + +void UMorphTarget::RemapVertexIndices( USkeletalMesh* InBaseMesh, const TArray< TArray<uint32> > & BasedWedgePointIndices ) +{ + // make sure base wedge point indices have more than what this morph target has + // any morph target import needs base mesh (correct LOD index if it belongs to LOD) + check ( BasedWedgePointIndices.Num() >= MorphLODModels.Num() ); + check ( InBaseMesh ); + + // for each LOD + FSkeletalMeshResource* ImportedResource = InBaseMesh->GetImportedResource(); + for ( int32 LODIndex=0; LODIndex<MorphLODModels.Num(); ++LODIndex ) + { + FStaticLODModel & BaseLODModel = ImportedResource->LODModels[LODIndex]; + FMorphTargetLODModel& MorphLODModel = MorphLODModels[LODIndex]; + const TArray<uint32> & LODWedgePointIndices = BasedWedgePointIndices[LODIndex]; + TArray<uint32> NewWedgePointIndices; + + // If the LOD has been simplified, don't remap vertex indices else the data will be useless if the mesh is unsimplified. + check( LODIndex < InBaseMesh->LODInfo.Num() ); + if ( InBaseMesh->LODInfo[ LODIndex ].bHasBeenSimplified ) + { + continue; + } + + // copy the wedge point indices - it makes easy to find + if( BaseLODModel.RawPointIndices.GetBulkDataSize() ) + { + NewWedgePointIndices.Empty( BaseLODModel.RawPointIndices.GetElementCount() ); + NewWedgePointIndices.AddUninitialized( BaseLODModel.RawPointIndices.GetElementCount() ); + FMemory::Memcpy( NewWedgePointIndices.GetData(), BaseLODModel.RawPointIndices.Lock(LOCK_READ_ONLY), BaseLODModel.RawPointIndices.GetBulkDataSize() ); + BaseLODModel.RawPointIndices.Unlock(); + + // Source Indices used : Save it so that you don't use it twice + TArray<uint32> SourceIndicesUsed; + SourceIndicesUsed.Empty(MorphLODModel.Vertices.Num()); + + // go through all vertices + for ( int32 VertIdx=0; VertIdx<MorphLODModel.Vertices.Num(); ++VertIdx ) + { + // Get Old Base Vertex ID + uint32 OldVertIdx = MorphLODModel.Vertices[VertIdx].SourceIdx; + // find PointIndices from the old list + uint32 BasePointIndex = LODWedgePointIndices[OldVertIdx]; + + // Find the PointIndices from new list + int32 NewVertIdx = NewWedgePointIndices.Find(BasePointIndex); + // See if it's already used + if ( SourceIndicesUsed.Find(NewVertIdx) != INDEX_NONE ) + { + // if used look for next right vertex index + for ( int32 Iter = NewVertIdx + 1; Iter<NewWedgePointIndices.Num(); ++Iter ) + { + // found one + if (NewWedgePointIndices[Iter] == BasePointIndex) + { + // see if used again + if (SourceIndicesUsed.Find(Iter) == INDEX_NONE) + { + // if not, this slot is available + // update new value + MorphLODModel.Vertices[VertIdx].SourceIdx = Iter; + SourceIndicesUsed.Add(Iter); + break; + } + } + } + } + else + { + // update new value + MorphLODModel.Vertices[VertIdx].SourceIdx = NewVertIdx; + SourceIndicesUsed.Add(NewVertIdx); + } + } + + MorphLODModel.Vertices.Sort(FCompareVertexAnimDeltas()); + } + } +} +/** +* Constructor. +* Converts a skeletal mesh to raw vertex data +* needed for creating a morph target mesh +* +* @param SrcMesh - source skeletal mesh to convert +* @param LODIndex - level of detail to use for the geometry +*/ +FMorphMeshRawSource::FMorphMeshRawSource( USkeletalMesh* SrcMesh, int32 LODIndex ) : + SourceMesh(SrcMesh) +{ + check(SrcMesh); + FSkeletalMeshResource* ImportedResource = SrcMesh->GetImportedResource(); + check(ImportedResource->LODModels.IsValidIndex(LODIndex)); + + // get the mesh data for the given lod + FStaticLODModel& LODModel = ImportedResource->LODModels[LODIndex]; + + // vertices are packed in this order iot stay consistent + // with the indexing used by the FStaticLODModel vertex buffer + // + // Chunk0 + // Rigid0 + // Rigid1 + // Soft0 + // Soft1 + // Chunk1 + // Rigid0 + // Rigid1 + // Soft0 + // Soft1 + + // iterate over the chunks for the skeletal mesh + for( int32 ChunkIdx=0; ChunkIdx < LODModel.Chunks.Num(); ChunkIdx++ ) + { + // each chunk has both rigid and smooth vertices + const FSkelMeshChunk& Chunk = LODModel.Chunks[ChunkIdx]; + // rigid vertices should always be added first so that we are + // consistent with the way vertices are packed in the FStaticLODModel vertex buffer + for( int32 VertexIdx=0; VertexIdx < Chunk.RigidVertices.Num(); VertexIdx++ ) + { + const FRigidSkinVertex& SourceVertex = Chunk.RigidVertices[VertexIdx]; + FMorphMeshVertexRaw RawVertex = + { + SourceVertex.Position, + SourceVertex.TangentX, + SourceVertex.TangentY, + SourceVertex.TangentZ + }; + Vertices.Add( RawVertex ); + } + // smooth vertices are added next. The resulting Vertices[] array should + // match the FStaticLODModel vertex buffer when indexing vertices + for( int32 VertexIdx=0; VertexIdx < Chunk.SoftVertices.Num(); VertexIdx++ ) + { + const FSoftSkinVertex& SourceVertex = Chunk.SoftVertices[VertexIdx]; + FMorphMeshVertexRaw RawVertex = + { + SourceVertex.Position, + SourceVertex.TangentX, + SourceVertex.TangentY, + SourceVertex.TangentZ + }; + Vertices.Add( RawVertex ); + } + } + + // Copy the indices manually, since the LODModel's index buffer may have a different alignment. + Indices.Empty(LODModel.MultiSizeIndexContainer.GetIndexBuffer()->Num()); + for(int32 Index = 0;Index < LODModel.MultiSizeIndexContainer.GetIndexBuffer()->Num();Index++) + { + Indices.Add(LODModel.MultiSizeIndexContainer.GetIndexBuffer()->Get(Index)); + } + + // copy the wedge point indices + if( LODModel.RawPointIndices.GetBulkDataSize() ) + { + WedgePointIndices.Empty( LODModel.RawPointIndices.GetElementCount() ); + WedgePointIndices.AddUninitialized( LODModel.RawPointIndices.GetElementCount() ); + FMemory::Memcpy( WedgePointIndices.GetData(), LODModel.RawPointIndices.Lock(LOCK_READ_ONLY), LODModel.RawPointIndices.GetBulkDataSize() ); + LODModel.RawPointIndices.Unlock(); + } +} + +/** +* Constructor. +* Converts a static mesh to raw vertex data +* needed for creating a morph target mesh +* +* @param SrcMesh - source static mesh to convert +* @param LODIndex - level of detail to use for the geometry +*/ +FMorphMeshRawSource::FMorphMeshRawSource( UStaticMesh* SrcMesh, int32 LODIndex ) : + SourceMesh(SrcMesh) +{ + // @todo - not implemented + // not sure if we will support static mesh morphing yet +} + +/** +* Return true if current vertex data can be morphed to the target vertex data +* +*/ +bool FMorphMeshRawSource::IsValidTarget( const FMorphMeshRawSource& Target ) const +{ + //@todo sz - + // heuristic is to check for the same number of original points + //return( WedgePointIndices.Num() == Target.WedgePointIndices.Num() ); + return true; +} + diff --git a/pool/shard007/C++/0094301_PropertyAlignControl.cpp b/pool/shard007/C++/0094301_PropertyAlignControl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..89e52390b758b4384e027ab64d0b9d22a148a3f4 --- /dev/null +++ b/pool/shard007/C++/0094301_PropertyAlignControl.cpp @@ -0,0 +1,111 @@ +/*! + @file + @author Albert Semenov + @date 08/2010 +*/ + +#include "Precompiled.h" +#include "PropertyAlignControl.h" +#include "FactoryManager.h" + +namespace tools +{ + + FACTORY_ITEM_ATTRIBUTE(PropertyAlignControl) + + PropertyAlignControl::PropertyAlignControl() : + mName(nullptr), + mComboBox(nullptr) + { + } + + PropertyAlignControl::~PropertyAlignControl() + { + mComboBox->eventComboChangePosition -= MyGUI::newDelegate(this, &PropertyAlignControl::notifyComboChangePosition); + } + + void PropertyAlignControl::OnInitialise(Control* _parent, MyGUI::Widget* _place, const std::string& _layoutName) + { + PropertyControl::OnInitialise(_parent, _place, "PropertyComboBoxControl.layout"); + + assignWidget(mName, "Name", false); + assignWidget(mComboBox, "ComboBox"); + + mComboBox->addItem("Default"); + mComboBox->addItem("Stretch"); + mComboBox->addItem("Center"); + + mComboBox->addItem("Left Top"); + mComboBox->addItem("Left Bottom"); + mComboBox->addItem("Left VStretch"); + mComboBox->addItem("Left VCenter"); + + mComboBox->addItem("Right Top"); + mComboBox->addItem("Right Bottom"); + mComboBox->addItem("Right VStretch"); + mComboBox->addItem("Right VCenter"); + + mComboBox->addItem("HStretch Top"); + mComboBox->addItem("HStretch Bottom"); + mComboBox->addItem("HStretch VStretch"); + mComboBox->addItem("HStretch VCenter"); + + mComboBox->addItem("HCenter Bottom"); + mComboBox->addItem("HCenter VStretch"); + mComboBox->addItem("HCenter VCenter"); + mComboBox->beginToItemFirst(); + + mComboBox->eventComboChangePosition += MyGUI::newDelegate(this, &PropertyAlignControl::notifyComboChangePosition); + } + + void PropertyAlignControl::updateCaption() + { + PropertyPtr proper = getProperty(); + if (proper != nullptr) + mName->setCaption(proper->getType()->getName()); + } + + void PropertyAlignControl::updateProperty() + { + PropertyPtr proper = getProperty(); + if (proper != nullptr) + { + mComboBox->setEnabled(!proper->getType()->getReadOnly()); + size_t index = getComboIndex(proper->getValue()); + mComboBox->setIndexSelected(index); + } + else + { + mComboBox->setIndexSelected(MyGUI::ITEM_NONE); + mComboBox->setEnabled(false); + } + } + + void PropertyAlignControl::notifyComboChangePosition(MyGUI::ComboBox* _sender, size_t _index) + { + PropertyPtr proper = getProperty(); + if (proper != nullptr) + { + std::string value = _index != MyGUI::ITEM_NONE ? mComboBox->getItemNameAt(_index) : ""; + executeAction(value); + } + } + + size_t PropertyAlignControl::getComboIndex(const MyGUI::UString& _name) + { + size_t result = MyGUI::ITEM_NONE; + + size_t count = mComboBox->getItemCount(); + for (size_t index = 0; index < count; ++index) + { + if (mComboBox->getItemNameAt(index) == _name) + { + result = index; + break; + } + } + + return result; + } + +} diff --git a/pool/shard007/C++/0094304_Symbol.ut.cpp b/pool/shard007/C++/0094304_Symbol.ut.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f26fed900bbdde96e578615d032c10994b706c6 --- /dev/null +++ b/pool/shard007/C++/0094304_Symbol.ut.cpp @@ -0,0 +1,82 @@ +/* + * The Restful Matching-Engine. + * Copyright (C) 2013, 2018 Swirly Cloud Limited. + * + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU General Public License as published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without + * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with this program; if + * not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ +#include "Symbol.hpp" + +#include <boost/test/unit_test.hpp> + +#include <swirly/util/String.hpp> + +using namespace std; +using namespace swirly; + +BOOST_AUTO_TEST_SUITE(SymbolSuite) + +BOOST_AUTO_TEST_CASE(SymbolEmptyCase) +{ + Symbol symbol; + BOOST_TEST(symbol.empty()); + BOOST_TEST(symbol.size() == 0U); + BOOST_TEST(symbol.compare(""sv) == 0); + BOOST_TEST(symbol == Symbol{""sv}); +} + +BOOST_AUTO_TEST_CASE(SymbolNonEmptyCase) +{ + Symbol symbol{"Foo"sv}; + BOOST_TEST(!symbol.empty()); + BOOST_TEST(symbol.size() == 3U); + BOOST_TEST(symbol.compare("Foo"sv) == 0); + BOOST_TEST(symbol == Symbol{"Foo"sv}); +} + +BOOST_AUTO_TEST_CASE(SymbolUpperBoundCase) +{ + Symbol symbol{"0123456789ABCDEFx"sv}; + BOOST_TEST(symbol.size() == MaxSymbol); + BOOST_TEST(symbol == "0123456789ABCDEF"sv); + + symbol = "0123456789abcdefx"sv; + BOOST_TEST(symbol.size() == MaxSymbol); + BOOST_TEST(symbol == "0123456789abcdef"sv); +} + +BOOST_AUTO_TEST_CASE(SymbolIndexCase) +{ + Symbol symbol{"Bar"sv}; + BOOST_TEST(symbol[0] == 'B'); + BOOST_TEST(symbol[1] == 'a'); + BOOST_TEST(symbol[2] == 'r'); + BOOST_TEST(symbol.front() == 'B'); + BOOST_TEST(symbol.back() == 'r'); +} + +BOOST_AUTO_TEST_CASE(SymbolClearCase) +{ + Symbol symbol{"Foo"sv}; + symbol.clear(); + BOOST_TEST(symbol.empty()); +} + +BOOST_AUTO_TEST_CASE(SymbolFormatCase) +{ + Symbol symbol{"Foo"sv}; + stringstream ss; + ss << symbol; + BOOST_TEST(ss.str() == "Foo"); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/pool/shard007/C++/0094305_Assert.cpp b/pool/shard007/C++/0094305_Assert.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b745a15e1fa60f242788907ebd500f3f53e9c7d7 --- /dev/null +++ b/pool/shard007/C++/0094305_Assert.cpp @@ -0,0 +1,41 @@ +#include <sstream> + +#include <Ancona/Util/Assert.hpp> + +using namespace ild; + +AssertException::AssertException(const std::string & message) : std::runtime_error(message) +{ + +} + +bool AssertControls::_throwException = true; +std::ostream * AssertControls::_errorStream = NULL; + +void AssertControls::SetThrowException(bool value) +{ + _throwException = value; +} + +void AssertControls::SetErrorStream(std::ostream * errorStream) +{ + _errorStream = errorStream; +} + +void AssertControls::_ild_assert(bool condition, const std::string & message, const char * fileName, int lineNumber) +{ + if(!condition) + { + std::stringstream errMsg; + errMsg << "Assert Failed In File: " << fileName << " Line: " << lineNumber << + std::endl << " Message: " << message; + if(_throwException) + { + throw AssertException(errMsg.str()); + } + if(_errorStream != NULL) + { + *_errorStream << errMsg.str(); + } + } +} diff --git a/pool/shard007/C++/0094307_intro.cpp b/pool/shard007/C++/0094307_intro.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1fd6d974b01c19f5f20fca082d2ef3b8e6176419 --- /dev/null +++ b/pool/shard007/C++/0094307_intro.cpp @@ -0,0 +1,153 @@ +// This file is part of Chaotic Rage (c) 2010 Josh Heidenreich +// +// kate: tab-width 4; indent-width 4; space-indent off; word-wrap off; + +#include "intro.h" +#include "render_opengl.h" +#include "gl_debug.h" +#include "../game_state.h" +#include "../game_engine.h" +#include "../render/sprite.h" +#include "../mod/mod.h" +#include "../mod/song.h" +#include "../audio/audio.h" +#include "../util/ui_update.h" +#include <glm/glm.hpp> +#include <glm/gtc/matrix_transform.hpp> +#include <glm/gtc/type_ptr.hpp> + + +using namespace std; + + +Intro::Intro(GameState *st) +{ + mod = new Mod(st, "data/intro"); + if (!mod) { + reportFatalError("Intro mod failed to load. Is the working directory correct?"); + } + + this->st = st; + this->render = reinterpret_cast<RenderOpenGL*>(GEng()->render); + + sg = new Song(); + sg->name = "intro"; + + SDL_RWops * rw = mod->loadRWops("intro.ogg"); + + sg->music = Mix_LoadMUS_RW(rw, 0); // does this leak? + + img1 = this->render->loadSprite("joshcorp.png", mod); + img2 = this->render->loadSprite("sdl.png", mod); + img3 = this->render->loadSprite("game.png", mod); + text = this->render->loadSprite("loading.png", mod); + + if (img1 == NULL || img2 == NULL || img3 == NULL || text == NULL) { + reportFatalError("Intro failed to load. Is the working directory correct?"); + } + + this->start = 0; + this->lasttime = 0; +} + + +Intro::~Intro() +{ + delete(mod); + //delete(sg); // yep it leaks - keep the music playing even after into finished + delete(img1); + delete(img2); + delete(img3); + delete(text); +} + + +/** +* Prepare to run the intro +**/ +void Intro::doit() +{ + GLShader *shader; + + if (sg->music != NULL) { + GEng()->audio->playSong(sg); + } + + start = SDL_GetTicks(); + lasttime = 0; + + CHECK_OPENGL_ERROR + + // Find 'basic' shader + map<int, GLShader*>::const_iterator pos = render->shaders.find(SHADER_BASIC); + if (pos == render->shaders.end()) { + assert(false); + } else { + shader = pos->second; + } + + // Set shader and uniforms + glUseProgram(shader->p()); + glm::mat4 projection = glm::ortho<float>( + 0.0f, static_cast<float>(this->render->getWidth()), + static_cast<float>(this->render->getHeight()), 0.0f, + 1.0f, -1.0f + ); + glUniformMatrix4fv(shader->uniform("uMVP"), 1, GL_FALSE, &projection[0][0]); + glUniform1i(shader->uniform("uTex"), 0); + + CHECK_OPENGL_ERROR + + this->updateUI(); +} + + +/** +* This is called at regular intervals by the module loading code +**/ +void Intro::updateUI() +{ + int time = SDL_GetTicks() - start; + SpritePtr img; + + SDL_Event event; + while (SDL_PollEvent(&event)) { + if (event.type == SDL_QUIT) { + exit(0); + } + } + + // Update the image + if (time > 1000) { + img = this->img3; + } else if (time > 500) { + img = this->img2; + } else { + img = this->img1; + } + + CHECK_OPENGL_ERROR + + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + // Render img + int x = (this->render->getWidth() - img->w) / 2; + int y = (this->render->getHeight() - img->h) / 2; + this->render->renderSprite(img, x, y); + + // Flashing message + int frame = static_cast<int>(floor(time / 500.0f)); + if (frame % 2 == 0) { + x = (this->render->getWidth() - text->w) / 2; + y = this->render->getHeight() - text->h - 50; + this->render->renderSprite(text, x, y); + } + + #ifdef SDL1_VIDEO + SDL_GL_SwapBuffers(); + #else + SDL_GL_SwapWindow(this->render->window); + #endif + + CHECK_OPENGL_ERROR +} diff --git a/pool/shard007/C++/0094311_connectcustomkeystoreresponse.cpp b/pool/shard007/C++/0094311_connectcustomkeystoreresponse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..00c6d3875b3d77eadcc4bc59a082af3957db1d3b --- /dev/null +++ b/pool/shard007/C++/0094311_connectcustomkeystoreresponse.cpp @@ -0,0 +1,199 @@ +/* + Copyright 2013-2021 Paul Colby + + This file is part of QtAws. + + QtAws is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + QtAws is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with the QtAws. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "connectcustomkeystoreresponse.h" +#include "connectcustomkeystoreresponse_p.h" + +#include <QDebug> +#include <QNetworkReply> +#include <QXmlStreamReader> + +namespace QtAws { +namespace KMS { + +/*! + * \class QtAws::KMS::ConnectCustomKeyStoreResponse + * \brief The ConnectCustomKeyStoreResponse class provides an interace for KMS ConnectCustomKeyStore responses. + * + * \inmodule QtAwsKMS + * + * <fullname>AWS Key Management Service</fullname> + * + * AWS Key Management Service (AWS KMS) is an encryption and key management web service. This guide describes the AWS KMS + * operations that you can call programmatically. For general information about AWS KMS, see the <a + * href="https://docs.aws.amazon.com/kms/latest/developerguide/"> <i>AWS Key Management Service Developer Guide</i> + * + * </a>> <note> + * + * AWS provides SDKs that consist of libraries and sample code for various programming languages and platforms (Java, Ruby, + * .Net, macOS, Android, etc.). The SDKs provide a convenient way to create programmatic access to AWS KMS and other AWS + * services. For example, the SDKs take care of tasks such as signing requests (see below), managing errors, and retrying + * requests automatically. For more information about the AWS SDKs, including how to download and install them, see <a + * href="http://aws.amazon.com/tools/">Tools for Amazon Web + * + * Services</a>> </note> + * + * We recommend that you use the AWS SDKs to make programmatic API calls to AWS + * + * KMS> + * + * Clients must support TLS (Transport Layer Security) 1.0. We recommend TLS 1.2. Clients must also support cipher suites + * with Perfect Forward Secrecy (PFS) such as Ephemeral Diffie-Hellman (DHE) or Elliptic Curve Ephemeral Diffie-Hellman + * (ECDHE). Most modern systems such as Java 7 and later support these + * + * modes> + * + * <b>Signing Requests</b> + * + * </p + * + * Requests must be signed by using an access key ID and a secret access key. We strongly recommend that you <i>do not</i> + * use your AWS account (root) access key ID and secret key for everyday work with AWS KMS. Instead, use the access key ID + * and secret access key for an IAM user. You can also use the AWS Security Token Service to generate temporary security + * credentials that you can use to sign + * + * requests> + * + * All AWS KMS operations require <a + * href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature Version + * + * 4</a>> + * + * <b>Logging API Requests</b> + * + * </p + * + * AWS KMS supports AWS CloudTrail, a service that logs AWS API calls and related events for your AWS account and delivers + * them to an Amazon S3 bucket that you specify. By using the information collected by CloudTrail, you can determine what + * requests were made to AWS KMS, who made the request, when it was made, and so on. To learn more about CloudTrail, + * including how to turn it on and find your log files, see the <a + * href="https://docs.aws.amazon.com/awscloudtrail/latest/userguide/">AWS CloudTrail User + * + * Guide</a>> + * + * <b>Additional Resources</b> + * + * </p + * + * For more information about credentials and request signing, see the + * + * following> <ul> <li> + * + * <a href="https://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html">AWS Security Credentials</a> - + * This topic provides general information about the types of credentials used for accessing + * + * AWS> </li> <li> + * + * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html">Temporary Security Credentials</a> - + * This section of the <i>IAM User Guide</i> describes how to create and use temporary security + * + * credentials> </li> <li> + * + * <a href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature Version 4 Signing Process</a> + * - This set of topics walks you through the process of signing a request using an access key ID and a secret access + * + * key> </li> </ul> + * + * <b>Commonly Used API Operations</b> + * + * </p + * + * Of the API operations discussed in this guide, the following will prove the most useful for most applications. You will + * likely perform operations other than these, such as creating keys and assigning policies, by using the + * + * console> <ul> <li> + * + * <a>Encrypt</a> + * + * </p </li> <li> + * + * <a>Decrypt</a> + * + * </p </li> <li> + * + * <a>GenerateDataKey</a> + * + * </p </li> <li> + * + * <a>GenerateDataKeyWithoutPlaintext</a> + * + * \sa KmsClient::connectCustomKeyStore + */ + +/*! + * Constructs a ConnectCustomKeyStoreResponse object for \a reply to \a request, with parent \a parent. + */ +ConnectCustomKeyStoreResponse::ConnectCustomKeyStoreResponse( + const ConnectCustomKeyStoreRequest &request, + QNetworkReply * const reply, + QObject * const parent) + : KmsResponse(new ConnectCustomKeyStoreResponsePrivate(this), parent) +{ + setRequest(new ConnectCustomKeyStoreRequest(request)); + setReply(reply); +} + +/*! + * \reimp + */ +const ConnectCustomKeyStoreRequest * ConnectCustomKeyStoreResponse::request() const +{ + Q_D(const ConnectCustomKeyStoreResponse); + return static_cast<const ConnectCustomKeyStoreRequest *>(d->request); +} + +/*! + * \reimp + * Parses a successful KMS ConnectCustomKeyStore \a response. + */ +void ConnectCustomKeyStoreResponse::parseSuccess(QIODevice &response) +{ + //Q_D(ConnectCustomKeyStoreResponse); + QXmlStreamReader xml(&response); + /// @todo +} + +/*! + * \class QtAws::KMS::ConnectCustomKeyStoreResponsePrivate + * \brief The ConnectCustomKeyStoreResponsePrivate class provides private implementation for ConnectCustomKeyStoreResponse. + * \internal + * + * \inmodule QtAwsKMS + */ + +/*! + * Constructs a ConnectCustomKeyStoreResponsePrivate object with public implementation \a q. + */ +ConnectCustomKeyStoreResponsePrivate::ConnectCustomKeyStoreResponsePrivate( + ConnectCustomKeyStoreResponse * const q) : KmsResponsePrivate(q) +{ + +} + +/*! + * Parses a KMS ConnectCustomKeyStore response element from \a xml. + */ +void ConnectCustomKeyStoreResponsePrivate::parseConnectCustomKeyStoreResponse(QXmlStreamReader &xml) +{ + Q_ASSERT(xml.name() == QLatin1String("ConnectCustomKeyStoreResponse")); + Q_UNUSED(xml) ///< @todo +} + +} // namespace KMS +} // namespace QtAws diff --git a/pool/shard007/C++/0094312_main.cpp b/pool/shard007/C++/0094312_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e98625b18f78fc2b5ea5b7ec997376a4cf3f4781 --- /dev/null +++ b/pool/shard007/C++/0094312_main.cpp @@ -0,0 +1,82 @@ +// This code uses standard c++ allocation of arrays + +#define _USE_MATH_DEFINES +#include <iostream> +#include <cmath> +#include <cstring> +#include <fstream> +#include <random> +#include <chrono> +#include <time.h> +#include "planet.h" +#include "solver.h" + +using namespace std; + +void PrintInitialValues(int, double, double, double *, double *, int); +void PrintFinalValues(int, double *, double *); + + +int main() +{ + int IntegrationPoints; // No. of integration points + double FinalTime; // End time of calculation + int Dimension; // No. of spatial dimensions + + cout << "Earth-Sun binary system" << endl; + Dimension = 3; + + IntegrationPoints = 10000; + FinalTime = 50.; + + double TimeStep = FinalTime/((double) IntegrationPoints); + double x[3],v[3]; // positions and velocities + // initial position x = 1AU, y = z = 0, vx = 2pi, vy=0, vz=0 + planet planet1(0.000003,1.,0.0,0.0,0.0,6.3,0.); // Earth: (mass,x,y,z,vx,vy,vz) + planet planet2(1.,0.,0.,0.,0.,0.,0.); // Sun: (mass,x,y,z,vx,vy,vz) + + solver binary_vv(5.0); + binary_vv.add(planet1); + binary_vv.add(planet2); + + PrintInitialValues(Dimension,TimeStep,FinalTime,x,v,IntegrationPoints); + + cout << "Velocity Verlet results for the Sun-Earth system:" << endl; + binary_vv.VelocityVerlet(Dimension,IntegrationPoints,FinalTime,1,0.); + + for(int j = 0; j < Dimension;j++){ + x[j] = binary_vv.all_planets[0].position[j]; + v[j] = binary_vv.all_planets[0].velocity[j]; + } + PrintFinalValues(Dimension,x,v); + return 0; +} + + + +void PrintInitialValues(int Dimension,double TimeStep, double FinalTime,double *x_initial,double *v_initial, int N){ + // A function that prints out the set up of the calculation + + cout << "Time step = " << TimeStep << "; final time = " << FinalTime << "; integration points = " << N << endl; + + cout << "Initial position = "; + for(int j=0;j<Dimension;j++) cout << x_initial[j] << " "; + cout << endl; + + cout << "Initial velocity = "; + for(int j=0;j<Dimension;j++) cout << v_initial[j] << " "; + cout << endl; +} + +void PrintFinalValues(int Dimension,double *x_final,double *v_final){ + // A function that prints out the final results of the calculation + + cout << "Final position = "; + for(int j=0; j<Dimension; j++) cout << x_final[j] << " "; + cout << endl; + + cout << "Final velocity = "; + for(int j=0; j<Dimension; j++) cout << v_final[j] << " "; + cout << endl; +} + diff --git a/pool/shard007/C++/0094314_stack-ex.cpp b/pool/shard007/C++/0094314_stack-ex.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c9eba0ceb48845efa6c208cccbe17559a0335259 --- /dev/null +++ b/pool/shard007/C++/0094314_stack-ex.cpp @@ -0,0 +1,108 @@ +#include <iostream> + +using namespace std; + +#define STACK_SIZE 10 + +class StackError { + int status_; +public: + StackError(int status) { + status_ = status; + } + + int get_status() { + return status_; + } +}; + +class Stack { + int top_; + char elems_[STACK_SIZE]; + +public: + + Stack() { + top_ = 0; + } + + void push(char new_element) { + if (is_full()) { + throw StackError(1); + } + + elems_[top_++] = new_element; + } + + char pop() { + if (is_empty()) { + throw StackError(2); + } + + return elems_[--top_]; + } + + char peek() { + if(is_empty()) { + return -1; + } + return elems_[top_ - 1]; + } + + int top() { + return top_; + } + + bool is_full() { + return top_ == STACK_SIZE; + } + + bool is_empty() { + return top_ == 0; + } + + /*int hasValidTopPointer() { + if (top_ < 0) { + return 1; + } else if (top_ > max_) { + return 2; + } + + return 0; + }*/ +}; + +int main() { + + Stack s; + for (int i = 0; i < 15; i++) { + try { + s.push(i); + } catch (StackError ex) { + cout << "Stack error catched" << endl; + } + } + + try { + for (int i = 0; i < 15; i++) { + s.push(i); + } + cout << "not executed" << endl; + } catch (StackError ex) { + cout << "Stack error catched" << endl; + } + + try { + while (true) { + int i = s.pop(); + + cout << i << endl; + } + } catch (StackError ex) { + cout << "Stack error in pop" << endl; + cout << "Status: " << ex.get_status() << endl; + } + + + return 0; +} diff --git a/pool/shard007/C++/0094316_ElasticMaterial.cpp b/pool/shard007/C++/0094316_ElasticMaterial.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b148ad0e48c9fea03ddbf99be3e871552b222437 --- /dev/null +++ b/pool/shard007/C++/0094316_ElasticMaterial.cpp @@ -0,0 +1,224 @@ +//---------------------------------------------------------------------------- +// XC program; finite element analysis code +// for structural analysis and design. +// +// Copyright (C) Luis Claudio Pérez Tato +// +// This program derives from OpenSees <http://opensees.berkeley.edu> +// developed by the «Pacific earthquake engineering research center». +// +// Except for the restrictions that may arise from the copyright +// of the original program (see copyright_opensees.txt) +// XC is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This software is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// +// You should have received a copy of the GNU General Public License +// along with this program. +// If not, see <http://www.gnu.org/licenses/>. +//---------------------------------------------------------------------------- +/* ****************************************************************** ** +** OpenSees - Open System for Earthquake Engineering Simulation ** +** Pacific Earthquake Engineering Research Center ** +** ** +** ** +** (C) Copyright 1999, The Regents of the University of California ** +** All Rights Reserved. ** +** ** +** Commercial use of this program without express permission of the ** +** University of California, Berkeley, is strictly prohibited. See ** +** file 'COPYRIGHT' in main directory for information on usage and ** +** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** +** ** +** Developed by: ** +** Frank McKenna (fmckenna@ce.berkeley.edu) ** +** Gregory L. Fenves (fenves@ce.berkeley.edu) ** +** Filip C. Filippou (filippou@ce.berkeley.edu) ** +** ** +** ****************************************************************** */ + +// $Revision: 1.5 $ +// $Date: 2003/02/25 23:33:38 $ +// $Source: /usr/local/cvs/OpenSees/SRC/material/uniaxial/ElasticMaterial.cpp,v $ + + +// File: ~/material/ElasticMaterial.C +// +// Written: fmk +// Created: 07/98 +// Revision: A +// +// Description: This file contains the class implementation for +// ElasticMaterial. +// +// What: "@(#) ElasticMaterial.C, revA" + +#include <material/uniaxial/ElasticMaterial.h> +#include "domain/component/Parameter.h" +#include <utility/matrix/Vector.h> + +#include <domain/mesh/element/utils/Information.h> + + +//! @brief Constructor. +XC::ElasticMaterial::ElasticMaterial(int tag, double e, double et) + :ElasticBaseMaterial(tag,MAT_TAG_ElasticMaterial,e), trialStrainRate(0.0), eta(et) + {} + +//! @brief Constructor. +//! +//! To construct an elastic material object with an integer identifier \p +//! tag and the class identifier \p classTag. +XC::ElasticMaterial::ElasticMaterial(int tag, int classtag) + :ElasticBaseMaterial(tag,classtag,0.0), trialStrainRate(0.0), eta(0.0) + {} + +//! @brief Default constructor. +XC::ElasticMaterial::ElasticMaterial(void) + :ElasticBaseMaterial(0,MAT_TAG_ElasticMaterial,0.0), trialStrainRate(0.0), eta(0.0) + {} + +int XC::ElasticMaterial::setTrialStrain(double strain, double strainRate) + { + trialStrain = strain; + trialStrainRate = strainRate; + return 0; + } + +//! @brief Sets the value of the trial strain, \f$\epsilon\f$ to be {\em +//! strain}. Returns 0. +int XC::ElasticMaterial::setTrial(double strain, double &stress, double &tangent, double strainRate) + { + trialStrain = strain; + trialStrainRate = strainRate; + + stress = getStress(); + tangent = E; + + return 0; + } + +//! @brief Returns the product of \f$E * \epsilon\f$, where \f$\epsilon\f$ is +//! the current trial strain. +double XC::ElasticMaterial::getStress(void) const + { return E*def_total() + eta*trialStrainRate; } + + +int XC::ElasticMaterial::commitState(void) + { return 0; } + + +int XC::ElasticMaterial::revertToLastCommit(void) + { return 0; } + + +int XC::ElasticMaterial::revertToStart(void) + { + trialStrain = 0.0; + trialStrainRate = 0.0; + return 0; + } + +//! @brief Virtual constructor. +XC::UniaxialMaterial *XC::ElasticMaterial::getCopy(void) const + { return new ElasticMaterial(*this); } + +//! @brief Send object members through the channel being passed as parameter. +int XC::ElasticMaterial::sendData(CommParameters &cp) + { + int res= ElasticBaseMaterial::sendData(cp); + res+= cp.sendDoubles(trialStrainRate, eta,getDbTagData(),CommMetaData(3)); + return res; + } + +//! @brief Receives object members through the channel being passed as parameter. +int XC::ElasticMaterial::recvData(const CommParameters &cp) + { + int res= ElasticBaseMaterial::recvData(cp); + res+= cp.receiveDoubles(trialStrainRate, eta,getDbTagData(),CommMetaData(3)); + return res; + } + +//! @brief Send the object through the communicator. +//! +//! Sends the object through the communicator. Returns 0 if successful, a +//! warning message is printed, \p tag and \f$E\f$ are set to \f$0.0\f$, and a +//! negative number is returned if the Channel object fails to receive +//! the object. +int XC::ElasticMaterial::sendSelf(CommParameters &cp) + { + setDbTag(cp); + const int dataTag= getDbTag(); + inicComm(4); + int res= sendData(cp); + res+= cp.sendIdData(getDbTagData(),dataTag); + if(res < 0) + std::cerr << getClassName() << "::" << __FUNCTION__ + << "; failed to send data\n"; + return res; + } + +//! @brief Receive the object through the communicator. +//! +//! Receives the object through the communicator. Returns 0 if successful, a +//! warning message is printed, \p tag and \f$E\f$ are set to \f$0.0\f$, and a +//! negative number is returned if the Channel object fails to receive +//! the object. +int XC::ElasticMaterial::recvSelf(const CommParameters &cp) + { + inicComm(4); + const int dataTag= getDbTag(); + int res= cp.receiveIdData(getDbTagData(),dataTag); + if(res<0) + std::cerr << getClassName() << "::" << __FUNCTION__ + << "; failed to receive ids.\n"; + else + { + res= recvData(cp); + if(res < 0) + std::cerr << getClassName() << "::" << __FUNCTION__ + << "; - failed to receive data\n"; + } + return res; + } + +//! Prints to the stream \p s the objects \p tag and \f$E\f$ values. +void XC::ElasticMaterial::Print(std::ostream &s, int flag) + { + s << "Elastic tag: " << this->getTag() << std::endl; + s << " E: " << E << " eta: " << eta << std::endl; + } + +int XC::ElasticMaterial::setParameter(const std::vector<std::string> &argv, Parameter ¶m) + { + if(argv[0] == "E") + return param.addObject(1, this); + else if(argv[0] == "eta") + return param.addObject(2, this); + else + return -1; + } + +int XC::ElasticMaterial::updateParameter(int parameterID, Information &info) + { + switch(parameterID) { + case -1: + return -1; + case 1: + E = info.theDouble; + return 0; + case 2: + eta = info.theDouble; + return 0; + default: + return -1; + } + } + diff --git a/pool/shard007/C++/0094317_assetexporterplugin.cpp b/pool/shard007/C++/0094317_assetexporterplugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1c6e6d65df62dc782033220136d1ba7d92fbda08 --- /dev/null +++ b/pool/shard007/C++/0094317_assetexporterplugin.cpp @@ -0,0 +1,132 @@ +/**************************************************************************** +** +** Copyright (C) 2020 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of Qt Creator. +** +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +****************************************************************************/ + +#include "assetexporterplugin.h" + +#include "assetexportpluginconstants.h" +#include "assetexportdialog.h" +#include "assetexporter.h" +#include "assetexporterview.h" +#include "filepathmodel.h" +#include "componentexporter.h" + +#include "dumpers/itemnodedumper.h" +#include "dumpers/textnodedumper.h" +#include "dumpers/assetnodedumper.h" + +#include "coreplugin/actionmanager/actionmanager.h" +#include "coreplugin/actionmanager/actioncontainer.h" +#include "coreplugin/documentmanager.h" +#include "qmldesigner/qmldesignerplugin.h" +#include "projectexplorer/projectexplorerconstants.h" +#include "projectexplorer/session.h" +#include "projectexplorer/project.h" +#include "projectexplorer/session.h" +#include "projectexplorer/taskhub.h" + +#include "extensionsystem/pluginmanager.h" +#include "extensionsystem/pluginspec.h" + +#include "utils/algorithm.h" + +#include <QCoreApplication> +#include <QAction> + +#include <QLoggingCategory> + +namespace QmlDesigner { + +AssetExporterPlugin::AssetExporterPlugin() : + m_view(new AssetExporterView) +{ + ProjectExplorer::TaskHub::addCategory( Constants::TASK_CATEGORY_ASSET_EXPORT, + tr("Asset Export"), false); + + auto *designerPlugin = QmlDesigner::QmlDesignerPlugin::instance(); + auto &viewManager = designerPlugin->viewManager(); + viewManager.registerViewTakingOwnership(m_view); + + // Add dumper templates for factory instantiation. + Component::addNodeDumper<ItemNodeDumper>(); + Component::addNodeDumper<TextNodeDumper>(); + Component::addNodeDumper<AssetNodeDumper>(); + + // Instantiate actions created by the plugin. + addActions(); + + connect(ProjectExplorer::SessionManager::instance(), + &ProjectExplorer::SessionManager::startupProjectChanged, + this, &AssetExporterPlugin::updateActions); + + updateActions(); +} + +QString AssetExporterPlugin::pluginName() const +{ + return QLatin1String("AssetExporterPlugin"); +} + +void AssetExporterPlugin::onExport() +{ + auto startupProject = ProjectExplorer::SessionManager::startupProject(); + if (!startupProject) + return; + + FilePathModel model(startupProject); + auto exportDir = startupProject->projectFilePath().parentDir(); + if (!exportDir.parentDir().isEmpty()) + exportDir = exportDir.parentDir(); + exportDir = exportDir.pathAppended(startupProject->displayName() + "_export"); + AssetExporter assetExporter(m_view, startupProject); + AssetExportDialog assetExporterDialog(exportDir, assetExporter, model); + assetExporterDialog.exec(); +} + +void AssetExporterPlugin::addActions() +{ + auto exportAction = new QAction(tr("Export Components")); + exportAction->setToolTip(tr("Export components in the current project.")); + connect(exportAction, &QAction::triggered, this, &AssetExporterPlugin::onExport); + Core::Command *cmd = Core::ActionManager::registerAction(exportAction, Constants::EXPORT_QML); + + // Add action to build menu + Core::ActionContainer *buildMenu = + Core::ActionManager::actionContainer(ProjectExplorer::Constants::M_BUILDPROJECT); + buildMenu->addAction(cmd, ProjectExplorer::Constants::G_BUILD_RUN); +} + +void AssetExporterPlugin::updateActions() +{ + auto project = ProjectExplorer::SessionManager::startupProject(); + QAction* const exportAction = Core::ActionManager::command(Constants::EXPORT_QML)->action(); + exportAction->setEnabled(project && !project->needsConfiguration()); +} + +QString AssetExporterPlugin::metaInfo() const +{ + return QLatin1String(":/assetexporterplugin/assetexporterplugin.metainfo"); +} + +} //QmlDesigner diff --git a/pool/shard007/C++/0094322_http_body.cc b/pool/shard007/C++/0094322_http_body.cc new file mode 100644 index 0000000000000000000000000000000000000000..00acead83d8c16ad771bcbffc661f8b399152e98 --- /dev/null +++ b/pool/shard007/C++/0094322_http_body.cc @@ -0,0 +1,115 @@ +// Copyright 2014 The Crashpad 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 "util/net/http_body.h" + +#include <string.h> + +#include <algorithm> +#include <limits> + +#include "base/logging.h" +#include "base/stl_util.h" +#include "util/misc/implicit_cast.h" + +namespace crashpad { + +StringHTTPBodyStream::StringHTTPBodyStream(const std::string& string) + : HTTPBodyStream(), string_(string), bytes_read_() { +} + +StringHTTPBodyStream::~StringHTTPBodyStream() { +} + +ssize_t StringHTTPBodyStream::GetBytesBuffer(uint8_t* buffer, size_t max_len) { + size_t num_bytes_remaining = string_.length() - bytes_read_; + if (num_bytes_remaining == 0) { + return num_bytes_remaining; + } + + size_t num_bytes_returned = + std::min(std::min(num_bytes_remaining, max_len), + implicit_cast<size_t>(std::numeric_limits<ssize_t>::max())); + memcpy(buffer, &string_[bytes_read_], num_bytes_returned); + bytes_read_ += num_bytes_returned; + return num_bytes_returned; +} + +FileHTTPBodyStream::FileHTTPBodyStream(const base::FilePath& path) + : HTTPBodyStream(), path_(path), file_(), file_state_(kUnopenedFile) { +} + +FileHTTPBodyStream::~FileHTTPBodyStream() { +} + +ssize_t FileHTTPBodyStream::GetBytesBuffer(uint8_t* buffer, size_t max_len) { + switch (file_state_) { + case kUnopenedFile: + file_.reset(LoggingOpenFileForRead(path_)); + if (!file_.is_valid()) { + file_state_ = kFileOpenError; + return -1; + } + file_state_ = kReading; + break; + case kFileOpenError: + return -1; + case kClosedAtEOF: + return 0; + case kReading: + break; + } + + ssize_t rv = ReadFile(file_.get(), buffer, max_len); + if (rv == 0) { + file_.reset(); + file_state_ = kClosedAtEOF; + } else if (rv < 0) { + PLOG(ERROR) << "read"; + } + return rv; +} + +CompositeHTTPBodyStream::CompositeHTTPBodyStream( + const CompositeHTTPBodyStream::PartsList& parts) + : HTTPBodyStream(), parts_(parts), current_part_(parts_.begin()) { +} + +CompositeHTTPBodyStream::~CompositeHTTPBodyStream() { + STLDeleteContainerPointers(parts_.begin(), parts_.end()); +} + +ssize_t CompositeHTTPBodyStream::GetBytesBuffer(uint8_t* buffer, + size_t buffer_len) { + ssize_t max_len = std::min( + buffer_len, implicit_cast<size_t>(std::numeric_limits<ssize_t>::max())); + ssize_t bytes_copied = 0; + while (bytes_copied < max_len && current_part_ != parts_.end()) { + ssize_t this_read = (*current_part_)->GetBytesBuffer( + buffer + bytes_copied, max_len - bytes_copied); + + if (this_read == 0) { + // If the current part has returned 0 indicating EOF, advance the current + // part and try again. + ++current_part_; + } else if (this_read < 0) { + return this_read; + } + bytes_copied += this_read; + } + + return bytes_copied; +} + +} // namespace crashpad diff --git a/pool/shard007/C++/0094332_PictureThumbLoader.cpp b/pool/shard007/C++/0094332_PictureThumbLoader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..18983895b815e750c0956530123a2aef21e6e416 --- /dev/null +++ b/pool/shard007/C++/0094332_PictureThumbLoader.cpp @@ -0,0 +1,237 @@ +/* + * Copyright (C) 2005-2012 Team XBMC + * http://www.xbmc.org + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XBMC; see the file COPYING. If not, see + * <http://www.gnu.org/licenses/>. + * + */ + +#include "PictureThumbLoader.h" +#include "Picture.h" +#include "filesystem/File.h" +#include "FileItem.h" +#include "TextureCache.h" +#include "filesystem/Directory.h" +#include "filesystem/MultiPathDirectory.h" +#include "guilib/GUIWindowManager.h" +#include "GUIUserMessages.h" +#include "settings/GUISettings.h" +#include "utils/URIUtils.h" +#include "settings/Settings.h" +#include "settings/AdvancedSettings.h" + +using namespace XFILE; +using namespace std; + +CPictureThumbLoader::CPictureThumbLoader() : CThumbLoader(1), CJobQueue(true) +{ + m_regenerateThumbs = false; +} + +CPictureThumbLoader::~CPictureThumbLoader() +{ + StopThread(); +} + +bool CPictureThumbLoader::LoadItem(CFileItem* pItem) +{ + if (pItem->m_bIsShareOrDrive) return true; + if (pItem->IsParentFolder()) return true; + + if (pItem->HasThumbnail() && m_regenerateThumbs) + { + CTextureCache::Get().ClearCachedImage(pItem->GetThumbnailImage()); + CTextureDatabase db; + if (db.Open()) + db.ClearTextureForPath(pItem->GetPath(), "thumb"); + pItem->SetThumbnailImage(""); + } + + CStdString thumb; + if (pItem->IsPicture() && !pItem->IsZIP() && !pItem->IsRAR() && !pItem->IsCBZ() && !pItem->IsCBR() && !pItem->IsPlayList()) + { // load the thumb from the image file + thumb = pItem->HasThumbnail() ? pItem->GetThumbnailImage() : CTextureCache::GetWrappedThumbURL(pItem->GetPath()); + } + else if (pItem->IsVideo() && !pItem->IsZIP() && !pItem->IsRAR() && !pItem->IsCBZ() && !pItem->IsCBR() && !pItem->IsPlayList()) + { // video + if (!CVideoThumbLoader::FillThumb(*pItem)) + { + CStdString thumbURL = CVideoThumbLoader::GetEmbeddedThumbURL(*pItem); + if (CTextureCache::Get().HasCachedImage(thumbURL)) + { + thumb = thumbURL; + } + else if (g_guiSettings.GetBool("myvideos.extractthumb") && g_guiSettings.GetBool("myvideos.extractflags")) + { + CFileItem item(*pItem); + CThumbExtractor* extract = new CThumbExtractor(item, pItem->GetPath(), true, thumbURL); + AddJob(extract); + thumb.clear(); + } + } + } + else if (!pItem->HasThumbnail()) + { // folder, zip, cbz, rar, cbr, playlist may have a previously cached image + thumb = GetCachedImage(*pItem, "thumb"); + } + if (!thumb.IsEmpty()) + { + CTextureCache::Get().BackgroundCacheImage(thumb); + pItem->SetThumbnailImage(thumb); + } + pItem->FillInDefaultIcon(); + return true; +} + +void CPictureThumbLoader::OnJobComplete(unsigned int jobID, bool success, CJob* job) +{ + if (success) + { + CThumbExtractor* loader = (CThumbExtractor*)job; + loader->m_item.SetPath(loader->m_listpath); + CFileItemPtr pItem(new CFileItem(loader->m_item)); + CGUIMessage msg(GUI_MSG_NOTIFY_ALL, 0, 0, GUI_MSG_UPDATE_ITEM, 0, pItem); + g_windowManager.SendThreadMessage(msg); + } + CJobQueue::OnJobComplete(jobID, success, job); +} + + +void CPictureThumbLoader::OnLoaderFinish() +{ + m_regenerateThumbs = false; +} + +void CPictureThumbLoader::ProcessFoldersAndArchives(CFileItem *pItem) +{ + if (pItem->HasThumbnail()) + return; + + CTextureDatabase db; + db.Open(); + if (pItem->IsCBR() || pItem->IsCBZ()) + { + CStdString strTBN(URIUtils::ReplaceExtension(pItem->GetPath(),".tbn")); + if (CFile::Exists(strTBN)) + { + db.SetTextureForPath(pItem->GetPath(), "thumb", strTBN); + CTextureCache::Get().BackgroundCacheImage(strTBN); + pItem->SetThumbnailImage(strTBN); + return; + } + } + if ((pItem->m_bIsFolder || pItem->IsCBR() || pItem->IsCBZ()) && !pItem->m_bIsShareOrDrive && !pItem->IsParentFolder()) + { + // first check for a folder.jpg + CStdString thumb = "folder.jpg"; + CStdString strPath = pItem->GetPath(); + if (pItem->IsCBR()) + { + URIUtils::CreateArchivePath(strPath,"rar",pItem->GetPath(),""); + thumb = "cover.jpg"; + } + if (pItem->IsCBZ()) + { + URIUtils::CreateArchivePath(strPath,"zip",pItem->GetPath(),""); + thumb = "cover.jpg"; + } + if (pItem->IsMultiPath()) + strPath = CMultiPathDirectory::GetFirstPath(pItem->GetPath()); + thumb = URIUtils::AddFileToFolder(strPath, thumb); + if (CFile::Exists(thumb)) + { + db.SetTextureForPath(pItem->GetPath(), "thumb", thumb); + CTextureCache::Get().BackgroundCacheImage(thumb); + pItem->SetThumbnailImage(thumb); + return; + } + if (!pItem->IsPlugin()) + { + // we load the directory, grab 4 random thumb files (if available) and then generate + // the thumb. + + CFileItemList items; + + CDirectory::GetDirectory(strPath, items, g_settings.m_pictureExtensions, DIR_FLAG_NO_FILE_DIRS); + + // create the folder thumb by choosing 4 random thumbs within the folder and putting + // them into one thumb. + // count the number of images + for (int i=0; i < items.Size();) + { + if (!items[i]->IsPicture() || items[i]->IsZIP() || items[i]->IsRAR() || items[i]->IsPlayList()) + { + items.Remove(i); + } + else + i++; + } + + if (items.IsEmpty()) + { + if (pItem->IsCBZ() || pItem->IsCBR()) + { + CDirectory::GetDirectory(strPath, items, g_settings.m_pictureExtensions, DIR_FLAG_NO_FILE_DIRS); + for (int i=0;i<items.Size();++i) + { + CFileItemPtr item = items[i]; + if (item->m_bIsFolder) + { + ProcessFoldersAndArchives(item.get()); + pItem->SetThumbnailImage(items[i]->GetThumbnailImage()); + pItem->SetIconImage(items[i]->GetIconImage()); + return; + } + } + } + return; // no images in this folder + } + + // randomize them + items.Randomize(); + + if (items.Size() < 4 || pItem->IsCBR() || pItem->IsCBZ()) + { // less than 4 items, so just grab the first thumb + items.Sort(SORT_METHOD_LABEL, SortOrderAscending); + CStdString thumb = CTextureCache::GetWrappedThumbURL(items[0]->GetPath()); + db.SetTextureForPath(pItem->GetPath(), "thumb", thumb); + CTextureCache::Get().BackgroundCacheImage(thumb); + pItem->SetThumbnailImage(thumb); + } + else + { + // ok, now we've got the files to get the thumbs from, lets create it... + // we basically load the 4 images and combine them + vector<string> files; + for (int thumb = 0; thumb < 4; thumb++) + files.push_back(items[thumb]->GetPath()); + CStdString thumb = CTextureCache::GetWrappedImageURL(pItem->GetPath(), "picturefolder"); + CStdString relativeCacheFile = CTextureCache::GetCacheFile(thumb) + ".png"; + if (CPicture::CreateTiledThumb(files, CTextureCache::GetCachedPath(relativeCacheFile))) + { + CTextureDetails details; + details.file = relativeCacheFile; + details.width = g_advancedSettings.GetThumbSize(); + details.height = g_advancedSettings.GetThumbSize(); + CTextureCache::Get().AddCachedTexture(thumb, details); + db.SetTextureForPath(pItem->GetPath(), "thumb", thumb); + pItem->SetThumbnailImage(CTextureCache::GetCachedPath(relativeCacheFile)); + } + } + } + // refill in the icon to get it to update + pItem->FillInDefaultIcon(); + } +} diff --git a/pool/shard007/C++/0094333_random.cpp b/pool/shard007/C++/0094333_random.cpp new file mode 100644 index 0000000000000000000000000000000000000000..765a0f355090846d2c683013450ba4ff842a1882 --- /dev/null +++ b/pool/shard007/C++/0094333_random.cpp @@ -0,0 +1,94 @@ +/* + This file is part of Warzone 2100. + Copyright (C) 1999-2004 Eidos Interactive + Copyright (C) 2005-2013 Warzone 2100 Project + + Warzone 2100 is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + Warzone 2100 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Warzone 2100; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#include "random.h" +#include "lib/netplay/netplay.h" + +static MersenneTwister gamePseudorandomNumberGenerator; + +MersenneTwister::MersenneTwister(uint32_t seed) + : offset(624) +{ + // Set state to something pseudorandom. Exact constants aren't important here. + state[0] = seed; + for (unsigned i = 1; i != 624; ++i) + { + state[i] = 0x6C078965*(state[i - 1] ^ state[i - 1]>>30) + i; + } +} + +uint32_t MersenneTwister::u32() +{ + if (offset == 624) + { + generate(); + } + + uint32_t ret = state[offset++]; + + // Give better than 624 dimensional equidistribution for lower bits. + // Don't change the constants unless you know what you're doing. + // Can skip this step if it noticably affects performance (which it probably doesn't), since we aren't doing Monte-Carlo simulations. + ret ^= ret>>11; + ret ^= ret<<7 & 0x9D2C5680; + ret ^= ret<<15 & 0xEFC60000; + ret ^= ret>>18; + + return ret; +} + +void MersenneTwister::generate() +{ + offset = 0; + + // Don't change these constants, unless you have verified that the period is still 2**19937 - 1. + // Discards the lower 31 bits of state[0], since the state is 19937 = 624*32 - 31 bits. + // Loop tripled, to avoid using %624 everywhere. + for (unsigned i = 0; i != 227; ++i) + { + int v = (state[i]&0x80000000) | (state[i + 1 ]&0x7FFFFFFF); + state[i] = state[i + 397 ] ^ v>>1 ^ ((v&0x00000001)*0x9908B0DF); + } + for (unsigned i = 227; i != 623; ++i) + { + int v = (state[i]&0x80000000) | (state[i + 1 ]&0x7FFFFFFF); + state[i] = state[i + 397 - 624] ^ v>>1 ^ ((v&0x00000001)*0x9908B0DF); + } + for (unsigned i = 623; i != 624; ++i) // Very short loop. + { + int v = (state[i]&0x80000000) | (state[i + 1 - 624]&0x7FFFFFFF); + state[i] = state[i + 397 - 624] ^ v>>1 ^ ((v&0x00000001)*0x9908B0DF); + } +} + +void gameSRand(uint32_t seed) +{ + gamePseudorandomNumberGenerator = MersenneTwister(seed); +} + +uint32_t gameRandU32() +{ + return gamePseudorandomNumberGenerator.u32(); +} + +int32_t gameRand(uint32_t limit) +{ + syncDebug("Used a random number."); + return gamePseudorandomNumberGenerator.u32()%limit; +} diff --git a/pool/shard007/C++/0094336_RealPathMgr.cpp b/pool/shard007/C++/0094336_RealPathMgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..40cc687292075646c9a6ac14aeb8309f2191fe5e --- /dev/null +++ b/pool/shard007/C++/0094336_RealPathMgr.cpp @@ -0,0 +1,231 @@ +// -*-Mode: C++;-*- + +// * BeginRiceCopyright ***************************************************** +// +// $HeadURL$ +// $Id$ +// +// -------------------------------------------------------------------------- +// Part of HPCToolkit (hpctoolkit.org) +// +// Information about sources of support for research and development of +// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'. +// -------------------------------------------------------------------------- +// +// Copyright ((c)) 2002-2015, Rice University +// 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 Rice University (RICE) 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 RICE 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 RICE 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. +// +// ******************************************************* EndRiceCopyright * + +//*************************************************************************** +// +// File: +// $HeadURL$ +// +// Purpose: +// [The purpose of this file] +// +// Description: +// [The set of functions, macros, etc. defined in the file] +// +//*************************************************************************** + +//************************* System Include Files **************************** + +#include <string> +using std::string; + + +//*************************** User Include Files **************************** + +#include <include/gcc-attr.h> + +#include "Logic.hpp" +#include "RealPathMgr.hpp" +#include "PathReplacementMgr.hpp" +#include "PathFindMgr.hpp" +#include "StrUtil.hpp" + +#include "diagnostics.h" +#include "realpath.h" + +//*************************** Forward Declarations ************************** + +//*************************************************************************** + +//*************************************************************************** +// RealPathMgr +//*************************************************************************** + +static RealPathMgr s_singleton; + +RealPathMgr::RealPathMgr() +{ +} + + +RealPathMgr::~RealPathMgr() +{ +} + + +RealPathMgr& RealPathMgr::singleton() +{ + return s_singleton; +} + + +bool +RealPathMgr::realpath(string& pathNm) const +{ + if (pathNm.empty()) { + return false; + } + + // INVARIANT: 'pathNm' is not empty + + // INVARIANT: all entries in the map are non-empty + MyMap::iterator it = m_cache.find(pathNm); + + // ------------------------------------------------------- + // 1. Check cache for 'pathNm' + // ------------------------------------------------------- + if (it != m_cache.end()) { + // use cached value + const string& pathNm_real = it->second; + if (pathNm_real[0] == '/') { // optimization: only copy if fully resolved + pathNm = pathNm_real; + } + } + else { + // ------------------------------------------------------- + // 2. Consult cache with path-replaced 'pathNm' + // ------------------------------------------------------- + string pathNm_orig = pathNm; + + pathNm = PathReplacementMgr::singleton().replace(pathNm); + it = m_cache.find(pathNm); + + if (it != m_cache.end()) { + // use cached value + const string& pathNm_real = it->second; + if (pathNm_real[0] == '/') { // optimization: only copy if fully resolved + pathNm = pathNm_real; + } + + // since 'pathNm_orig' was not in map, ensure it is + m_cache.insert(make_pair(pathNm_orig, pathNm_real)); + } + else { + // ------------------------------------------------------- + // 3. Resolve 'pathNm' using PathFindMgr or realpath + // ------------------------------------------------------- + string pathNm_real = pathNm; + + if (m_searchPaths.empty()) { + pathNm_real = RealPath(pathNm.c_str()); + } + else { + const char* pathNm_pf = + PathFindMgr::singleton().pathfind(m_searchPaths.c_str(), + pathNm.c_str(), "r"); + if (pathNm_pf) { + pathNm_real = pathNm_pf; + } + } + + pathNm = pathNm_real; + m_cache.insert(make_pair(pathNm_orig, pathNm_real)); + } + } + return (pathNm[0] == '/'); // fully resolved +} + + +void +RealPathMgr::searchPaths(const string& pathsStr) +{ + std::vector<std::string> searchPathVec; + StrUtil::tokenize_str(pathsStr, ":", searchPathVec); + + // INVARIANT: m_searchPaths is non-empty + m_searchPaths += "."; // current working directory + + for (uint i = 0; i < searchPathVec.size(); ++i) { + string path = searchPathVec[i]; + + if (PathFindMgr::isRecursivePath(path.c_str())) { + path = path.substr(0, path.length() - PathFindMgr::RecursivePathSfxLn); + path = RealPath(path.c_str()); + path += "/*"; + } + else if (path != ".") { + path = RealPath(path.c_str()); + } + + m_searchPaths += ":" + path; + } +} + + +//*************************************************************************** + +string +RealPathMgr::toString(uint flags) const +{ + std::ostringstream os; + dump(os, flags); + return os.str(); +} + + +std::ostream& +RealPathMgr::dump(std::ostream& os, uint GCC_ATTR_UNUSED flags, + const char* pfx) const +{ + os << pfx << "[ RealPathMgr:" << std::endl; + for (MyMap::const_iterator it = m_cache.begin(); it != m_cache.end(); ++it) { + const string& x = it->first; + const string& y = it->second; + os << pfx << " " << x << " => " << y << std::endl; + } + os << pfx << "]" << std::endl; + + os.flush(); + return os; +} + + +void +RealPathMgr::ddump(uint flags) const +{ + dump(std::cerr, flags); +} + diff --git a/pool/shard007/C++/0094338_video_capture_impl_manager_unittest.cc b/pool/shard007/C++/0094338_video_capture_impl_manager_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..2193d9310db2c206777823fa5baa93f2dc15e2c7 --- /dev/null +++ b/pool/shard007/C++/0094338_video_capture_impl_manager_unittest.cc @@ -0,0 +1,177 @@ +// 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 "base/bind.h" +#include "base/callback.h" +#include "base/memory/ref_counted.h" +#include "base/message_loop/message_loop.h" +#include "base/run_loop.h" +#include "content/child/child_process.h" +#include "content/renderer/media/video_capture_impl.h" +#include "content/renderer/media/video_capture_impl_manager.h" +#include "content/renderer/media/video_capture_message_filter.h" +#include "media/base/bind_to_current_loop.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using ::testing::_; +using ::testing::DoAll; +using ::testing::SaveArg; +using media::BindToCurrentLoop; + +namespace content { + +ACTION_P(RunClosure, closure) { + closure.Run(); +} + +class MockVideoCaptureImpl : public VideoCaptureImpl { + public: + MockVideoCaptureImpl(media::VideoCaptureSessionId session_id, + VideoCaptureMessageFilter* filter, + base::Closure destruct_callback) + : VideoCaptureImpl(session_id, filter), + destruct_callback_(destruct_callback) { + } + + ~MockVideoCaptureImpl() override { destruct_callback_.Run(); } + + private: + base::Closure destruct_callback_; + + DISALLOW_COPY_AND_ASSIGN(MockVideoCaptureImpl); +}; + +class MockVideoCaptureImplManager : public VideoCaptureImplManager { + public: + explicit MockVideoCaptureImplManager( + base::Closure destruct_video_capture_callback) + : destruct_video_capture_callback_( + destruct_video_capture_callback) {} + ~MockVideoCaptureImplManager() override {} + + protected: + VideoCaptureImpl* CreateVideoCaptureImplForTesting( + media::VideoCaptureSessionId id, + VideoCaptureMessageFilter* filter) const override { + return new MockVideoCaptureImpl(id, + filter, + destruct_video_capture_callback_); + } + + private: + base::Closure destruct_video_capture_callback_; + + DISALLOW_COPY_AND_ASSIGN(MockVideoCaptureImplManager); +}; + +class VideoCaptureImplManagerTest : public ::testing::Test { + public: + VideoCaptureImplManagerTest() + : manager_(new MockVideoCaptureImplManager( + BindToCurrentLoop(cleanup_run_loop_.QuitClosure()))) { + params_.requested_format = media::VideoCaptureFormat( + gfx::Size(176, 144), 30, media::PIXEL_FORMAT_I420); + child_process_.reset(new ChildProcess()); + } + + void FakeChannelSetup() { + scoped_refptr<base::SingleThreadTaskRunner> task_runner = + child_process_->io_task_runner(); + if (!task_runner->BelongsToCurrentThread()) { + task_runner->PostTask( + FROM_HERE, base::Bind(&VideoCaptureImplManagerTest::FakeChannelSetup, + base::Unretained(this))); + return; + } + manager_->video_capture_message_filter()->OnFilterAdded(NULL); + } + + protected: + MOCK_METHOD2(OnFrameReady, + void(const scoped_refptr<media::VideoFrame>&, + base::TimeTicks estimated_capture_time)); + MOCK_METHOD0(OnStarted, void()); + MOCK_METHOD0(OnStopped, void()); + + void OnStateUpdate(VideoCaptureState state) { + switch (state) { + case VIDEO_CAPTURE_STATE_STARTED: + OnStarted(); + break; + case VIDEO_CAPTURE_STATE_STOPPED: + OnStopped(); + break; + default: + NOTREACHED(); + } + } + + base::Closure StartCapture(const media::VideoCaptureSessionId id, + const media::VideoCaptureParams& params) { + return manager_->StartCapture( + id, params, base::Bind(&VideoCaptureImplManagerTest::OnStateUpdate, + base::Unretained(this)), + base::Bind(&VideoCaptureImplManagerTest::OnFrameReady, + base::Unretained(this))); + } + + base::MessageLoop message_loop_; + scoped_ptr<ChildProcess> child_process_; + media::VideoCaptureParams params_; + base::RunLoop cleanup_run_loop_; + scoped_ptr<MockVideoCaptureImplManager> manager_; + + private: + DISALLOW_COPY_AND_ASSIGN(VideoCaptureImplManagerTest); +}; + +TEST_F(VideoCaptureImplManagerTest, MultipleImpls) { + base::Closure release_cb1 = manager_->UseDevice(0); + base::Closure release_cb2 = manager_->UseDevice(1); + base::Closure stop_cb1, stop_cb2; + { + base::RunLoop run_loop; + base::Closure quit_closure = BindToCurrentLoop(run_loop.QuitClosure()); + EXPECT_CALL(*this, OnStarted()).WillOnce(RunClosure(quit_closure)); + EXPECT_CALL(*this, OnStarted()).RetiresOnSaturation(); + stop_cb1 = StartCapture(0, params_); + stop_cb2 = StartCapture(1, params_); + FakeChannelSetup(); + run_loop.Run(); + } + + { + base::RunLoop run_loop; + base::Closure quit_closure = BindToCurrentLoop(run_loop.QuitClosure()); + EXPECT_CALL(*this, OnStopped()).WillOnce(RunClosure(quit_closure)); + EXPECT_CALL(*this, OnStopped()).RetiresOnSaturation(); + stop_cb1.Run(); + stop_cb2.Run(); + run_loop.Run(); + } + + release_cb1.Run(); + release_cb2.Run(); + cleanup_run_loop_.Run(); +} + +TEST_F(VideoCaptureImplManagerTest, RefusesMultipleClients) { + // TODO(ajose): EXPECT_DEATH is unsafe in a threaded context - what to use + // instead? + base::Closure release_cb1 = manager_->UseDevice(0); +// Use DCHECK_IS_ON rather than EXPECT_DEBUG_DEATH or similar to avoid +// issues on release builds that include DCHECKs. +#if DCHECK_IS_ON() + EXPECT_DEATH(manager_->UseDevice(0), ""); +#endif +} + +TEST_F(VideoCaptureImplManagerTest, NoLeak) { + manager_->UseDevice(0).Reset(); + manager_.reset(); + cleanup_run_loop_.Run(); +} + +} // namespace content diff --git a/pool/shard007/C++/0094339_sensor.cpp b/pool/shard007/C++/0094339_sensor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dea0974b1b6452e9b521bb5b3badeebaf9b9e967 --- /dev/null +++ b/pool/shard007/C++/0094339_sensor.cpp @@ -0,0 +1,33 @@ +#include "sensor.h" + +namespace sensor_simulator +{ + +Sensor::Sensor(std::shared_ptr<Ekf> ekf): _ekf{ekf} +{ +} + +Sensor::~Sensor() +{ +} + +void Sensor::update(uint64_t time) +{ + if(should_send(time)) + { + send(time); + _time_last_data_sent = time; + } +} + +bool Sensor::should_send(uint64_t time) const +{ + return _is_running && is_time_to_send(time); +} + +bool Sensor::is_time_to_send(uint64_t time) const +{ + return (time >= _time_last_data_sent) && ((time - _time_last_data_sent) >= _update_period); +} + +} // namespace sensor_simulator diff --git a/pool/shard007/C++/0094344_accessible_pane_view.cc b/pool/shard007/C++/0094344_accessible_pane_view.cc new file mode 100644 index 0000000000000000000000000000000000000000..84fccdc14a77c8d1994caec3e6bd9ba08ed98f7e --- /dev/null +++ b/pool/shard007/C++/0094344_accessible_pane_view.cc @@ -0,0 +1,262 @@ +// Copyright (c) 2012 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 "ui/views/accessible_pane_view.h" + +#include "base/message_loop/message_loop.h" +#include "ui/accessibility/ax_view_state.h" +#include "ui/views/focus/focus_search.h" +#include "ui/views/focus/view_storage.h" +#include "ui/views/widget/widget.h" + +namespace views { + +// Create tiny subclass of FocusSearch that overrides GetParent and Contains, +// delegating these to methods in AccessiblePaneView. This is needed so that +// subclasses of AccessiblePaneView can customize the focus search logic and +// include views that aren't part of the AccessiblePaneView's view +// hierarchy in the focus order. +class AccessiblePaneViewFocusSearch : public FocusSearch { + public: + explicit AccessiblePaneViewFocusSearch(AccessiblePaneView* pane_view) + : FocusSearch(pane_view, true, true), + accessible_pane_view_(pane_view) {} + + protected: + virtual View* GetParent(View* v) OVERRIDE { + return accessible_pane_view_->ContainsForFocusSearch(root(), v) ? + accessible_pane_view_->GetParentForFocusSearch(v) : NULL; + } + + // Returns true if |v| is contained within the hierarchy rooted at |root|. + // Subclasses can override this if they need custom focus search behavior. + virtual bool Contains(View* root, const View* v) OVERRIDE { + return accessible_pane_view_->ContainsForFocusSearch(root, v); + } + + private: + AccessiblePaneView* accessible_pane_view_; + DISALLOW_COPY_AND_ASSIGN(AccessiblePaneViewFocusSearch); +}; + +AccessiblePaneView::AccessiblePaneView() + : pane_has_focus_(false), + allow_deactivate_on_esc_(false), + focus_manager_(NULL), + home_key_(ui::VKEY_HOME, ui::EF_NONE), + end_key_(ui::VKEY_END, ui::EF_NONE), + escape_key_(ui::VKEY_ESCAPE, ui::EF_NONE), + left_key_(ui::VKEY_LEFT, ui::EF_NONE), + right_key_(ui::VKEY_RIGHT, ui::EF_NONE), + method_factory_(this) { + focus_search_.reset(new AccessiblePaneViewFocusSearch(this)); + last_focused_view_storage_id_ = ViewStorage::GetInstance()->CreateStorageID(); +} + +AccessiblePaneView::~AccessiblePaneView() { + if (pane_has_focus_) { + focus_manager_->RemoveFocusChangeListener(this); + } +} + +bool AccessiblePaneView::SetPaneFocus(views::View* initial_focus) { + if (!visible()) + return false; + + if (!focus_manager_) + focus_manager_ = GetFocusManager(); + + View* focused_view = focus_manager_->GetFocusedView(); + if (focused_view && !ContainsForFocusSearch(this, focused_view)) { + ViewStorage* view_storage = ViewStorage::GetInstance(); + view_storage->RemoveView(last_focused_view_storage_id_); + view_storage->StoreView(last_focused_view_storage_id_, focused_view); + } + + // Use the provided initial focus if it's visible and enabled, otherwise + // use the first focusable child. + if (!initial_focus || + !ContainsForFocusSearch(this, initial_focus) || + !initial_focus->visible() || + !initial_focus->enabled()) { + initial_focus = GetFirstFocusableChild(); + } + + // Return false if there are no focusable children. + if (!initial_focus) + return false; + + focus_manager_->SetFocusedView(initial_focus); + + // If we already have pane focus, we're done. + if (pane_has_focus_) + return true; + + // Otherwise, set accelerators and start listening for focus change events. + pane_has_focus_ = true; + ui::AcceleratorManager::HandlerPriority normal = + ui::AcceleratorManager::kNormalPriority; + focus_manager_->RegisterAccelerator(home_key_, normal, this); + focus_manager_->RegisterAccelerator(end_key_, normal, this); + focus_manager_->RegisterAccelerator(escape_key_, normal, this); + focus_manager_->RegisterAccelerator(left_key_, normal, this); + focus_manager_->RegisterAccelerator(right_key_, normal, this); + focus_manager_->AddFocusChangeListener(this); + + return true; +} + +bool AccessiblePaneView::SetPaneFocusAndFocusDefault() { + return SetPaneFocus(GetDefaultFocusableChild()); +} + +views::View* AccessiblePaneView::GetDefaultFocusableChild() { + return NULL; +} + +View* AccessiblePaneView::GetParentForFocusSearch(View* v) { + return v->parent(); +} + +bool AccessiblePaneView::ContainsForFocusSearch(View* root, const View* v) { + return root->Contains(v); +} + +void AccessiblePaneView::RemovePaneFocus() { + focus_manager_->RemoveFocusChangeListener(this); + pane_has_focus_ = false; + + focus_manager_->UnregisterAccelerator(home_key_, this); + focus_manager_->UnregisterAccelerator(end_key_, this); + focus_manager_->UnregisterAccelerator(escape_key_, this); + focus_manager_->UnregisterAccelerator(left_key_, this); + focus_manager_->UnregisterAccelerator(right_key_, this); +} + +views::View* AccessiblePaneView::GetFirstFocusableChild() { + FocusTraversable* dummy_focus_traversable; + views::View* dummy_focus_traversable_view; + return focus_search_->FindNextFocusableView( + NULL, false, views::FocusSearch::DOWN, false, + &dummy_focus_traversable, &dummy_focus_traversable_view); +} + +views::View* AccessiblePaneView::GetLastFocusableChild() { + FocusTraversable* dummy_focus_traversable; + views::View* dummy_focus_traversable_view; + return focus_search_->FindNextFocusableView( + this, true, views::FocusSearch::DOWN, false, + &dummy_focus_traversable, &dummy_focus_traversable_view); +} + +//////////////////////////////////////////////////////////////////////////////// +// View overrides: + +views::FocusTraversable* AccessiblePaneView::GetPaneFocusTraversable() { + if (pane_has_focus_) + return this; + else + return NULL; +} + +bool AccessiblePaneView::AcceleratorPressed( + const ui::Accelerator& accelerator) { + + views::View* focused_view = focus_manager_->GetFocusedView(); + if (!ContainsForFocusSearch(this, focused_view)) + return false; + + switch (accelerator.key_code()) { + case ui::VKEY_ESCAPE: { + RemovePaneFocus(); + View* last_focused_view = ViewStorage::GetInstance()->RetrieveView( + last_focused_view_storage_id_); + if (last_focused_view) { + focus_manager_->SetFocusedViewWithReason( + last_focused_view, FocusManager::kReasonFocusRestore); + } else if (allow_deactivate_on_esc_) { + focused_view->GetWidget()->Deactivate(); + } + return true; + } + case ui::VKEY_LEFT: + focus_manager_->AdvanceFocus(true); + return true; + case ui::VKEY_RIGHT: + focus_manager_->AdvanceFocus(false); + return true; + case ui::VKEY_HOME: + focus_manager_->SetFocusedViewWithReason( + GetFirstFocusableChild(), views::FocusManager::kReasonFocusTraversal); + return true; + case ui::VKEY_END: + focus_manager_->SetFocusedViewWithReason( + GetLastFocusableChild(), views::FocusManager::kReasonFocusTraversal); + return true; + default: + return false; + } +} + +void AccessiblePaneView::SetVisible(bool flag) { + if (visible() && !flag && pane_has_focus_) { + RemovePaneFocus(); + focus_manager_->RestoreFocusedView(); + } + View::SetVisible(flag); +} + +void AccessiblePaneView::GetAccessibleState(ui::AXViewState* state) { + state->role = ui::AX_ROLE_PANE; +} + +void AccessiblePaneView::RequestFocus() { + SetPaneFocusAndFocusDefault(); +} + +//////////////////////////////////////////////////////////////////////////////// +// FocusChangeListener overrides: + +void AccessiblePaneView::OnWillChangeFocus(views::View* focused_before, + views::View* focused_now) { + // Act when focus has changed. +} + +void AccessiblePaneView::OnDidChangeFocus(views::View* focused_before, + views::View* focused_now) { + if (!focused_now) + return; + + views::FocusManager::FocusChangeReason reason = + focus_manager_->focus_change_reason(); + + if (!ContainsForFocusSearch(this, focused_now) || + reason == views::FocusManager::kReasonDirectFocusChange) { + // We should remove pane focus (i.e. make most of the controls + // not focusable again) because the focus has left the pane, + // or because the focus changed within the pane due to the user + // directly focusing to a specific view (e.g., clicking on it). + RemovePaneFocus(); + } +} + +//////////////////////////////////////////////////////////////////////////////// +// FocusTraversable overrides: + +views::FocusSearch* AccessiblePaneView::GetFocusSearch() { + DCHECK(pane_has_focus_); + return focus_search_.get(); +} + +views::FocusTraversable* AccessiblePaneView::GetFocusTraversableParent() { + DCHECK(pane_has_focus_); + return NULL; +} + +views::View* AccessiblePaneView::GetFocusTraversableParentView() { + DCHECK(pane_has_focus_); + return NULL; +} + +} // namespace views diff --git a/pool/shard007/C++/0094345_o3_component.cpp b/pool/shard007/C++/0094345_o3_component.cpp new file mode 100644 index 0000000000000000000000000000000000000000..baa458a55681e08626828b8e42aa12a55526dffc --- /dev/null +++ b/pool/shard007/C++/0094345_o3_component.cpp @@ -0,0 +1,191 @@ +/* Hector -- A Simple Climate Model + Copyright (C) 2014-2015 Battelle Memorial Institute + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License, version 2 as + published by the Free Software Foundation. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ +/* + * ozone_component.cpp + * hector + * + * Created by Adria Schwarber on 10/24/2013. + * + */ + +#include <math.h> + +#include "components/o3_component.hpp" +#include "core/core.hpp" +#include "h_util.hpp" +#include "visitors/avisitor.hpp" + +namespace Hector { + +using namespace std; + +//------------------------------------------------------------------------------ +/*! \brief Constructor + */ +OzoneComponent::OzoneComponent() { +} + +//------------------------------------------------------------------------------ +/*! \brief Destructor + */ +OzoneComponent::~OzoneComponent() { +} + +//------------------------------------------------------------------------------ +// documentation is inherited +string OzoneComponent::getComponentName() const { + const string name = OZONE_COMPONENT_NAME; + + return name; +} + +//------------------------------------------------------------------------------ +// documentation is inherited +void OzoneComponent::init( Core* coreptr ) { + logger.open( getComponentName(), false, Logger::DEBUG ); + H_LOG( logger, Logger::DEBUG ) << "hello " << getComponentName() << std::endl; + core = coreptr; + + CO_emissions.allowInterp( true ); + NMVOC_emissions.allowInterp( true ); + NOX_emissions.allowInterp( true );//Inputs like CO and NMVOC and NOX, + Ma.allowInterp( true ); + O3.allowInterp(true); + + + + // Inform core what data we can provide + core->registerCapability( D_ATMOSPHERIC_O3, getComponentName() ); + // Register the emissions we accept (note that OH component also + // accepts these. That's ok + core->registerInput(D_EMISSIONS_CO, getComponentName()); + core->registerInput(D_EMISSIONS_NMVOC, getComponentName()); + core->registerInput(D_EMISSIONS_NOX, getComponentName()); +} + +//------------------------------------------------------------------------------ +// documentation is inherited +unitval OzoneComponent::sendMessage( const std::string& message, + const std::string& datum, + const message_data info ) throw ( h_exception ) +{ + unitval returnval; + + if( message==M_GETDATA ) { //! Caller is requesting data + return getData( datum, info.date ); + + } else if( message==M_SETDATA ) { //! Caller is requesting to set data + setData(datum, info); + //TODO: change core so that parsing is routed through sendMessage + //TODO: make setData private + + } else { //! We don't handle any other messages + H_THROW( "Caller sent unknown message: "+message ); + } + + return returnval; +} + +//------------------------------------------------------------------------------ +// documentation is inherited +void OzoneComponent::setData( const string& varName, + const message_data& data ) throw ( h_exception ) +{ + H_LOG( logger, Logger::DEBUG ) << "Setting " << varName << "[" << data.date << "]=" << data.value_str << std::endl; + + try { + if ( varName == D_PREINDUSTRIAL_O3 ) { + H_ASSERT( data.date == Core::undefinedIndex() , "date not allowed" ); + PO3 = data.getUnitval(U_DU_O3); + } else if( varName == D_EMISSIONS_NOX ) { + H_ASSERT( data.date != Core::undefinedIndex(), "date required" ); + NOX_emissions.set( data.date, data.getUnitval(U_TG_N)); + } else if( varName == D_EMISSIONS_CO ) { + H_ASSERT( data.date != Core::undefinedIndex(), "date required" ); + CO_emissions.set( data.date, data.getUnitval(U_TG_CO)); + } else if( varName == D_EMISSIONS_NMVOC ) { + H_ASSERT( data.date != Core::undefinedIndex(), "date required" ); + NMVOC_emissions.set( data.date, data.getUnitval(U_TG_NMVOC)); + } else { + H_THROW( "Unknown variable name while parsing " + getComponentName() + ": " + + varName ); + } + } catch( h_exception& parseException ) { + H_RETHROW( parseException, "Could not parse var: "+varName ); + } +} + +//------------------------------------------------------------------------------ +// documentation is inherited +void OzoneComponent::prepareToRun() throw ( h_exception ) { + + H_LOG( logger, Logger::DEBUG ) << "prepareToRun " << std::endl; + oldDate = core->getStartDate(); + O3.set(oldDate, PO3); // set the first year's value +} + +//------------------------------------------------------------------------------ +// documentation is inherited +void OzoneComponent::run( const double runToDate ) throw ( h_exception ) { + + // Calculate O3 based on NOX, CO, NMVOC, CH4. + // Modified from Tanaka et al 2007 + + unitval current_nox = NOX_emissions.get( runToDate ); + unitval current_co = CO_emissions.get( runToDate ); + unitval current_nmvoc = NMVOC_emissions.get( runToDate ); + unitval current_ch4 = core->sendMessage( M_GETDATA, D_ATMOSPHERIC_CH4, runToDate ); + + O3.set( runToDate, unitval( ( 5*log( current_ch4 ) ) + ( 0.125*current_nox ) + ( 0.0011*current_co ) + + ( 0.0033*current_nmvoc ), U_DU_O3 ) ); + + oldDate=runToDate; + + H_LOG( logger, Logger::DEBUG ) << "Year " << runToDate << " O3 concentration = " << O3.get( runToDate ) << std::endl; +} + +//------------------------------------------------------------------------------ +// documentation is inherited +unitval OzoneComponent::getData( const std::string& varName, + const double date ) throw ( h_exception ) { + + unitval returnval; + + if( varName == D_ATMOSPHERIC_O3 ) { + H_ASSERT( date != Core::undefinedIndex(), "Date required for O3" ); //== is a comparision + returnval = O3.get( date ); + } else { + H_THROW( "Caller is requesting unknown variable: " + varName ); + } + + return returnval; +} + +//------------------------------------------------------------------------------ +// documentation is inherited +void OzoneComponent::shutDown() { + H_LOG( logger, Logger::DEBUG ) << "goodbye " << getComponentName() << std::endl; + logger.close(); +} + +//------------------------------------------------------------------------------ +// documentation is inherited +void OzoneComponent::accept( AVisitor* visitor ) { + visitor->visit( this ); +} + +} diff --git a/pool/shard007/C++/0094346_gameAgent.cpp b/pool/shard007/C++/0094346_gameAgent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b7ff604755fea6e0f7a674c8b29e60339e21b972 --- /dev/null +++ b/pool/shard007/C++/0094346_gameAgent.cpp @@ -0,0 +1,156 @@ +/** + *====================================================================== + * Student#1: Angelo Pulcini Student ID: 3946703 + * Student#2: Jonathan Evans Student ID: 5201713 + * Course: COMP 472 Section: Lec F + * Instructor: Sabine Bergler + * Assignment #2 + * + * Description: + * This is the implementation file for the gameAgent class. + * + *====================================================================== + */ +#include "gameAgent.h" +#include "stateSpace.h" //Needed to use the stateSpace and to use the element data type +#include "gameLogic.h" //Needed to use the gameLogic +#include <iostream> //for debugging purposes +#include <bitset> + +using namespace std; + +gameAgent::gameAgent(int newColour, int newSkill, Algorithm newAlgorithm, Heuristic newHeuristic) +{ + colour = colour; + skill = ((skill - 1) * 2) + 1; // this assumes that skill is put in as 1,2,3, etc and has not been adjusted to work with depth + algorithm = algorithm; + heuristic = heuristic; + + storage = new stateSpace(); + gameRules = new gameLogic(); +} + + +bitset<64> gameAgent::generateMoves(element currentBoard) +{ + //currentSet.push_back(currentBoard); // add the currentBoard to the agents vector. Actually, for the generateChildren function to work properly the vector should be empty. + + // generate all nodes for move search + do + { +// gameRules->generateChildren(skill, currentBoard.black, currentBoard.white, currentSet); // generate the children of the board + //calculateCost(); //Score the boards before adding them to the stateSpace +// storage->addChildren(currentSet); // add those children to the stateSpace + currentSet.clear(); // clear the set for the next iteration + + storage->nextNode(); // advance to next element + }while(storage->getDepth() < skill); + + vector<element> targetNodes; + storage->getNodes(skill, targetNodes); + + //return determineMove(targetNodes); // bitset that is all 0's except a single 1 indicating the move + + bitset<64> temp; + return temp; +} + +/* +void gameAgent::calculateScore() +{ + int blackPieces; + int whitePieces; + int edgeBonus = 0; + + switch(heuristic) + { + case VERYEASY: // checks board for player colour minus opponent colour + blackPieces = _stateSpace.getBlackBoard().count(); + whitePieces = _stateSpace.getWhiteBoard().count(); + // _stateSpace.getDepth() % 2 is 1 when looking at player moves and 0 when looking at opponent moves + if ((_colour == 0 && _stateSpace.getDepth() % 2 == 1) || (_colour == 1 && _stateSpace.getDepth() % 2 == 0)) + _stateSpace.setScore((float)(blackPieces - whitePieces)); + else + _stateSpace.setScore((float)(whitePieces - blackPieces)); + break; + + case EASY: // player pieces divided by opponent pieces + blackPieces = _stateSpace.getBlackBoard().count(); + whitePieces = _stateSpace.getWhiteBoard().count(); + if ((_colour == 0 && _stateSpace.getDepth() % 2 == 1) || (_colour == 1 && _stateSpace.getDepth() % 2 == 0)) + _stateSpace.setScore((float)(blackPieces / whitePieces)); + else + _stateSpace.setScore((float)(whitePieces / blackPieces)); + break; + + case MEDIUM: // player pieces divided by opponent pieces plus points for having edge pieces + blackPieces = _stateSpace.getBlackBoard().count(); + whitePieces = _stateSpace.getWhiteBoard().count(); + if ((_colour == 0 && _stateSpace.getDepth() % 2 == 1) || (_colour == 1 && _stateSpace.getDepth() % 2 == 0)) + { + for (int i = 0; i < 64; ++i) + if ((i <= 7 || i >= 56 || i % 8 == 0 || (i + 1) % 8 == 0) && (_stateSpace.getBlackBoard()[i] == 1)) + edgeBonus++; + _stateSpace.setScore((float)(blackPieces / whitePieces + edgeBonus)); + } + else + { + for (int i = 0; i < 64; ++i) + if ((i <= 7 || i >= 56 || i % 8 == 0 || (i + 1) % 8 == 0) && (_stateSpace.getWhiteBoard()[i] == 1)) + edgeBonus++; + _stateSpace.setScore((float)(whitePieces / blackPieces + edgeBonus)); + } + break; + + default: // same as VERYEASY + blackPieces = _stateSpace.getBlackBoard().count(); + whitePieces = _stateSpace.getWhiteBoard().count(); + // _stateSpace.getDepth() % 2 is 1 when looking at player moves and 0 when looking at opponent moves + if ((_colour == 0 && _stateSpace.getDepth() % 2 == 1) || (_colour == 1 && _stateSpace.getDepth() % 2 == 0)) + _stateSpace.setScore((float)(blackPieces - whitePieces)); + else + _stateSpace.setScore((float)(whitePieces - blackPieces)); + break; + } +} + + +bitset<64> determineMove(vector<element> nodes) +{ +// element* bestElement; + bitset<64> bestMove; + /*float bestScore = 0.0f; + + switch(_algorithm) + { + case MINMAX: + // I'm looking for the vector containing all the elements I've generated here + for(vector<element *>::iterator it = _stateList.start(); it != _stateList.end(); ++it) + { + // find elements with depth == skill - 1 -> these are the parents of the last row + // take the children of that element and select the one with the lowest score + // if that score is higher than bestScore + // set bestElement to that element and bestScore to the score + // once this has been done with all elements, bestElement will be the parent with the highest low score amongst its children + // trace this back until the element being examined has depth == 1 + // set bestElement to this value + } + break; + case GREEDY: + for(vector<element *>::iterator it = _stateList.start(); it != _stateList.end(); ++it) + { + // find elements with depth == skill -> these are the last row + // find the element amongst these with the highest score + // trace this back until the element being examined has depth == 1 + // set bestElement to this value + } + break; + } + + // take bestElement and create the move bitset from its data + // get this bitset with (parent.getBlackBoard || parent.getWhiteBoard) ^ (move.getBlackBoard || move.getWhiteBoard) + // set bestMove to this bitSet<64> + + return bestMove; +} +*/ \ No newline at end of file diff --git a/pool/shard007/C++/0094347_My_Calendar_II.cpp b/pool/shard007/C++/0094347_My_Calendar_II.cpp new file mode 100644 index 0000000000000000000000000000000000000000..efbbf0d2f4fde8b0f6ac7df77c9dc66b36dc52b6 --- /dev/null +++ b/pool/shard007/C++/0094347_My_Calendar_II.cpp @@ -0,0 +1,66 @@ +class MyCalendarTwo { +public: + vector<pair<int, int> > data; + vector<vector<int> > inter; + + MyCalendarTwo() { + data.clear(); + inter.clear(); + } + + bool isinter(int s1, int e1, int s2, int e2) { + if (s1 <= s2 && s2 < e1) return true; + if (s1 < e2 && e2 <= e1) return true; + + + if (s2 <= s1 && s1 < e2) return true; + if (s2 < e1 && e1 <= e2) return true; + + return false; + } + + bool check(int idx, int start, int end) { + int s1 = data[idx].first; + int e1 = data[idx].second; + int s = -1, e = -1; + for (int i = 0; i < inter[idx].size(); i++) { + int s2 = data[inter[idx][i]].first; + int e2 = data[inter[idx][i]].second; + + s = max(s1, s2); + e = min(e1, e2); + + if (isinter(s, e, start, end)) return true; + } + + return false; + } + + bool book(int start, int end) { + vector<int> tmp; + for (int i = 0; i < data.size(); i++) { + if (isinter(data[i].first, data[i].second, + start, end)) { + if (check(i, start, end)) { + return false; + } + tmp.push_back(i); + } + } + + data.push_back(make_pair(start, end)); + int idx = data.size()-1; + inter.push_back(vector<int>()); + for (int i = 0; i < tmp.size(); i++) { + inter[tmp[i]].push_back(idx); + inter[idx].push_back(tmp[i]); + } + return true; + } +}; + +/** + * Your MyCalendarTwo object will be instantiated and called as such: + * MyCalendarTwo obj = new MyCalendarTwo(); + * bool param_1 = obj.book(start,end); + */ diff --git a/pool/shard007/C++/0094349_points.cpp b/pool/shard007/C++/0094349_points.cpp new file mode 100644 index 0000000000000000000000000000000000000000..88bea400f14fc841f9435ff8f0ba95cc91b75d14 --- /dev/null +++ b/pool/shard007/C++/0094349_points.cpp @@ -0,0 +1,115 @@ +/********************************************************************** + * File: points.c (Formerly coords.c) + * Description: Member functions for coordinate classes. + * Author: Ray Smith + * Created: Fri Mar 15 08:58:17 GMT 1991 + * + * (C) Copyright 1991, Hewlett-Packard Ltd. + ** 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 "mfcpch.h" //precompiled headers +#include <stdlib.h> +#include "ndminx.h" +#include "serialis.h" +#include "points.h" + +ELISTIZE_S (ICOORDELT) //turn to list +bool FCOORD::normalise() { //Convert to unit vec + float len = length (); + + if (len < 0.0000000001) { + return false; + } + xcoord /= len; + ycoord /= len; + return true; +} + +// Set from the given x,y, shrinking the vector to fit if needed. +void ICOORD::set_with_shrink(int x, int y) { + // Fit the vector into an ICOORD, which is 16 bit. + int factor = 1; + int max_extent = MAX(abs(x), abs(y)); + if (max_extent > MAX_INT16) + factor = max_extent / MAX_INT16 + 1; + xcoord = x / factor; + ycoord = y / factor; +} + +// The fortran/basic sgn function returns -1, 0, 1 if x < 0, x == 0, x > 0 +// respectively. +static int sign(int x) { + if (x < 0) + return -1; + else + return x > 0 ? 1 : 0; +} + +// Setup for iterating over the pixels in a vector by the well-known +// Bresenham rendering algorithm. +// Starting with major/2 in the accumulator, on each step add major_step, +// and then add minor to the accumulator. When the accumulator >= major +// subtract major and step a minor step. + +void ICOORD::setup_render(ICOORD* major_step, ICOORD* minor_step, + int* major, int* minor) const { + int abs_x = abs(xcoord); + int abs_y = abs(ycoord); + if (abs_x >= abs_y) { + // X-direction is major. + major_step->xcoord = sign(xcoord); + major_step->ycoord = 0; + minor_step->xcoord = 0; + minor_step->ycoord = sign(ycoord); + *major = abs_x; + *minor = abs_y; + } else { + // Y-direction is major. + major_step->xcoord = 0; + major_step->ycoord = sign(ycoord); + minor_step->xcoord = sign(xcoord); + minor_step->ycoord = 0; + *major = abs_y; + *minor = abs_x; + } +} + + +void ICOORD::serialise_asc( //convert to ascii + FILE *f //file to write + ) { + serialise_INT32(f, xcoord); + serialise_INT32(f, ycoord); +} + + +void ICOORD::de_serialise_asc( //convert from ascii + FILE *f //file to write + ) { + xcoord = (inT16) de_serialise_INT32 (f); + ycoord = (inT16) de_serialise_INT32 (f); +} + + +void ICOORDELT::serialise_asc( //convert to ascii + FILE *f //file to write + ) { + ((ICOORD *) this)->serialise_asc (f); +} + + +void ICOORDELT::de_serialise_asc( //convert from ascii + FILE *f //file to write + ) { + ((ICOORD *) this)->de_serialise_asc (f); +} diff --git a/pool/shard007/C++/0094353_host_video_dispatcher.cc b/pool/shard007/C++/0094353_host_video_dispatcher.cc new file mode 100644 index 0000000000000000000000000000000000000000..bc23cfda952374990f04fe4e7a84b0f353db75d4 --- /dev/null +++ b/pool/shard007/C++/0094353_host_video_dispatcher.cc @@ -0,0 +1,41 @@ +// 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 "remoting/protocol/host_video_dispatcher.h" + +#include <utility> + +#include "base/bind.h" +#include "net/socket/stream_socket.h" +#include "remoting/base/compound_buffer.h" +#include "remoting/base/constants.h" +#include "remoting/proto/video.pb.h" +#include "remoting/protocol/message_pipe.h" +#include "remoting/protocol/message_serialization.h" +#include "remoting/protocol/video_feedback_stub.h" + +namespace remoting { +namespace protocol { + +HostVideoDispatcher::HostVideoDispatcher() + : ChannelDispatcherBase(kVideoChannelName) {} +HostVideoDispatcher::~HostVideoDispatcher() = default; + +void HostVideoDispatcher::ProcessVideoPacket( + std::unique_ptr<VideoPacket> packet, + base::OnceClosure done) { + message_pipe()->Send(packet.get(), std::move(done)); +} + +void HostVideoDispatcher::OnIncomingMessage( + std::unique_ptr<CompoundBuffer> message) { + std::unique_ptr<VideoAck> ack = ParseMessage<VideoAck>(message.get()); + if (!ack) + return; + if (video_feedback_stub_) + video_feedback_stub_->ProcessVideoAck(std::move(ack)); +} + +} // namespace protocol +} // namespace remoting diff --git a/pool/shard007/C++/0094355_buffercl.cpp b/pool/shard007/C++/0094355_buffercl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c6a141748bc8f2036df9e2b70a6945ebc41553c6 --- /dev/null +++ b/pool/shard007/C++/0094355_buffercl.cpp @@ -0,0 +1,125 @@ +/********************************************************************************* + * + * Inviwo - Interactive Visualization Workshop + * + * Copyright (c) 2013-2019 Inviwo Foundation + * 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. + * + * 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 <modules/opencl/buffer/buffercl.h> +#include <inviwo/core/util/stdextensions.h> // make_unique is c++14 but works on some compilers + +namespace inviwo { + +BufferCL::BufferCL(size_t size, const DataFormatBase* format, BufferUsage usage, const void* data, + cl_mem_flags readWriteFlag) + : BufferCLBase() + , BufferRepresentation(format, usage) + , readWriteFlag_(readWriteFlag) + , size_(size) { + // Generate a new buffer + if (data != nullptr) { + // CL_MEM_COPY_HOST_PTR can be used with CL_MEM_ALLOC_HOST_PTR to initialize the contents of + // the cl_mem object allocated using host-accessible (e.g. PCIe) memory. + clBuffer_ = util::make_unique<cl::Buffer>( + OpenCL::getPtr()->getContext(), + readWriteFlag_ | CL_MEM_COPY_HOST_PTR | CL_MEM_ALLOC_HOST_PTR, + std::max(std::size_t{1}, getSize()) * getSizeOfElement(), const_cast<void*>(data)); + } else { + clBuffer_ = + util::make_unique<cl::Buffer>(OpenCL::getPtr()->getContext(), readWriteFlag_, + std::max(std::size_t{1}, getSize()) * getSizeOfElement()); + } +} + +BufferCL::BufferCL(const BufferCL& rhs) + : BufferCLBase(rhs) + , BufferRepresentation(rhs) + , readWriteFlag_(rhs.readWriteFlag_) + , size_(rhs.size_) { + clBuffer_ = + util::make_unique<cl::Buffer>(OpenCL::getPtr()->getContext(), readWriteFlag_, + std::max(std::size_t{1}, getSize()) * getSizeOfElement()); + OpenCL::getPtr()->getQueue().enqueueCopyBuffer(rhs.get(), *clBuffer_, 0, 0, + getSize() * getSizeOfElement()); +} + +BufferCL* BufferCL::clone() const { return new BufferCL(*this); } + +BufferCL::~BufferCL() {} + +void BufferCL::setSize(size_t size) { + size_ = size; + clBuffer_ = + util::make_unique<cl::Buffer>(OpenCL::getPtr()->getContext(), readWriteFlag_, + std::max(std::size_t{1}, getSize()) * getSizeOfElement()); +} +size_t BufferCL::getSize() const { return size_; } + +std::type_index BufferCL::getTypeIndex() const { return std::type_index(typeid(BufferCL)); } + +void BufferCL::upload(const void* data, size_t size) { + // Resize buffer if necessary + if (size > size_ * getSizeOfElement()) { + clBuffer_ = util::make_unique<cl::Buffer>( + OpenCL::getPtr()->getContext(), + readWriteFlag_ | CL_MEM_COPY_HOST_PTR | CL_MEM_ALLOC_HOST_PTR, + std::max(std::size_t{1}, getSize()) * getSizeOfElement(), const_cast<void*>(data)); + } else { + OpenCL::getPtr()->getQueue().enqueueWriteBuffer(*clBuffer_, true, 0, size, + const_cast<void*>(data)); + } +} + +void BufferCL::download(void* data) const { + try { + OpenCL::getPtr()->getQueue().enqueueReadBuffer(*clBuffer_, true, 0, + getSize() * getSizeOfElement(), data); + } catch (cl::Error& err) { + LogError(getCLErrorString(err)); + } +} + +} // namespace inviwo + +namespace cl { + +template <> +cl_int Kernel::setArg(cl_uint index, const inviwo::BufferCL& value) { + return setArg(index, value.get()); +} + +template <> +cl_int Kernel::setArg(cl_uint index, const inviwo::BufferBase& value) { + return setArg(index, value.getRepresentation<inviwo::BufferCL>()->get()); +} + +#define DataFormatIdMacro(i) \ + template <> \ + cl_int Kernel::setArg(cl_uint index, const inviwo::Buffer<inviwo::Data##i::type>& value) { \ + return setArg(index, value.getRepresentation<inviwo::BufferCL>()->get()); \ + } +#include <inviwo/core/util/formatsdefinefunc.h> + +} // namespace cl \ No newline at end of file diff --git a/pool/shard007/C++/0094358_utilitydialog.cpp b/pool/shard007/C++/0094358_utilitydialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b2fa0d31d8eeb2fcecd93973b366614740f4e0fa --- /dev/null +++ b/pool/shard007/C++/0094358_utilitydialog.cpp @@ -0,0 +1,173 @@ +// Copyright (c) 2011-2014 The Beardcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "utilitydialog.h" + +#include "ui_helpmessagedialog.h" + +#include "bitcoingui.h" +#include "clientmodel.h" +#include "guiutil.h" + +#include "clientversion.h" +#include "init.h" +#include "util.h" + +#include <stdio.h> + +#include <QCloseEvent> +#include <QLabel> +#include <QRegExp> +#include <QTextTable> +#include <QTextCursor> +#include <QVBoxLayout> + +/** "Help message" or "About" dialog box */ +HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) : + QDialog(parent), + ui(new Ui::HelpMessageDialog) +{ + ui->setupUi(this); + + QString version = tr("Beardcoin Core") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()); + /* On x86 add a bit specifier to the version so that users can distinguish between + * 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambigious. + */ +#if defined(__x86_64__) + version += " " + tr("(%1-bit)").arg(64); +#elif defined(__i386__ ) + version += " " + tr("(%1-bit)").arg(32); +#endif + + if (about) + { + setWindowTitle(tr("About Beardcoin Core")); + + /// HTML-format the license message from the core + QString licenseInfo = QString::fromStdString(LicenseInfo()); + QString licenseInfoHTML = licenseInfo; + // Make URLs clickable + QRegExp uri("<(.*)>", Qt::CaseSensitive, QRegExp::RegExp2); + uri.setMinimal(true); // use non-greedy matching + licenseInfoHTML.replace(uri, "<a href=\"\\1\">\\1</a>"); + // Replace newlines with HTML breaks + licenseInfoHTML.replace("\n\n", "<br><br>"); + + ui->aboutMessage->setTextFormat(Qt::RichText); + ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); + text = version + "\n" + licenseInfo; + ui->aboutMessage->setText(version + "<br><br>" + licenseInfoHTML); + ui->aboutMessage->setWordWrap(true); + ui->helpMessage->setVisible(false); + } else { + setWindowTitle(tr("Command-line options")); + QString header = tr("Usage:") + "\n" + + " beardcoin-qt [" + tr("command-line options") + "] " + "\n"; + QTextCursor cursor(ui->helpMessage->document()); + cursor.insertText(version); + cursor.insertBlock(); + cursor.insertText(header); + cursor.insertBlock(); + + QString coreOptions = QString::fromStdString(HelpMessage(HMM_BITCOIN_QT)); + text = version + "\n" + header + "\n" + coreOptions; + + QTextTableFormat tf; + tf.setBorderStyle(QTextFrameFormat::BorderStyle_None); + tf.setCellPadding(2); + QVector<QTextLength> widths; + widths << QTextLength(QTextLength::PercentageLength, 35); + widths << QTextLength(QTextLength::PercentageLength, 65); + tf.setColumnWidthConstraints(widths); + + QTextCharFormat bold; + bold.setFontWeight(QFont::Bold); + + Q_FOREACH (const QString &line, coreOptions.split("\n")) { + if (line.startsWith(" -")) + { + cursor.currentTable()->appendRows(1); + cursor.movePosition(QTextCursor::PreviousCell); + cursor.movePosition(QTextCursor::NextRow); + cursor.insertText(line.trimmed()); + cursor.movePosition(QTextCursor::NextCell); + } else if (line.startsWith(" ")) { + cursor.insertText(line.trimmed()+' '); + } else if (line.size() > 0) { + //Title of a group + if (cursor.currentTable()) + cursor.currentTable()->appendRows(1); + cursor.movePosition(QTextCursor::Down); + cursor.insertText(line.trimmed(), bold); + cursor.insertTable(1, 2, tf); + } + } + + ui->helpMessage->moveCursor(QTextCursor::Start); + ui->scrollArea->setVisible(false); + ui->aboutLogo->setVisible(false); + } +} + +HelpMessageDialog::~HelpMessageDialog() +{ + delete ui; +} + +void HelpMessageDialog::printToConsole() +{ + // On other operating systems, the expected action is to print the message to the console. + fprintf(stdout, "%s\n", qPrintable(text)); +} + +void HelpMessageDialog::showOrPrint() +{ +#if defined(WIN32) + // On Windows, show a message box, as there is no stderr/stdout in windowed applications + exec(); +#else + // On other operating systems, print help text to console + printToConsole(); +#endif +} + +void HelpMessageDialog::on_okButton_accepted() +{ + close(); +} + + +/** "Shutdown" window */ +ShutdownWindow::ShutdownWindow(QWidget *parent, Qt::WindowFlags f): + QWidget(parent, f) +{ + QVBoxLayout *layout = new QVBoxLayout(); + layout->addWidget(new QLabel( + tr("Beardcoin Core is shutting down...") + "<br /><br />" + + tr("Do not shut down the computer until this window disappears."))); + setLayout(layout); +} + +void ShutdownWindow::showShutdownWindow(BitcoinGUI *window) +{ + if (!window) + return; + + // Show a simple window indicating shutdown status + QWidget *shutdownWindow = new ShutdownWindow(); + // We don't hold a direct pointer to the shutdown window after creation, so use + // Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually. + shutdownWindow->setAttribute(Qt::WA_DeleteOnClose); + shutdownWindow->setWindowTitle(window->windowTitle()); + + // Center shutdown window at where main window was + const QPoint global = window->mapToGlobal(window->rect().center()); + shutdownWindow->move(global.x() - shutdownWindow->width() / 2, global.y() - shutdownWindow->height() / 2); + shutdownWindow->show(); +} + +void ShutdownWindow::closeEvent(QCloseEvent *event) +{ + event->ignore(); +} diff --git a/pool/shard007/C++/0094361_xmlwriter.cpp b/pool/shard007/C++/0094361_xmlwriter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5bc0b5389f45b1f5d1fca988c6aadbf614a37277 --- /dev/null +++ b/pool/shard007/C++/0094361_xmlwriter.cpp @@ -0,0 +1,81 @@ +#include <config.h> + +#include <stdexcept> +#include <sstream> +#include "xmlwriter.hpp" + +XmlWriter::XmlWriter(std::ostream& outstream) : + out(outstream), + indent(0), + closetag(), + lasttag(), + sections() +{ +} + +XmlWriter::~XmlWriter() +{ + if(sections.size() > 0) { + std::cerr << "WARNING: NOT CLOSED: "; + for(std::vector<std::string>::iterator i = sections.begin(); + i != sections.end(); ++i) + std::cerr << *i << " "; + std::cerr << "\n"; + } + + closeTag(); +} + +void XmlWriter::openTag(const char* name) +{ + newLine(); + out << "<" << name; + closetag = ">"; + indent++; + + sections.push_back(name); +} + +void XmlWriter::closeTag(const char* name) +{ + if(sections.size() == 0) + throw std::runtime_error("got closeSection without prior openSection."); + + const std::string& lastsection = sections.back(); + if (lastsection != name) { + std::ostringstream msg; + msg << "mismatch in open/closeSection. Expected '" + << lastsection << "' got '" << name << "'"; + throw std::runtime_error(msg.str()); + } + sections.pop_back(); + + indent--; + newLine(); + // XXX: We should check for consistency here + out << "</" << name; + closetag = ">" ; +} + +void XmlWriter::writeTag(const char* name) +{ + newLine(); + out << "<" << name; + closetag = "/>"; + lasttag = name; +} + +void XmlWriter::newLine() +{ + if(closetag != "") { + closeTag(); + for (int i=0;i<indent;i++) + out << "\t"; + } +} + +void XmlWriter::closeTag() +{ + if (closetag != "") + out << closetag << "\n"; +} diff --git a/pool/shard007/C++/0094362_swizzle2_test.cpp b/pool/shard007/C++/0094362_swizzle2_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0c99712da11e948a08f8279690f634e953814d16 --- /dev/null +++ b/pool/shard007/C++/0094362_swizzle2_test.cpp @@ -0,0 +1,104 @@ +//Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc. + +//Distributed under the Boost Software License, Version 1.0. (See accompanying +//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +#include <boost/qvm/vec_operations.hpp> +#include <boost/qvm/vec_access.hpp> +#include <boost/qvm/vec.hpp> +#include <boost/qvm/swizzle.hpp> +#include "test_qvm_vector.hpp" + +int +main() + { + using namespace boost::qvm; + test_qvm::vector<V1,4> v1; + v1.a[0]=42.0f; + v1.a[1]=43.0f; + v1.a[2]=44.0f; + v1.a[3]=45.0f; + XX(v1) + XX(v1); + -XX(v1); + XX(42.0f) + XX(42.0f); + -XX(42.0f); + { + test_qvm::vector<V2,2> v0=X0(42.0f); + BOOST_TEST(v0.a[0]==42); + BOOST_TEST(v0.a[1]==0); + test_qvm::vector<V2,2> v2=_1X(42.0f); + BOOST_TEST(v2.a[0]==1); + BOOST_TEST(v2.a[1]==42); + float s=42.0f; + BOOST_TEST(&X(X1(s))==&s); + } + { + test_qvm::vector<V2,2> r; + r.a[0]=v1.a[0]; + r.a[1]=v1.a[0]; + test_qvm::vector<V2,2> v2=XX(v1); + BOOST_QVM_TEST_EQ(v2,r); + } + { + test_qvm::vector<V2,2> r; + r.a[0]=v1.a[0]; + r.a[1]=v1.a[1]; + test_qvm::vector<V2,2> v2=XY(v1); + BOOST_QVM_TEST_EQ(v2,r); + } + { + test_qvm::vector<V2,2> r; + r.a[0]=v1.a[0]; + r.a[1]=v1.a[2]; + test_qvm::vector<V2,2> v2=XZ(v1); + BOOST_QVM_TEST_EQ(v2,r); + } + { + test_qvm::vector<V2,2> r; + r.a[0]=v1.a[0]; + r.a[1]=v1.a[3]; + test_qvm::vector<V2,2> v2=XW(v1); + BOOST_QVM_TEST_EQ(v2,r); + } + { + test_qvm::vector<V2,2> r; + r.a[0]=v1.a[0]; + r.a[1]=0; + test_qvm::vector<V2,2> v2=X0(v1); + BOOST_QVM_TEST_EQ(v2,r); + } + { + test_qvm::vector<V2,2> r; + r.a[0]=v1.a[0]; + r.a[1]=1; + test_qvm::vector<V2,2> v2=X1(v1); + BOOST_QVM_TEST_EQ(v2,r); + } + { + test_qvm::vector<V2,2> v2=XY(v1); + test_qvm::vector<V3,2> v3; + XY(v3)=XY(v2); + BOOST_QVM_TEST_EQ(v2,v3); + } + { + test_qvm::vector<V1,2> v=_00(); + BOOST_TEST(v.a[0]==0); + BOOST_TEST(v.a[1]==0); + } + { + test_qvm::vector<V1,2> v=_01(); + BOOST_TEST(v.a[0]==0); + BOOST_TEST(v.a[1]==1); + } + { + test_qvm::vector<V1,2> v=_10(); + BOOST_TEST(v.a[0]==1); + BOOST_TEST(v.a[1]==0); + } + { + test_qvm::vector<V1,2> v=_11(); + BOOST_TEST(v.a[0]==1); + BOOST_TEST(v.a[1]==1); + } + return boost::report_errors(); + } diff --git a/pool/shard007/C++/0094364_IpeScopeBlock.cpp b/pool/shard007/C++/0094364_IpeScopeBlock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1b2e25f26061b86f1bbf6c17b28659e1e2ba5248 --- /dev/null +++ b/pool/shard007/C++/0094364_IpeScopeBlock.cpp @@ -0,0 +1,111 @@ +/* + * Copyright 2004-2015 Cray Inc. + * Other additional copyright holders may be indicated within. + * + * The entirety of this work is 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 "IpeScopeBlock.h" + +#include "AstDumpToNode.h" +#include "symbol.h" + +#include "IpeEnv.h" + +IpeScopeBlock::IpeScopeBlock(IpeScope* block) : IpeScope(block) +{ + +} + +IpeScopeBlock::~IpeScopeBlock() +{ + +} + +const char* IpeScopeBlock::type() const +{ + return "Block"; +} + +const char* IpeScopeBlock::name() const +{ + return "Block"; +} + +int IpeScopeBlock::frameSize() const +{ + int delta = 8; // NOAKES Size of every type is currently 8 + + return mParent->frameSize() + mVariables.size() * delta; +} + +bool IpeScopeBlock::isScopeBlockStmt() const +{ + return true; +} + +int IpeScopeBlock::locationSet(ArgSymbol* arg) const +{ + AstDumpToNode logger(stdout, 3); + + printf(" IpeScopeBlock::locationSet(ArgSymbol*) unsupported\n"); + printf(" "); + arg->accept(&logger); + printf("\n\n"); + + INT_ASSERT(false); + return 0; +} + +int IpeScopeBlock::locationSet(VarSymbol* var) const +{ + int retval = -1; + + INT_ASSERT(false); + + if (var == NULL || var->depth() >= 0 || var->offset() >= 0) + { + AstDumpToNode logger(stdout, 3); + + printf(" IpeScopeBlock::locationSet(VarSymbol*) unsupported\n"); + printf(" "); + var->accept(&logger); + printf("\n\n"); + + INT_ASSERT(false); + } + + else + { + int offset = mParent->frameSize(); + + for (size_t i = 0; i < mVariables.size() && retval == -1; i++) + { + if (mVariables[i] == var) + { + retval = offset; + var->locationSet(1, offset); + } + else + { + offset = offset + 8; + } + } + + INT_ASSERT(retval >= 0); + } + + return retval; +} diff --git a/pool/shard007/C++/0094365_DescribeComplianceByResourceResult.cpp b/pool/shard007/C++/0094365_DescribeComplianceByResourceResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb12cf34bd9f7d9fd4880e71816cd8e53b4cb5a7 --- /dev/null +++ b/pool/shard007/C++/0094365_DescribeComplianceByResourceResult.cpp @@ -0,0 +1,57 @@ +/* +* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ +#include <aws/config/model/DescribeComplianceByResourceResult.h> +#include <aws/core/utils/json/JsonSerializer.h> +#include <aws/core/AmazonWebServiceResult.h> +#include <aws/core/utils/UnreferencedParam.h> + +#include <utility> + +using namespace Aws::ConfigService::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +DescribeComplianceByResourceResult::DescribeComplianceByResourceResult() +{ +} + +DescribeComplianceByResourceResult::DescribeComplianceByResourceResult(const AmazonWebServiceResult<JsonValue>& result) +{ + *this = result; +} + +DescribeComplianceByResourceResult& DescribeComplianceByResourceResult::operator =(const AmazonWebServiceResult<JsonValue>& result) +{ + const JsonValue& jsonValue = result.GetPayload(); + if(jsonValue.ValueExists("ComplianceByResources")) + { + Array<JsonValue> complianceByResourcesJsonList = jsonValue.GetArray("ComplianceByResources"); + for(unsigned complianceByResourcesIndex = 0; complianceByResourcesIndex < complianceByResourcesJsonList.GetLength(); ++complianceByResourcesIndex) + { + m_complianceByResources.push_back(complianceByResourcesJsonList[complianceByResourcesIndex].AsObject()); + } + } + + if(jsonValue.ValueExists("NextToken")) + { + m_nextToken = jsonValue.GetString("NextToken"); + + } + + + + return *this; +} diff --git a/pool/shard007/C++/0094370_language_aware_rewriter.cc b/pool/shard007/C++/0094370_language_aware_rewriter.cc new file mode 100644 index 0000000000000000000000000000000000000000..4fee43941941bf6476ed2cf3843f41d94e9f7562 --- /dev/null +++ b/pool/shard007/C++/0094370_language_aware_rewriter.cc @@ -0,0 +1,270 @@ +// Copyright 2010-2014, 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. + +#include "rewriter/language_aware_rewriter.h" + +#include <string> + +#include "base/logging.h" +#include "base/util.h" +#include "composer/composer.h" +#include "config/config.pb.h" +#include "config/config_handler.h" +#include "converter/conversion_request.h" +#include "converter/segments.h" +#include "dictionary/dictionary_interface.h" +#include "dictionary/pos_matcher.h" +#include "session/commands.pb.h" +#include "usage_stats/usage_stats.h" + +namespace mozc { + +LanguageAwareRewriter::LanguageAwareRewriter( + const POSMatcher &pos_matcher, + const DictionaryInterface *dictionary) + : unknown_id_(pos_matcher.GetUnknownId()), + dictionary_(dictionary) {} + +LanguageAwareRewriter::~LanguageAwareRewriter() {} + +namespace { + +bool IsEnabled(const mozc::commands::Request &request) { + // The current default value of language_aware_input is + // NO_LANGUAGE_AWARE_INPUT and only unittests set LANGUAGE_AWARE_SUGGESTION + // at this moment. Thus, FillRawText is not performed in the productions + // yet. + if (request.language_aware_input() == + mozc::commands::Request::NO_LANGUAGE_AWARE_INPUT) { + return false; + } else if (request.language_aware_input() == + mozc::commands::Request::LANGUAGE_AWARE_SUGGESTION) { + return true; + } + DCHECK_EQ(mozc::commands::Request::DEFAULT_LANGUAGE_AWARE_BEHAVIOR, + request.language_aware_input()); + + if (!GET_CONFIG(use_spelling_correction)) { + return false; + } + +#ifdef OS_ANDROID + return false; +#else // OS_ANDROID + return true; +#endif // OS_ANDROID +} + +} // namespace + +int LanguageAwareRewriter::capability( + const ConversionRequest &request) const { + // Language aware input is performed only on suggestion or prediction. + if (!IsEnabled(request.request())) { + return RewriterInterface::NOT_AVAILABLE; + } + + return (RewriterInterface::SUGGESTION | RewriterInterface::PREDICTION); +} + +namespace { +bool IsRawQuery(const composer::Composer &composer, + const DictionaryInterface *dictionary, + int *rank) { + string raw_text; + composer.GetRawString(&raw_text); + + // Check if the length of text is less than or equal to three. + // For example, "cat" is not treated as a raw query so far to avoid + // false negative cases. + if (raw_text.size() <= 3) { + return false; + } + + // If the composition string is same with the raw_text, there is no + // need to add the candidate to suggestions. + string composition; + composer.GetStringForPreedit(&composition); + if (composition == raw_text) { + return false; + } + + // If alphabet characters are in the middle of the composition, it is + // probably a raw query. For example, "えぁmpぇ" (example) contains + // "m" and "p" in the middle. So it is treated as a raw query. On the + // other hand, "くえry" (query) contains alphabet characters, but they + // are at the end of the string, so it cannot be determined here. + // + // Note, GetQueryForPrediction omits the trailing alphabet characters of + // the composition string and returns it. + string key; + composer.GetQueryForPrediction(&key); + if (Util::ContainsScriptType(key, Util::ALPHABET)) { + *rank = 0; + return true; + } + + // If the input text is stored in the dictionary, it is perhaps a raw query. + // For example, the input characters of "れもヴぇ" (remove) is in the + // dictionary, so it is treated as a raw text. This logic is a little + // aggressive because "たけ" (take), "ほうせ" (house) and so forth are also + // treated as raw texts. + if (dictionary->HasValue(raw_text)) { + *rank = 2; + return true; + } + + return false; +} + +// Get T13n candidate ids from existing candidates. +void GetAlphabetIds(const Segment &segment, uint16 *lid, uint16 *rid) { + DCHECK(lid); + DCHECK(rid); + + for (int i = 0; i < segment.candidates_size(); ++i) { + const Segment::Candidate &candidate = segment.candidate(i); + const Util::ScriptType type = Util::GetScriptType(candidate.value); + if (type == Util::ALPHABET) { + *lid = candidate.lid; + *rid = candidate.rid; + return; + } + } +} +} // namespace + +// Note: This function seemed slow, but the benchmark tests +// resulted that it was only less than 0.1% point penalty. +// = session_handler_benchmark_test +// BM_PerformanceForRandomKeyEvents: 891944807 -> 892740748 (1.00089) +// = converter_benchmark_test +// BM_DesktopAnthyCorpusConversion 25062440090 -> 25101542382 (1.002) +// BM_DesktopStationPredictionCorpusPrediction 8695341697 -> 8672187681 (0.997) +// BM_DesktopStationPredictionCorpusSuggestion 6149502840 -> 6152393270 (1.000) +bool LanguageAwareRewriter::FillRawText( + const ConversionRequest &request, Segments *segments) const { + if (segments->conversion_segments_size() != 1 || !request.has_composer()) { + return false; + } + + int rank = 0; + if (!IsRawQuery(request.composer(), dictionary_, &rank)) { + return false; + } + + Segment *segment = segments->mutable_conversion_segment(0); + + string raw_string; + request.composer().GetRawString(&raw_string); + + uint16 lid = unknown_id_; + uint16 rid = unknown_id_; + GetAlphabetIds(*segment, &lid, &rid); + + // Create a candidate. + if (rank > segment->candidates_size()) { + rank = segment->candidates_size(); + } + Segment::Candidate *candidate = segment->insert_candidate(rank); + candidate->Init(); + candidate->value = raw_string; + candidate->key = raw_string; + candidate->content_value = raw_string; + candidate->content_key = raw_string; + candidate->lid = lid; + candidate->rid = rid; + + candidate->attributes |= (Segment::Candidate::NO_VARIANTS_EXPANSION | + Segment::Candidate::NO_EXTRA_DESCRIPTION); + candidate->prefix = "\xE2\x86\x92 "; // "→ " + candidate->description = + // "もしかして" + "\xE3\x82\x82\xE3\x81\x97\xE3\x81\x8B\xE3\x81\x97\xE3\x81\xA6"; + + // Set usage stats + usage_stats::UsageStats::IncrementCount("LanguageAwareSuggestionTriggered"); + + return true; +} + +bool LanguageAwareRewriter::Rewrite( + const ConversionRequest &request, Segments *segments) const { + if (!IsEnabled(request.request())) { + return false; + } + return FillRawText(request, segments); +} + +namespace { +bool IsLangaugeAwareInputCandidate(const composer::Composer &composer, + const Segment::Candidate &candidate) { + // Check candidate.prefix to filter if the candidate is probably generated + // from LanguangeAwareInput or not. + // + // "→ " + if (candidate.prefix != "\xE2\x86\x92 ") { + return false; + } + + string raw_string; + composer.GetRawString(&raw_string); + if (raw_string != candidate.value) { + return false; + } + return true; +} +} // namespace + +void LanguageAwareRewriter::Finish(const ConversionRequest &request, + Segments *segments) { + if (request.request().language_aware_input() != + mozc::commands::Request::LANGUAGE_AWARE_SUGGESTION) { + return; + } + + if (segments->conversion_segments_size() != 1 || !request.has_composer()) { + return; + } + + // Update usage stats + const Segment &segment = segments->conversion_segment(0); + // Ignores segments which are not converted or not committed. + if (segment.candidates_size() == 0 || + segment.segment_type() != Segment::FIXED_VALUE) { + return; + } + + if (IsLangaugeAwareInputCandidate(request.composer(), + segment.candidate(0))) { + usage_stats::UsageStats::IncrementCount("LanguageAwareSuggestionCommitted"); + } +} + +} // namespace mozc diff --git a/pool/shard007/C++/0094371_AddLayerVersionPermissionResult.cpp b/pool/shard007/C++/0094371_AddLayerVersionPermissionResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..25a4f6540292ef53fa01b9beb570a3d25ebf3d52 --- /dev/null +++ b/pool/shard007/C++/0094371_AddLayerVersionPermissionResult.cpp @@ -0,0 +1,56 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include <aws/lambda/model/AddLayerVersionPermissionResult.h> +#include <aws/core/utils/json/JsonSerializer.h> +#include <aws/core/AmazonWebServiceResult.h> +#include <aws/core/utils/StringUtils.h> +#include <aws/core/utils/UnreferencedParam.h> + +#include <utility> + +using namespace Aws::Lambda::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +AddLayerVersionPermissionResult::AddLayerVersionPermissionResult() +{ +} + +AddLayerVersionPermissionResult::AddLayerVersionPermissionResult(const Aws::AmazonWebServiceResult<JsonValue>& result) +{ + *this = result; +} + +AddLayerVersionPermissionResult& AddLayerVersionPermissionResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) +{ + JsonView jsonValue = result.GetPayload().View(); + if(jsonValue.ValueExists("Statement")) + { + m_statement = jsonValue.GetString("Statement"); + + } + + if(jsonValue.ValueExists("RevisionId")) + { + m_revisionId = jsonValue.GetString("RevisionId"); + + } + + + + return *this; +} diff --git a/pool/shard007/C++/0094374_replaygain.cpp b/pool/shard007/C++/0094374_replaygain.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5f72c40aa3a7725b1b4f1361c1e1c3d308570b2c --- /dev/null +++ b/pool/shard007/C++/0094374_replaygain.cpp @@ -0,0 +1,168 @@ +/* + * Cantata + * + * Copyright (c) 2011-2015 Craig Drummond <craig.p.drummond@gmail.com> + * + * ---- + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "replaygain.h" +#include "jobcontroller.h" +#include <QCoreApplication> +#include <stdio.h> + +// Work-around possible locale issues by forcing usage of '.' as separator +static QString formatDouble(double d) +{ + return QString::number(d, 'f', 10).replace(",", "."); +} + +ReplayGain::ReplayGain(const QStringList &fileNames) + : QObject(0) + , files(fileNames) + , lastProgress(-1) + , totalScanned(0) +{ + TrackScanner::init(); + JobController::self()->setMaxActive(8); +} + +ReplayGain::~ReplayGain() +{ + clearScanners(); +} + +void ReplayGain::scan() +{ + for (int i=0; i<files.count(); ++i) { + if (scanners.count()<100) { + createScanner(i); + } else { + toScan.append(i); + } + } +} + +void ReplayGain::createScanner(int index) +{ + TrackScanner *s=new TrackScanner(index); + s->setFile(files.at(index)); + connect(s, SIGNAL(progress(int)), this, SLOT(scannerProgress(int))); + connect(s, SIGNAL(done()), this, SLOT(scannerDone())); + scanners.insert(index, s); + JobController::self()->add(s); +} + +void ReplayGain::clearScanners() +{ + JobController::self()->cancel(); + QMap<int, TrackScanner *>::ConstIterator it(scanners.constBegin()); + QMap<int, TrackScanner *>::ConstIterator end(scanners.constEnd()); + + for (; it!=end; ++it) { + it.value()->stop(); + } + scanners.clear(); + toScan.clear(); + tracks.clear(); +} + +void ReplayGain::showProgress() +{ + int finished=0; + quint64 totalProgress=0; + QMap<int, Track>::iterator it=tracks.begin(); + QMap<int, Track>::iterator end=tracks.end(); + + for (; it!=end; ++it) { + if ((*it).finished) { + finished++; + } + totalProgress+=(*it).finished ? 100 : (*it).progress; + } + int progress=(totalProgress/files.count())+0.5; + progress=(progress/5)*5; + if (progress!=lastProgress) { + lastProgress=progress; + printf("PROGRESS: %02d\n", lastProgress); + fflush(stdout); + } +} + +void ReplayGain::showResults() +{ + QList<TrackScanner *> okScanners; + for (int i=0; i<files.count(); ++i) { + TrackScanner *s=scanners[i]; + const Track &t=tracks[i]; + if (t.success && s->ok()) { + printf("TRACK: %d %s %s\n", i, formatDouble(TrackScanner::reference(s->results().loudness)).toLatin1().constData(), + formatDouble(s->results().peakValue()).toLatin1().constData()); + okScanners.append(s); + } else { + printf("TRACK: %d FAILED\n", i); + } + } + + if (okScanners.isEmpty()) { + printf("ALBUM: FAILED\n"); + } else { + TrackScanner::Data album=TrackScanner::global(okScanners); + printf("ALBUM: %s %s\n", formatDouble(TrackScanner::reference(album.loudness)).toLatin1().constData(), + formatDouble(album.peak).toLatin1().constData()); + } + fflush(stdout); + + QCoreApplication::exit(0); +} + +void ReplayGain::scannerProgress(int p) +{ + TrackScanner *s=qobject_cast<TrackScanner *>(sender()); + if (!s) { + return; + } + + tracks[s->index()].progress=p; + showProgress(); +} + +void ReplayGain::scannerDone() +{ + TrackScanner *s=qobject_cast<TrackScanner *>(sender()); + if (!s) { + return; + } + Track &track=tracks[s->index()]; + if (!track.finished) { + track.finished=true; + track.success=s->success(); + track.progress=100; + showProgress(); + totalScanned++; + } + + if (toScan.isEmpty()) { + if (totalScanned==files.count()) { + showResults(); + } + } else { + int index=toScan.takeAt(0); + createScanner(index); + } +} diff --git a/pool/shard007/C++/0094378_cowvote.cpp b/pool/shard007/C++/0094378_cowvote.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0db7475b11626c447aa603402e70169d6b152ef0 --- /dev/null +++ b/pool/shard007/C++/0094378_cowvote.cpp @@ -0,0 +1,40 @@ +//+----------------------------------------------------------------------------- +// +// File: cowvote.cpp +// +// Synopsis: Sort II, problem 1 +// +// Author: Qirong Ma, 10/23/2015 +// +//------------------------------------------------------------------------------ +#include <cstdio> +#include "../../include/sort.h" + +struct cow { + int id; + int vote1; + int vote2; + cow(){} + bool operator< (const cow& c2){return vote1 > c2.vote1;} + bool operator<=(const cow& c2){return vote1 >= c2.vote1;} + bool operator>=(const cow& c2){return vote1 <= c2.vote1;} +} R1[50000], R2[50000]; + +int main() { + int i, N, K; + scanf("%d %d", &N, &K); + for (i = 0; i < N; i++) { + R1[i].id = i; + scanf("%d %d", &R1[i].vote1, &R1[i].vote2); + } + quickSort(R1, N); + + for (i = 0; i < K; i++) { + R2[i].id = R1[i].id; + R2[i].vote1 = R1[i].vote2; + } + quickSort(R2, K); + printf("%d\n", R2[0].id + 1); + + return 0; +} diff --git a/pool/shard007/C++/0094381_population_class.cpp b/pool/shard007/C++/0094381_population_class.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8dc73874935a33306cf783bacef48995cbeb9848 --- /dev/null +++ b/pool/shard007/C++/0094381_population_class.cpp @@ -0,0 +1,95 @@ +// _________ __ __ +// / _____// |_____________ _/ |______ ____ __ __ ______ +// \_____ \\ __\_ __ \__ \\ __\__ \ / ___\| | \/ ___/ +// / \| | | | \// __ \| | / __ \_/ /_/ > | /\___ | +// /_______ /|__| |__| (____ /__| (____ /\___ /|____//____ > +// \/ \/ \//_____/ \/ +// ______________________ ______________________ +// T H E W A R B E G I N S +// Stratagus - A free fantasy real time strategy game engine +// +// (c) Copyright 2022 by Andrettin +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; only version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +// 02111-1307, USA. + +#include "stratagus.h" + +#include "population/population_class.h" + +#include "economy/resource.h" +#include "util/assert_util.h" +#include "util/vector_util.h" + +namespace wyrmgus { + +void population_class::process_gsml_scope(const gsml_data &scope) +{ + const std::string &tag = scope.get_tag(); + const std::vector<std::string> &values = scope.get_values(); + + if (tag == "promotion_targets") { + for (const std::string &value : values) { + population_class *other_class = population_class::get(value); + this->promotion_targets.push_back(other_class); + other_class->demotion_targets.push_back(this); + } + } else if (tag == "production_efficiency") { + scope.for_each_property([&](const gsml_property &property) { + const std::string &key = property.get_key(); + const std::string &value = property.get_value(); + + const resource *resource = resource::get(key); + this->production_efficiency_map[resource] = std::stoi(value); + }); + } else { + data_entry::process_gsml_scope(scope); + } +} + +void population_class::check() const +{ + assert_throw(this->get_resource_icon() != nullptr); + + for (const population_class *promotion_target : this->get_promotion_targets()) { + if (vector::contains(promotion_target->get_promotion_targets(), this)) { + throw std::runtime_error("Population classes \"" + this->get_identifier() + "\" and \"" + promotion_target->get_identifier() + "\" are both set as promotion targets of each other."); + } + } + + for (const population_class *demotion_target : this->get_demotion_targets()) { + if (vector::contains(demotion_target->get_demotion_targets(), this)) { + throw std::runtime_error("Population classes \"" + this->get_identifier() + "\" and \"" + demotion_target->get_identifier() + "\" are both set as demotion targets of each other."); + } + } +} + +bool population_class::promotes_to(const population_class *other, const bool include_indirectly) const +{ + if (vector::contains(this->get_promotion_targets(), other)) { + return true; + } + + if (include_indirectly) { + for (const population_class *promotion_target : this->get_promotion_targets()) { + if (promotion_target->promotes_to(other, include_indirectly)) { + return true; + } + } + } + + return false; +} + +} diff --git a/pool/shard007/C++/0094383_commonsettingspage.cpp b/pool/shard007/C++/0094383_commonsettingspage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0f04805dc2095d7c22553253e990c67453f490c1 --- /dev/null +++ b/pool/shard007/C++/0094383_commonsettingspage.cpp @@ -0,0 +1,141 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of Qt Creator. +** +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://www.qt.io/licensing. For further information +** use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 or version 3 as published by the Free +** Software Foundation and appearing in the file LICENSE.LGPLv21 and +** LICENSE.LGPLv3 included in the packaging of this file. Please review the +** following information to ensure the GNU Lesser General Public License +** requirements will be met: https://www.gnu.org/licenses/lgpl.html and +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +****************************************************************************/ + +#include "commonsettingspage.h" +#include "vcsbaseconstants.h" + +#include "ui_commonsettingspage.h" + +#include <coreplugin/icore.h> +#include <coreplugin/vcsmanager.h> + +#include <utils/environment.h> +#include <utils/hostosinfo.h> + +#include <QCoreApplication> + +namespace VcsBase { +namespace Internal { + +// ------------------ VcsBaseSettingsWidget + +CommonSettingsWidget::CommonSettingsWidget(QWidget *parent) : + QWidget(parent), + m_ui(new Ui::CommonSettingsPage) +{ + m_ui->setupUi(this); + m_ui->submitMessageCheckScriptChooser->setExpectedKind(Utils::PathChooser::ExistingCommand); + m_ui->submitMessageCheckScriptChooser->setHistoryCompleter(QLatin1String("Vcs.MessageCheckScript.History")); + m_ui->nickNameFieldsFileChooser->setExpectedKind(Utils::PathChooser::File); + m_ui->nickNameFieldsFileChooser->setHistoryCompleter(QLatin1String("Vcs.NickFields.History")); + m_ui->nickNameMailMapChooser->setExpectedKind(Utils::PathChooser::File); + m_ui->nickNameMailMapChooser->setHistoryCompleter(QLatin1String("Vcs.NickMap.History")); + m_ui->sshPromptChooser->setExpectedKind(Utils::PathChooser::ExistingCommand); + m_ui->sshPromptChooser->setHistoryCompleter(QLatin1String("Vcs.SshPrompt.History")); + + updatePath(); + + connect(Core::VcsManager::instance(), SIGNAL(configurationChanged(const IVersionControl*)), + this, SLOT(updatePath())); +} + +CommonSettingsWidget::~CommonSettingsWidget() +{ + delete m_ui; +} + +CommonVcsSettings CommonSettingsWidget::settings() const +{ + CommonVcsSettings rc; + rc.nickNameMailMap = m_ui->nickNameMailMapChooser->path(); + rc.nickNameFieldListFile = m_ui->nickNameFieldsFileChooser->path(); + rc.submitMessageCheckScript = m_ui->submitMessageCheckScriptChooser->path(); + rc.lineWrap= m_ui->lineWrapCheckBox->isChecked(); + rc.lineWrapWidth = m_ui->lineWrapSpinBox->value(); + rc.sshPasswordPrompt = m_ui->sshPromptChooser->path(); + return rc; +} + +void CommonSettingsWidget::setSettings(const CommonVcsSettings &s) +{ + m_ui->nickNameMailMapChooser->setPath(s.nickNameMailMap); + m_ui->nickNameFieldsFileChooser->setPath(s.nickNameFieldListFile); + m_ui->submitMessageCheckScriptChooser->setPath(s.submitMessageCheckScript); + m_ui->lineWrapCheckBox->setChecked(s.lineWrap); + m_ui->lineWrapSpinBox->setValue(s.lineWrapWidth); + m_ui->sshPromptChooser->setPath(s.sshPasswordPrompt); +} + +void CommonSettingsWidget::updatePath() +{ + Utils::Environment env = Utils::Environment::systemEnvironment(); + QStringList toAdd = Core::VcsManager::additionalToolsPath(); + env.appendOrSetPath(toAdd.join(Utils::HostOsInfo::pathListSeparator())); + m_ui->sshPromptChooser->setEnvironment(env); +} + +// --------------- VcsBaseSettingsPage +CommonOptionsPage::CommonOptionsPage(QObject *parent) : + VcsBaseOptionsPage(parent) +{ + m_settings.fromSettings(Core::ICore::settings()); + + setId(Constants::VCS_COMMON_SETTINGS_ID); + setDisplayName(QCoreApplication::translate("VcsBase", Constants::VCS_COMMON_SETTINGS_NAME)); +} + +QWidget *CommonOptionsPage::widget() +{ + if (!m_widget) { + m_widget = new CommonSettingsWidget; + m_widget->setSettings(m_settings); + } + return m_widget; +} + +void CommonOptionsPage::apply() +{ + if (m_widget) { + const CommonVcsSettings newSettings = m_widget->settings(); + if (newSettings != m_settings) { + m_settings = newSettings; + m_settings.toSettings(Core::ICore::settings()); + emit settingsChanged(m_settings); + } + } +} + +void CommonOptionsPage::finish() +{ + delete m_widget; +} + +} // namespace Internal +} // namespace VcsBase diff --git a/pool/shard007/C++/0094385_ARCBBState.cpp b/pool/shard007/C++/0094385_ARCBBState.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9c9e5ea25c056a5475a269531d436bc2b8c184c2 --- /dev/null +++ b/pool/shard007/C++/0094385_ARCBBState.cpp @@ -0,0 +1,222 @@ +//===--- ARCBBState.cpp ---------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See http://swift.org/LICENSE.txt for license information +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#define DEBUG_TYPE "sil-global-arc-opts" +#include "ARCBBState.h" +#include "llvm/Support/Debug.h" + +using namespace swift; + +//===----------------------------------------------------------------------===// +// ARCBBState +//===----------------------------------------------------------------------===// + +namespace { + +using ARCBBState = ARCSequenceDataflowEvaluator::ARCBBState; + +} // end anonymous namespace + +/// Merge in the state of the successor basic block. This is an intersection +/// operation. +void ARCBBState::mergeSuccBottomUp(ARCBBState &SuccBBState) { + // For each [(SILValue, BottomUpState)] that we are tracking... + for (auto &Pair : getBottomupStates()) { + if (!Pair.hasValue()) + continue; + + SILValue RefCountedValue = Pair->first; + + // If our SILValue was blotted, skip it. This will be ignored for the rest + // of the ARC optimization. + if (!RefCountedValue) + continue; + + // Then attempt to lookup the corresponding (SILValue, BottomUpState) from + // SuccBB. If we fail to do so, blot this SILValue and continue. + // + // Since we are already initialized by initSuccBottomUp(), this has the + // effect of an intersection. + auto Other = SuccBBState.PtrToBottomUpState.find(RefCountedValue); + if (Other == SuccBBState.PtrToBottomUpState.end()) { + PtrToBottomUpState.blot(RefCountedValue); + continue; + } + + SILValue OtherRefCountedValue = (*Other)->first; + + // If the other ref count value was blotted, blot our value and continue. + // This has the effect of an intersection since we already checked earlier + // that RefCountedValue was not blotted. + if (!OtherRefCountedValue) { + PtrToBottomUpState.blot(RefCountedValue); + continue; + } + + BottomUpRefCountState &RefCountState = Pair->second; + BottomUpRefCountState &OtherRefCountState = (*Other)->second; + + // Ok, now we know that the merged set can safely represent a set of + // of instructions which together semantically act as one ref count + // increment. Merge the two states together. + if (!RefCountState.merge(OtherRefCountState)) { + PtrToBottomUpState.blot(RefCountedValue); + } + } +} + +/// Initialize this BB with the state of the successor basic block. This is +/// called on a basic block's state and then any other successors states are +/// merged in. +void ARCBBState::initSuccBottomUp(ARCBBState &SuccBBState) { + PtrToBottomUpState = SuccBBState.PtrToBottomUpState; +} + +/// Merge in the state of the predecessor basic block. +void ARCBBState::mergePredTopDown(ARCBBState &PredBBState) { + // For each [(SILValue, TopDownState)] that we are tracking... + for (auto &Pair : getTopDownStates()) { + if (!Pair.hasValue()) + continue; + + SILValue RefCountedValue = Pair->first; + + // If our SILValue was blotted, skip it. This will be ignored in the rest of + // the optimizer. + if (!RefCountedValue) + continue; + + // Then attempt to lookup the corresponding (SILValue, TopDownState) from + // PredBB. If we fail to do so, blot this SILValue and continue. + // + // Since we are already initialized by initPredTopDown(), this has the + // effect of an intersection. + auto Other = PredBBState.PtrToTopDownState.find(RefCountedValue); + if (Other == PredBBState.PtrToTopDownState.end()) { + PtrToTopDownState.blot(RefCountedValue); + continue; + } + + SILValue OtherRefCountedValue = (*Other)->first; + + // If the other ref count value was blotted, blot our value and continue. + // This has the effect of an intersection. + if (!OtherRefCountedValue) { + PtrToTopDownState.blot(RefCountedValue); + continue; + } + + // Ok, so now we know that the ref counted value we are tracking was not + // blotted on either side. Grab the states. + TopDownRefCountState &RefCountState = Pair->second; + TopDownRefCountState &OtherRefCountState = (*Other)->second; + + // Attempt to merge Other into this ref count state. If we fail, blot this + // ref counted value and continue. + if (!RefCountState.merge(OtherRefCountState)) { + DEBUG(llvm::dbgs() << "Failed to merge!\n"); + PtrToTopDownState.blot(RefCountedValue); + continue; + } + + DEBUG(llvm::dbgs() << " Partial: " + << (RefCountState.isPartial() ? "yes" : "no") << "\n"); + } +} + +/// Initialize the state for this BB with the state of its predecessor +/// BB. Used to create an initial state before we merge in other +/// predecessors. +void ARCBBState::initPredTopDown(ARCBBState &PredBBState) { + PtrToTopDownState = PredBBState.PtrToTopDownState; +} + +void ARCBBState::initializeTrapStatus() { IsTrapBB = isARCInertTrapBB(BB); } + +//===----------------------------------------------------------------------===// +// ARCBBStateInfo +//===----------------------------------------------------------------------===// + +namespace { + +using ARCBBStateInfo = ARCSequenceDataflowEvaluator::ARCBBStateInfo; +using ARCBBStateInfoHandle = ARCSequenceDataflowEvaluator::ARCBBStateInfoHandle; + +} // end anonymous namespace + +ARCBBStateInfo::ARCBBStateInfo(SILFunction *F, PostOrderAnalysis *POA) + : BBToBBIDMap(), BBIDToBottomUpBBStateMap(POA->get(F)->size()), + BBIDToTopDownBBStateMap(POA->get(F)->size()), BackedgeMap() { + + // Initialize state for each one of our BB's in the RPOT. *NOTE* This means + // that unreachable predecessors will not have any BBState associated with + // them. + for (SILBasicBlock *BB : POA->get(F)->getReversePostOrder()) { + unsigned BBID = BBToBBIDMap.size(); + BBToBBIDMap[BB] = BBID; + + BBIDToBottomUpBBStateMap[BBID].init(BB); + BBIDToTopDownBBStateMap[BBID].init(BB); + + for (auto &Succ : BB->getSuccessors()) + if (SILBasicBlock *SuccBB = Succ.getBB()) + if (BBToBBIDMap.count(SuccBB)) + BackedgeMap[BB].insert(SuccBB); + } +} + +llvm::Optional<ARCBBStateInfoHandle> +ARCBBStateInfo::getBottomUpBBHandle(SILBasicBlock *BB) { + auto OptID = getBBID(BB); + if (!OptID.hasValue()) + return None; + + unsigned ID = OptID.getValue(); + + auto BackedgeIter = BackedgeMap.find(BB); + if (BackedgeIter == BackedgeMap.end()) + return ARCBBStateInfoHandle(BB, ID, BBIDToBottomUpBBStateMap[ID]); + return ARCBBStateInfoHandle(BB, ID, BBIDToBottomUpBBStateMap[ID], + BackedgeIter->second); +} + +llvm::Optional<ARCBBStateInfoHandle> +ARCBBStateInfo::getTopDownBBHandle(SILBasicBlock *BB) { + auto MaybeID = getBBID(BB); + if (!MaybeID.hasValue()) + return None; + + unsigned ID = MaybeID.getValue(); + + auto BackedgeIter = BackedgeMap.find(BB); + if (BackedgeIter == BackedgeMap.end()) + return ARCBBStateInfoHandle(BB, ID, BBIDToTopDownBBStateMap[ID]); + return ARCBBStateInfoHandle(BB, ID, BBIDToTopDownBBStateMap[ID], + BackedgeIter->second); +} + +llvm::Optional<unsigned> ARCBBStateInfo::getBBID(SILBasicBlock *BB) const { + auto Iter = BBToBBIDMap.find(BB); + if (Iter == BBToBBIDMap.end()) + return None; + return Iter->second; +} + +void ARCBBStateInfo::clear() { + assert(BBIDToBottomUpBBStateMap.size() == BBIDToTopDownBBStateMap.size() && + "These should be one to one mapped to basic blocks so should" + " have the same size"); + for (unsigned i : indices(BBIDToBottomUpBBStateMap)) { + BBIDToBottomUpBBStateMap[i].clear(); + BBIDToTopDownBBStateMap[i].clear(); + } +} diff --git a/pool/shard007/C++/0094387_inputpluginstub.cpp b/pool/shard007/C++/0094387_inputpluginstub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3b7c10c1c3f847516de442ca1221eaa9aa40b239 --- /dev/null +++ b/pool/shard007/C++/0094387_inputpluginstub.cpp @@ -0,0 +1,106 @@ +/* + Q Light Controller + inputplugin_stub.cpp + + Copyright (c) Heikki Junnila + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + Version 2 as published by the Free Software Foundation. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. The license is + in the file "COPYING". + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ + +#include <QtPlugin> + +#include "inputpluginstub.h" +#include "qlctypes.h" + +/**************************************************************************** + * Initialization + ****************************************************************************/ + +InputPluginStub::~InputPluginStub() +{ +} + +void InputPluginStub::init() +{ + m_configureCalled = 0; + m_canConfigure = false; +} + +QString InputPluginStub::name() +{ + return QString("Input Plugin Stub"); +} + +/**************************************************************************** + * Inputs + ****************************************************************************/ + +void InputPluginStub::open(quint32 input) +{ + if (m_openLines.contains(input) == false && input < KInputUniverseCount) + m_openLines.append(input); +} + +void InputPluginStub::close(quint32 input) +{ + m_openLines.removeAll(input); +} + +QStringList InputPluginStub::inputs() +{ + QStringList list; + + for (quint32 i = 0; i < KInputUniverseCount; i++) + list << QString("%1: Stub %1").arg(i + 1); + + return list; +} + +QString InputPluginStub::infoText(quint32 input) +{ + return QString("%1: This is a plugin stub for testing.").arg(input); +} + +/**************************************************************************** + * Configuration + ****************************************************************************/ + +void InputPluginStub::configure() +{ + m_configureCalled++; + emit configurationChanged(); +} + +bool InputPluginStub::canConfigure() +{ + return m_canConfigure; +} + +/**************************************************************************** + * Feedback + ****************************************************************************/ + +void InputPluginStub::feedBack(quint32 input, quint32 channel, uchar value) +{ + m_feedBackInput = input; + m_feedBackChannel = channel; + m_feedBackValue = value; +} + +/**************************************************************************** + * Plugin export + ****************************************************************************/ + +Q_EXPORT_PLUGIN2(inputpluginstub, InputPluginStub) diff --git a/pool/shard007/C++/0094393_uber_ui.cc b/pool/shard007/C++/0094393_uber_ui.cc new file mode 100644 index 0000000000000000000000000000000000000000..7a08bb333f88267f4f6cc8a036d4a50864438ac1 --- /dev/null +++ b/pool/shard007/C++/0094393_uber_ui.cc @@ -0,0 +1,177 @@ +// Copyright (c) 2012 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 "chrome/browser/ui/webui/uber/uber_ui.h" + +#include "base/stl_util.h" +#include "base/utf_string_conversions.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/chrome_url_data_manager.h" +#include "chrome/browser/ui/webui/chrome_web_ui_data_source.h" +#include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h" +#include "chrome/browser/ui/webui/extensions/extensions_ui.h" +#include "chrome/browser/ui/webui/options2/options_ui2.h" +#include "chrome/common/url_constants.h" +#include "content/public/browser/navigation_controller.h" +#include "content/public/browser/navigation_entry.h" +#include "content/public/browser/web_contents.h" +#include "content/public/browser/web_ui.h" +#include "grit/browser_resources.h" +#include "grit/chromium_strings.h" +#include "grit/generated_resources.h" + +using content::NavigationController; +using content::NavigationEntry; +using content::RenderViewHost; +using content::WebContents; + +namespace { + +ChromeWebUIDataSource* CreateUberHTMLSource() { + ChromeWebUIDataSource* source = + new ChromeWebUIDataSource(chrome::kChromeUIUberHost); + + source->set_json_path("strings.js"); + source->add_resource_path("uber.js", IDR_UBER_JS); + source->add_resource_path("uber_utils.js", IDR_UBER_UTILS_JS); + source->set_default_resource(IDR_UBER_HTML); + + // Hack alert: continue showing "Loading..." until a real title is set. + source->AddLocalizedString("pageTitle", IDS_TAB_LOADING_TITLE); + + source->AddString("extensionsFrameURL", + ASCIIToUTF16(chrome::kChromeUIExtensionsFrameURL)); + source->AddString("extensionsHost", + ASCIIToUTF16(chrome::kChromeUIExtensionsHost)); + source->AddString("helpFrameURL", + ASCIIToUTF16(chrome::kChromeUIHelpFrameURL)); + source->AddString("helpHost", + ASCIIToUTF16(chrome::kChromeUIHelpHost)); + source->AddString("historyFrameURL", + ASCIIToUTF16(chrome::kChromeUIHistoryFrameURL)); + source->AddString("historyHost", + ASCIIToUTF16(chrome::kChromeUIHistoryHost)); + source->AddString("settingsFrameURL", + ASCIIToUTF16(chrome::kChromeUISettingsFrameURL)); + source->AddString("settingsHost", + ASCIIToUTF16(chrome::kChromeUISettingsHost)); + + return source; +} + +ChromeWebUIDataSource* CreateUberFrameHTMLSource() { + ChromeWebUIDataSource* source = + new ChromeWebUIDataSource(chrome::kChromeUIUberFrameHost); + + source->set_json_path("strings.js"); + source->add_resource_path("uber_frame.js", IDR_UBER_FRAME_JS); + source->set_default_resource(IDR_UBER_FRAME_HTML); + + // TODO(jhawkins): Attempt to get rid of IDS_PRODUCT_OS_NAME. +#if defined(OS_CHROMEOS) + source->AddLocalizedString("shortProductName", IDS_PRODUCT_OS_NAME); +#else + source->AddLocalizedString("shortProductName", IDS_SHORT_PRODUCT_NAME); +#endif // defined(OS_CHROMEOS) + + source->AddString("extensionsHost", + ASCIIToUTF16(chrome::kChromeUIExtensionsHost)); + source->AddLocalizedString("extensionsDisplayName", + IDS_MANAGE_EXTENSIONS_SETTING_WINDOWS_TITLE); + source->AddString("helpHost", + ASCIIToUTF16(chrome::kChromeUIHelpHost)); + source->AddLocalizedString("helpDisplayName", IDS_HELP_TITLE); + source->AddString("historyHost", + ASCIIToUTF16(chrome::kChromeUIHistoryHost)); + source->AddLocalizedString("historyDisplayName", IDS_HISTORY_TITLE); + source->AddString("settingsHost", + ASCIIToUTF16(chrome::kChromeUISettingsHost)); + source->AddLocalizedString("settingsDisplayName", IDS_SETTINGS_TITLE); + + return source; +} + +} // namespace + +UberUI::UberUI(content::WebUI* web_ui) : WebUIController(web_ui) { + Profile* profile = Profile::FromWebUI(web_ui); + profile->GetChromeURLDataManager()->AddDataSource(CreateUberHTMLSource()); + + // The user may use a virtual (short) URL to get to the page. To avoid + // duplicate uber tabs, clear the virtual URL so that the omnibox will show + // the real URL. http://crbug.com/111878. + NavigationController* controller = &web_ui->GetWebContents()->GetController(); + NavigationEntry* pending_entry = controller->GetPendingEntry(); + if (pending_entry) + pending_entry->SetVirtualURL(GURL()); + + RegisterSubpage(chrome::kChromeUIExtensionsFrameURL); + RegisterSubpage(chrome::kChromeUIHelpFrameURL); + RegisterSubpage(chrome::kChromeUIHistoryFrameURL); + RegisterSubpage(chrome::kChromeUISettingsFrameURL); + RegisterSubpage(chrome::kChromeUIUberFrameURL); +} + +UberUI::~UberUI() { + STLDeleteValues(&sub_uis_); +} + +void UberUI::RegisterSubpage(const std::string& page_url) { + content::WebUI* webui = + web_ui()->GetWebContents()->CreateWebUI(GURL(page_url)); + + webui->SetFrameXPath("//iframe[starts-with(@src,'" + page_url + "')]"); + sub_uis_[page_url] = webui; +} + +void UberUI::RenderViewCreated(RenderViewHost* render_view_host) { + for (SubpageMap::iterator iter = sub_uis_.begin(); iter != sub_uis_.end(); + ++iter) { + iter->second->GetController()->RenderViewCreated(render_view_host); + } +} + +void UberUI::RenderViewReused(RenderViewHost* render_view_host) { + for (SubpageMap::iterator iter = sub_uis_.begin(); iter != sub_uis_.end(); + ++iter) { + iter->second->GetController()->RenderViewReused(render_view_host); + } +} + +void UberUI::DidBecomeActiveForReusedRenderView() { + for (SubpageMap::iterator iter = sub_uis_.begin(); iter != sub_uis_.end(); + ++iter) { + iter->second->GetController()->DidBecomeActiveForReusedRenderView(); + } +} + +bool UberUI::OverrideHandleWebUIMessage(const GURL& source_url, + const std::string& message, + const ListValue& args) { + // Find the appropriate subpage and forward the message. + SubpageMap::iterator subpage = sub_uis_.find(source_url.GetOrigin().spec()); + if (subpage == sub_uis_.end()) { + // The message was sent from the uber page itself. + DCHECK_EQ(std::string(chrome::kChromeUIUberHost), source_url.host()); + return false; + } + + // The message was sent from a subpage. + // TODO(jam) fix this to use interface + // return subpage->second->GetController()->OverrideHandleWebUIMessage( + // source_url, message, args); + subpage->second->ProcessWebUIMessage(source_url, message, args); + return true; +} + +// UberFrameUI + +UberFrameUI::UberFrameUI(content::WebUI* web_ui) : WebUIController(web_ui) { + Profile* profile = Profile::FromWebUI(web_ui); + profile->GetChromeURLDataManager()->AddDataSource( + CreateUberFrameHTMLSource()); +} + +UberFrameUI::~UberFrameUI() { +} diff --git a/pool/shard007/C++/0094396_song_info.cpp b/pool/shard007/C++/0094396_song_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f9237e440a65266ceba4a82b62da437179a15c92 --- /dev/null +++ b/pool/shard007/C++/0094396_song_info.cpp @@ -0,0 +1,149 @@ +/*************************************************************************** + * Copyright (C) 2008-2014 by Andrzej Rybczak * + * electricityispower@gmail.com * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * + ***************************************************************************/ + +#include "global.h" +#include "helpers.h" +#include "song_info.h" +#include "tag_editor.h" +#include "tags.h" +#include "title.h" +#include "screen_switcher.h" + +#ifdef HAVE_TAGLIB_H +# include "fileref.h" +# include "tag.h" +# include "boost/lexical_cast.hpp" +#endif // HAVE_TAGLIB_H + +using Global::MainHeight; +using Global::MainStartY; + +SongInfo *mySongInfo; + +const SongInfo::Metadata SongInfo::Tags[] = +{ + { "Title", &MPD::Song::getTitle, &MPD::MutableSong::setTitle }, + { "Artist", &MPD::Song::getArtist, &MPD::MutableSong::setArtist }, + { "Album Artist", &MPD::Song::getAlbumArtist, &MPD::MutableSong::setAlbumArtist }, + { "Album", &MPD::Song::getAlbum, &MPD::MutableSong::setAlbum }, + { "Date", &MPD::Song::getDate, &MPD::MutableSong::setDate }, + { "Track", &MPD::Song::getTrack, &MPD::MutableSong::setTrack }, + { "Genre", &MPD::Song::getGenre, &MPD::MutableSong::setGenre }, + { "Composer", &MPD::Song::getComposer, &MPD::MutableSong::setComposer }, + { "Performer", &MPD::Song::getPerformer, &MPD::MutableSong::setPerformer }, + { "Disc", &MPD::Song::getDisc, &MPD::MutableSong::setDisc }, + { "Comment", &MPD::Song::getComment, &MPD::MutableSong::setComment }, + { 0, 0, 0 } +}; + +SongInfo::SongInfo() +: Screen(NC::Scrollpad(0, MainStartY, COLS, MainHeight, "", Config.main_color, NC::Border())) +{ } + +void SongInfo::resize() +{ + size_t x_offset, width; + getWindowResizeParams(x_offset, width); + w.resize(width, MainHeight); + w.moveTo(x_offset, MainStartY); + hasToBeResized = 0; +} + +std::wstring SongInfo::title() +{ + return L"Song info"; +} + +void SongInfo::switchTo() +{ + using Global::myScreen; + if (myScreen != this) + { + auto s = currentSong(myScreen); + if (!s) + return; + SwitchTo::execute(this); + w.clear(); + w.reset(); + PrepareSong(*s); + w.flush(); + // redraw header after we're done with the file, since reading it from disk + // takes a bit of time and having header updated before content of a window + // is displayed doesn't look nice. + drawHeader(); + } + else + switchToPreviousScreen(); +} + +void SongInfo::PrepareSong(const MPD::Song &s) +{ + w << NC::Format::Bold << Config.color1 << "Filename: " << NC::Format::NoBold << Config.color2 << s.getName() << '\n' << NC::Color::End; + w << NC::Format::Bold << "Directory: " << NC::Format::NoBold << Config.color2; + ShowTag(w, s.getDirectory()); + w << "\n\n" << NC::Color::End; + w << NC::Format::Bold << "Length: " << NC::Format::NoBold << Config.color2 << s.getLength() << '\n' << NC::Color::End; +# ifdef HAVE_TAGLIB_H + if (!Config.mpd_music_dir.empty() && !s.isStream()) + { + std::string path_to_file; + if (s.isFromDatabase()) + path_to_file += Config.mpd_music_dir; + path_to_file += s.getURI(); + TagLib::FileRef f(path_to_file.c_str()); + if (!f.isNull()) + { + std::string channels; + switch (f.audioProperties()->channels()) + { + case 1: + channels = "Mono"; + break; + case 2: + channels = "Stereo"; + break; + default: + channels = boost::lexical_cast<std::string>(f.audioProperties()->channels()); + break; + } + w << NC::Format::Bold << "Bitrate: " << NC::Format::NoBold << Config.color2 << f.audioProperties()->bitrate() << " kbps\n" << NC::Color::End; + w << NC::Format::Bold << "Sample rate: " << NC::Format::NoBold << Config.color2 << f.audioProperties()->sampleRate() << " Hz\n" << NC::Color::End; + w << NC::Format::Bold << "Channels: " << NC::Format::NoBold << Config.color2 << channels << NC::Color::End << "\n"; + + auto rginfo = Tags::readReplayGain(f.file()); + if (!rginfo.empty()) + { + w << NC::Format::Bold << "\nReference loudness: " << NC::Format::NoBold << Config.color2 << rginfo.referenceLoudness() << NC::Color::End << "\n"; + w << NC::Format::Bold << "Track gain: " << NC::Format::NoBold << Config.color2 << rginfo.trackGain() << NC::Color::End << "\n"; + w << NC::Format::Bold << "Track peak: " << NC::Format::NoBold << Config.color2 << rginfo.trackPeak() << NC::Color::End << "\n"; + w << NC::Format::Bold << "Album gain: " << NC::Format::NoBold << Config.color2 << rginfo.albumGain() << NC::Color::End << "\n"; + w << NC::Format::Bold << "Album peak: " << NC::Format::NoBold << Config.color2 << rginfo.albumPeak() << NC::Color::End << "\n"; + } + } + } +# endif // HAVE_TAGLIB_H + w << NC::Color::Default; + + for (const Metadata *m = Tags; m->Name; ++m) + { + w << NC::Format::Bold << '\n' << m->Name << ": " << NC::Format::NoBold; + ShowTag(w, s.getTags(m->Get)); + } +} diff --git a/pool/shard007/C++/0094399_exportpeaks.cpp b/pool/shard007/C++/0094399_exportpeaks.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9abb1e8c55ed4af3415bb0e491c43d725518ef40 --- /dev/null +++ b/pool/shard007/C++/0094399_exportpeaks.cpp @@ -0,0 +1,78 @@ +// exportpeaks.cpp +// +// Rivendell web service portal -- ExportPeaks service +// +// (C) Copyright 2010-2018 Fred Gleason <fredg@paravelsystems.com> +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License version 2 as +// published by the Free Software Foundation. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +// + +#include <stdio.h> +#include <stdint.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> + +#include <rdapplication.h> +#include <rdaudioconvert.h> +#include <rdcart.h> +#include <rdconf.h> +#include <rdformpost.h> +#include <rdsettings.h> +#include <rdweb.h> + +#include "rdxport.h" + +void Xport::ExportPeaks() +{ + // + // Verify Post + // + int cartnum=0; + if(!xport_post->getValue("CART_NUMBER",&cartnum)) { + XmlExit("Missing CART_NUMBER",400,"exportpeaks.cpp",LINE_NUMBER); + } + int cutnum=0; + if(!xport_post->getValue("CUT_NUMBER",&cutnum)) { + XmlExit("Missing CUT_NUMBER",400,"exportpeaks.cpp",LINE_NUMBER); + } + + // + // Verify User Perms + // + if(!rda->user()->cartAuthorized(cartnum)) { + XmlExit("No such cart",404,"exportpeaks.cpp",LINE_NUMBER); + } + + // + // Open Audio File + // + RDWaveFile *wave=new RDWaveFile(RDCut::pathName(cartnum,cutnum)); + if(!wave->openWave()) { + XmlExit("No such audio",404,"exportpeaks.cpp",LINE_NUMBER); + } + if(!wave->hasEnergy()) { + XmlExit("No peak data available",400,"exportpeaks.cpp",LINE_NUMBER); + } + + // + // Send Data + // + printf("Content-type: application/octet-stream\n\n"); + fflush(NULL); + unsigned short *peaks=new unsigned short[wave->energySize()]; + wave->readEnergy(peaks,wave->energySize()); + write(1,peaks,sizeof(unsigned short)*wave->energySize()); + Exit(0); +} diff --git a/pool/shard007/C++/0094400_objectregistry.cc b/pool/shard007/C++/0094400_objectregistry.cc new file mode 100644 index 0000000000000000000000000000000000000000..001edad3deafd57388616d6c27ea4658b2435366 --- /dev/null +++ b/pool/shard007/C++/0094400_objectregistry.cc @@ -0,0 +1,170 @@ +/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ +/* + * Copyright 2011 Couchbase, Inc + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "config.h" + +#include "ep_engine.h" +#include "objectregistry.h" + +static ThreadLocal<EventuallyPersistentEngine*> *th; +static ThreadLocal<Atomic<size_t>*> *initial_track; + +/** + * Object registry link hook for getting the registry thread local + * installed. + */ +class installer { +public: + installer() { + if (th == NULL) { + th = new ThreadLocal<EventuallyPersistentEngine*>(); + initial_track = new ThreadLocal<Atomic<size_t>*>(); + } + } +} install; + +static bool verifyEngine(EventuallyPersistentEngine *engine) +{ + if (engine == NULL) { + if (getenv("ALLOW_NO_STATS_UPDATE") != NULL) { + return false; + } else { + assert(engine); + } + } + return true; +} + + +void ObjectRegistry::onCreateBlob(Blob *blob) +{ + EventuallyPersistentEngine *engine = th->get(); + if (verifyEngine(engine)) { + EPStats &stats = engine->getEpStats(); + stats.currentSize.incr(blob->getSize()); + stats.totalValueSize.incr(blob->getSize()); + assert(stats.currentSize.get() < GIGANTOR); + } +} + +void ObjectRegistry::onDeleteBlob(Blob *blob) +{ + EventuallyPersistentEngine *engine = th->get(); + if (verifyEngine(engine)) { + EPStats &stats = engine->getEpStats(); + stats.currentSize.decr(blob->getSize()); + stats.totalValueSize.decr(blob->getSize()); + assert(stats.currentSize.get() < GIGANTOR); + } +} + +void ObjectRegistry::onCreateQueuedItem(QueuedItem *qi) +{ + EventuallyPersistentEngine *engine = th->get(); + if (verifyEngine(engine)) { + EPStats &stats = engine->getEpStats(); + stats.memOverhead.incr(qi->size()); + assert(stats.memOverhead.get() < GIGANTOR); + } +} + +void ObjectRegistry::onDeleteQueuedItem(QueuedItem *qi) +{ + EventuallyPersistentEngine *engine = th->get(); + if (verifyEngine(engine)) { + EPStats &stats = engine->getEpStats(); + stats.memOverhead.decr(qi->size()); + assert(stats.memOverhead.get() < GIGANTOR); + } +} + +void ObjectRegistry::onCreateItem(Item *pItem) +{ + EventuallyPersistentEngine *engine = th->get(); + if (verifyEngine(engine)) { + EPStats &stats = engine->getEpStats(); + stats.memOverhead.incr(pItem->size() - pItem->getValMemSize()); + assert(stats.memOverhead.get() < GIGANTOR); + } +} + +void ObjectRegistry::onDeleteItem(Item *pItem) +{ + EventuallyPersistentEngine *engine = th->get(); + if (verifyEngine(engine)) { + EPStats &stats = engine->getEpStats(); + stats.memOverhead.decr(pItem->size() - pItem->getValMemSize()); + assert(stats.memOverhead.get() < GIGANTOR); + } +} + +EventuallyPersistentEngine *ObjectRegistry::getCurrentEngine() { + return th->get(); +} + +EventuallyPersistentEngine *ObjectRegistry::onSwitchThread(EventuallyPersistentEngine *engine, + bool want_old_thread_local) +{ + EventuallyPersistentEngine *old_engine = NULL; + if (want_old_thread_local) { + old_engine = th->get(); + } + th->set(engine); + return old_engine; +} + +void ObjectRegistry::setStats(Atomic<size_t>* init_track) { + initial_track->set(init_track); +} + +bool ObjectRegistry::memoryAllocated(size_t mem) { + EventuallyPersistentEngine *engine = th->get(); + if (initial_track->get()) { + initial_track->get()->incr(mem); + } + if (!engine) { + return false; + } + EPStats &stats = engine->getEpStats(); + stats.totalMemory.incr(mem); + if (stats.memoryTrackerEnabled && stats.totalMemory.get() >= GIGANTOR) { + LOG(EXTENSION_LOG_WARNING, + "Total memory in memoryAllocated() >= GIGANTOR !!! " + "Disable the memory tracker...\n"); + stats.memoryTrackerEnabled.set(false); + } + return true; +} + +bool ObjectRegistry::memoryDeallocated(size_t mem) { + EventuallyPersistentEngine *engine = th->get(); + if (initial_track->get()) { + initial_track->get()->decr(mem); + } + if (!engine) { + return false; + } + EPStats &stats = engine->getEpStats(); + stats.totalMemory.decr(mem); + if (stats.memoryTrackerEnabled && stats.totalMemory.get() >= GIGANTOR) { + LOG(EXTENSION_LOG_WARNING, + "Total memory in memoryDeallocated() >= GIGANTOR !!! " + "Disable the memory tracker...\n"); + stats.memoryTrackerEnabled.set(false); + } + return true; +} diff --git a/pool/shard007/C++/0094401_direct_manipulation.cc b/pool/shard007/C++/0094401_direct_manipulation.cc new file mode 100644 index 0000000000000000000000000000000000000000..c35de0c7ec7cb371db77f32b1656159496f17f82 --- /dev/null +++ b/pool/shard007/C++/0094401_direct_manipulation.cc @@ -0,0 +1,114 @@ +// 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. + +#include "ui/gfx/win/direct_manipulation.h" + +#include "base/win/windows_version.h" + +namespace gfx { +namespace win { + +// static +scoped_ptr<DirectManipulationHelper> +DirectManipulationHelper::CreateInstance() { + scoped_ptr<DirectManipulationHelper> instance; + + if (base::win::GetVersion() >= base::win::VERSION_WIN10) + instance.reset(new DirectManipulationHelper); + + return instance; +} + +DirectManipulationHelper::DirectManipulationHelper() {} + +DirectManipulationHelper::~DirectManipulationHelper() {} + +void DirectManipulationHelper::Initialize(HWND window) { + DCHECK(::IsWindow(window)); + + // TODO(ananta) + // Remove the CHECK statements here and below and replace them with logs + // when this code stabilizes. + HRESULT hr = manager_.CreateInstance(CLSID_DirectManipulationManager, + nullptr, CLSCTX_INPROC_SERVER); + CHECK(SUCCEEDED(hr)); + + hr = compositor_.CreateInstance(CLSID_DCompManipulationCompositor, + nullptr, CLSCTX_INPROC_SERVER); + CHECK(SUCCEEDED(hr)); + + hr = manager_->GetUpdateManager(IID_PPV_ARGS(update_manager_.Receive())); + CHECK(SUCCEEDED(hr)); + + hr = compositor_->SetUpdateManager(update_manager_.get()); + CHECK(SUCCEEDED(hr)); + + hr = frame_info_.QueryFrom(compositor_.get()); + CHECK(SUCCEEDED(hr)); + + hr = manager_->CreateViewport(frame_info_.get(), window, + IID_PPV_ARGS(view_port_outer_.Receive())); + CHECK(SUCCEEDED(hr)); + + // + // Enable the desired configuration for each viewport. + // + DIRECTMANIPULATION_CONFIGURATION configuration = + DIRECTMANIPULATION_CONFIGURATION_INTERACTION + | DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_X + | DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_Y + | DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_INERTIA + | DIRECTMANIPULATION_CONFIGURATION_RAILS_X + | DIRECTMANIPULATION_CONFIGURATION_RAILS_Y + | DIRECTMANIPULATION_CONFIGURATION_SCALING + | DIRECTMANIPULATION_CONFIGURATION_SCALING_INERTIA; + + hr = view_port_outer_->ActivateConfiguration(configuration); + CHECK(SUCCEEDED(hr)); +} + +void DirectManipulationHelper::SetBounds(const gfx::Rect& bounds) { + base::win::ScopedComPtr<IDirectManipulationPrimaryContent> + primary_content_outer; + HRESULT hr = view_port_outer_->GetPrimaryContent( + IID_PPV_ARGS(primary_content_outer.Receive())); + CHECK(SUCCEEDED(hr)); + + base::win::ScopedComPtr<IDirectManipulationContent> content_outer; + hr = content_outer.QueryFrom(primary_content_outer.get()); + CHECK(SUCCEEDED(hr)); + + RECT rect = bounds.ToRECT(); + + hr = view_port_outer_->SetViewportRect(&rect); + CHECK(SUCCEEDED(hr)); + + hr = content_outer->SetContentRect(&rect); + CHECK(SUCCEEDED(hr)); +} + +void DirectManipulationHelper::Activate(HWND window) { + DCHECK(::IsWindow(window)); + manager_->Activate(window); +} + +void DirectManipulationHelper::Deactivate(HWND window) { + DCHECK(::IsWindow(window)); + manager_->Deactivate(window); +} + +void DirectManipulationHelper:: HandleMouseWheel(HWND window, UINT message, + WPARAM w_param, LPARAM l_param) { + MSG msg = { window, message, w_param, l_param}; + + HRESULT hr = view_port_outer_->SetContact(DIRECTMANIPULATION_MOUSEFOCUS); + if (SUCCEEDED(hr)) { + BOOL handled = FALSE; + manager_->ProcessInput(&msg, &handled); + view_port_outer_->ReleaseContact(DIRECTMANIPULATION_MOUSEFOCUS); + } +} + +} // namespace win. +} // namespace gfx. diff --git a/pool/shard007/C++/0094406_FilterAddCommand.cpp b/pool/shard007/C++/0094406_FilterAddCommand.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9faaec19132b98490cfdc742e454550ea64bfdcc --- /dev/null +++ b/pool/shard007/C++/0094406_FilterAddCommand.cpp @@ -0,0 +1,64 @@ +/* This file is part of the KDE project + * Copyright (c) 2009 Jan Hambrecht <jaham@gmx.net> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "FilterAddCommand.h" +#include "KoShape.h" +#include "KoFilterEffect.h" +#include "KoFilterEffectStack.h" + +#include <klocale.h> + +FilterAddCommand::FilterAddCommand(KoFilterEffect *filterEffect, KoShape * shape, KUndo2Command *parent) + : KUndo2Command(parent), m_filterEffect(filterEffect), m_shape(shape), m_isAdded(false) +{ + Q_ASSERT(m_shape); + setText(i18nc("(qtundo-format)", "Add filter effect")); +} + +FilterAddCommand::~FilterAddCommand() +{ + if (!m_isAdded) + delete m_filterEffect; +} + +void FilterAddCommand::redo() +{ + KUndo2Command::redo(); + + if (m_shape->filterEffectStack()) { + m_shape->update(); + m_shape->filterEffectStack()->appendFilterEffect(m_filterEffect); + m_shape->update(); + m_isAdded = true; + } +} + +void FilterAddCommand::undo() +{ + if (m_shape->filterEffectStack()) { + int index = m_shape->filterEffectStack()->filterEffects().indexOf(m_filterEffect); + if (index >= 0) { + m_shape->update(); + m_shape->filterEffectStack()->takeFilterEffect(index); + m_shape->update(); + } + m_isAdded = false; + } + KUndo2Command::undo(); +} diff --git a/pool/shard007/C++/0094409_main.cpp b/pool/shard007/C++/0094409_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..81bd1229758902bab6a22987c909968861d4c0e9 --- /dev/null +++ b/pool/shard007/C++/0094409_main.cpp @@ -0,0 +1,117 @@ +#include "pch.h" +#include "engine.h" + +#if defined _DEBUG +#define new new(__FILE__, __LINE__) +#endif + +namespace d3d11 +{ + using namespace ang; + using namespace ang::platform; + using namespace ang::platform::windows; + + class main_app; + typedef object_wrapper<main_app> main_app_t; + + class main_wnd : public window + { + public: + main_wnd(); + + ANG_DECLARE_INTERFACE(); + + virtual void window_proc(events::message_t msg)override { + if (msg->msg() == events::win_msg_enum::erase_bkgnd + || msg->msg() == events::win_msg_enum::draw) + { + graphics::paint_dc_t dc = new graphics::paint_dc(this); + } + else + { + return window::window_proc(msg.get()); + } + } + + private: + virtual~main_wnd(); + }; + + class main_app : public app + { + engine_t _engine; + + public: + main_app(); + + ANG_DECLARE_INTERFACE(); + + bool init_app(array<string> cmdl)override; + bool exit_app()override; + + private: + virtual~main_app(); + }; + +} + +int main(int argc, char* argv[]) +{ + d3d11::main_app_t app = new d3d11::main_app(); + return (int)app->run(); +} + + +d3d11::main_wnd::main_wnd() +{ +} + +d3d11::main_wnd::~main_wnd() +{ + +} + + +ANG_IMPLEMENT_BASIC_INTERFACE(d3d11::main_wnd, window); + + +d3d11::main_app::main_app() +{ + _engine = new engine(); +} + +d3d11::main_app::~main_app() +{ + _engine = null; +} + +ANG_IMPLEMENT_BASIC_INTERFACE(d3d11::main_app, app); + +bool d3d11::main_app::init_app(ang::array<ang::string> cmdl) +{ + app::init_app(cmdl); + + window_t wnd = new d3d11::main_wnd(); + + wnd->created_event += new events::created_event(_engine, &engine::on_create_event); + wnd->destroyed_event += new events::destroyed_event(_engine, &engine::on_destroy_event); + wnd->size_event += new events::display_size_change_event(_engine, &engine::on_size_changed_event); + wnd->mouse_moved_event += new events::pointer_moved_event(_engine, &engine::on_pointer_moved_event); + wnd->mouse_button_pressed_event += new events::pointer_moved_event(_engine, &engine::on_pointer_pressed_event); + wnd->mouse_button_released_event += new events::pointer_moved_event(_engine, &engine::on_pointer_released_event); + + if (!wnd->create(new wnd_create_args( + "d3d11_core_view_wnd", "d3d11 Task3", { 100,100, 1124, 900 } + ))) + return false; + set_main_wnd(wnd); + + wnd->update_wnd(); + wnd->show(showing_flag::show); + return true; +} + +bool d3d11::main_app::exit_app() +{ + return app::exit_app(); +} \ No newline at end of file diff --git a/pool/shard007/C++/0094412_FSharedModuleConsole.cpp b/pool/shard007/C++/0094412_FSharedModuleConsole.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6d370e11b13cabc28994d7e2abaed90c2f700041 --- /dev/null +++ b/pool/shard007/C++/0094412_FSharedModuleConsole.cpp @@ -0,0 +1,48 @@ +#include "MoCrModule.h" + +MO_NAMESPACE_BEGIN + +//============================================================ +// <T>¹¹Ôì¹²ÏíÄ£¿é¿ØÖÆÌ¨¡£</T> +// +// @return ¹²ÏíÄ£¿é¿ØÖÆÌ¨ +//============================================================ +FSharedModuleConsole::FSharedModuleConsole(){ + _pModules = MO_CREATE(FSharedModuleList); +} + +//============================================================ +// <T>Îö¹¹¹²ÏíÄ£¿é¿ØÖÆÌ¨¡£</T> +//============================================================ +FSharedModuleConsole::~FSharedModuleConsole(){ + MO_DELETE(_pModules); +} + +//============================================================ +// <T>»ñµÃ¹²ÏíÄ£¿éÁÐ±í¡£</T> +// +// @return ¹²ÏíÄ£¿éÁбí +//============================================================ +FSharedModuleList* FSharedModuleConsole::Modules(){ + return _pModules; +} + +//============================================================ +// <T>×¢²á¹²ÏíÄ£¿é¡£</T> +// +// @param pModule ¹²ÏíÄ£¿é +//============================================================ +void FSharedModuleConsole::Register(FSharedModule* pModule){ + _pModules->Push(pModule); +} + +//============================================================ +// <T>×¢Ïú¹²ÏíÄ£¿é¡£</T> +// +// @param pModule ¹²ÏíÄ£¿é +//============================================================ +void FSharedModuleConsole::Unregister(FSharedModule* pModule){ + _pModules->Remove(pModule); +} + +MO_NAMESPACE_END diff --git a/pool/shard007/C++/0094416_PlatformGraphicsContext.cpp b/pool/shard007/C++/0094416_PlatformGraphicsContext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fcdcce983b81e5caf33443d11bb64bf22a7c2956 --- /dev/null +++ b/pool/shard007/C++/0094416_PlatformGraphicsContext.cpp @@ -0,0 +1,74 @@ +/* + * Copyright 2006, The Android Open Source Project + * + * 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. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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 "config.h" +#include "Node.h" +#include "PlatformGraphicsContext.h" +#include "SkCanvas.h" + +namespace WebCore { + +PlatformGraphicsContext::PlatformGraphicsContext(SkCanvas* canvas, WTF::Vector<Container>* buttons) + : mCanvas(canvas), m_deleteCanvas(false), m_buttons(buttons) +{ +} + +PlatformGraphicsContext::PlatformGraphicsContext() + : mCanvas(new SkCanvas), m_deleteCanvas(true), m_buttons(0) +{ +} + +PlatformGraphicsContext::~PlatformGraphicsContext() +{ + if (m_deleteCanvas) { +// printf("-------------------- deleting offscreen canvas\n"); + delete mCanvas; + } +} + +void PlatformGraphicsContext::storeButtonInfo(Node* node, const IntRect& r) +{ + if (m_buttons == NULL) + return; + // Check to see if we already have a Container for this node. If so, update + // it with the new rectangle and make the new recording canvas reference + // its picture. + Container* end = m_buttons->end(); + for (Container* ptr = m_buttons->begin(); ptr != end; ptr++) { + if (ptr->matches(node)) { + mCanvas->drawPicture(*(ptr->picture())); + ptr->setRect(r); + return; + } + } + // We did not have a Container representing this node, so create a new one. + Container container(node, r); + // Place a reference to our subpicture in the Picture. + mCanvas->drawPicture(*(container.picture())); + // Keep track of the information about the button. + m_buttons->append(container); +} + +} // WebCore diff --git a/pool/shard007/C++/0094420_options_page_apitest.cc b/pool/shard007/C++/0094420_options_page_apitest.cc new file mode 100644 index 0000000000000000000000000000000000000000..410ca61583e6bdfe316eeb30216bd7612f7f2cfc --- /dev/null +++ b/pool/shard007/C++/0094420_options_page_apitest.cc @@ -0,0 +1,57 @@ +// Copyright (c) 2012 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 "chrome/browser/extensions/extension_browsertest.h" +#include "chrome/browser/extensions/extension_service.h" +#include "chrome/browser/extensions/extension_system.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_tabstrip.h" +#include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/common/extensions/extension.h" +#include "chrome/common/url_constants.h" +#include "chrome/test/base/ui_test_utils.h" +#include "content/public/browser/notification_service.h" +#include "content/public/test/browser_test_utils.h" + +using extensions::Extension; + +// Used to simulate a click on the first element named 'Options'. +static const char kScriptClickOptionButton[] = + "(function() { " + " var button = document.querySelector('.options-link');" + " button.click();" + "})();"; + +// Test that an extension with an options page makes an 'Options' button appear +// on chrome://extensions, and that clicking the button opens a new tab with the +// extension's options page. +// Disabled because of flakiness. See http://crbug.com/174934. +IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, DISABLED_OptionsPage) { + ExtensionService* service = extensions::ExtensionSystem::Get( + browser()->profile())->extension_service(); + size_t installed_extensions = service->extensions()->size(); + // Install an extension with an options page. + const Extension* extension = + InstallExtension(test_data_dir_.AppendASCII("options.crx"), 1); + ASSERT_TRUE(extension); + EXPECT_EQ(installed_extensions + 1, service->extensions()->size()); + + // Go to the Extension Settings page and click the Options button. + ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIExtensionsURL)); + TabStripModel* tab_strip = browser()->tab_strip_model(); + ui_test_utils::WindowedTabAddedNotificationObserver observer( + content::NotificationService::AllSources()); + // NOTE: Currently the above script needs to execute in an iframe. The + // selector for that iframe may break if the layout of the extensions + // page changes. + EXPECT_TRUE(content::ExecuteScriptInFrame( + tab_strip->GetActiveWebContents(), + "//iframe[starts-with(@src, 'chrome://extension')]", + kScriptClickOptionButton)); + observer.Wait(); + EXPECT_EQ(2, tab_strip->count()); + + EXPECT_EQ(extension->GetResourceURL("options.html"), + tab_strip->GetWebContentsAt(1)->GetURL()); +} diff --git a/pool/shard007/C++/0094423_IFCProfile.cpp b/pool/shard007/C++/0094423_IFCProfile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..daafc9afed798e023ebf8b5f56f104abe59d65d4 --- /dev/null +++ b/pool/shard007/C++/0094423_IFCProfile.cpp @@ -0,0 +1,190 @@ +/* +Open Asset Import Library (assimp) +---------------------------------------------------------------------- + +Copyright (c) 2006-2019, assimp team + + +All rights reserved. + +Redistribution and use of this software 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 assimp team, nor the names of its + contributors may be used to endorse or promote products + derived from this software without specific prior + written permission of the assimp team. + +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 IFCProfile.cpp + * @brief Read profile and curves entities from IFC files + */ + +#ifndef ASSIMP_BUILD_NO_IFC_IMPORTER + +#include "IFCUtil.h" + +namespace Assimp { +namespace IFC { + +// ------------------------------------------------------------------------------------------------ +void ProcessPolyLine(const Schema_2x3::IfcPolyline& def, TempMesh& meshout, ConversionData& /*conv*/) +{ + // this won't produce a valid mesh, it just spits out a list of vertices + IfcVector3 t; + for(const Schema_2x3::IfcCartesianPoint& cp : def.Points) { + ConvertCartesianPoint(t,cp); + meshout.mVerts.push_back(t); + } + meshout.mVertcnt.push_back(static_cast<unsigned int>(meshout.mVerts.size())); +} + +// ------------------------------------------------------------------------------------------------ +bool ProcessCurve(const Schema_2x3::IfcCurve& curve, TempMesh& meshout, ConversionData& conv) +{ + std::unique_ptr<const Curve> cv(Curve::Convert(curve,conv)); + if (!cv) { + IFCImporter::LogWarn("skipping unknown IfcCurve entity, type is " + curve.GetClassName()); + return false; + } + + // we must have a bounded curve at this point + if (const BoundedCurve* bc = dynamic_cast<const BoundedCurve*>(cv.get())) { + try { + bc->SampleDiscrete(meshout); + } + catch(const CurveError& cv) { + IFCImporter::LogError(cv.mStr + " (error occurred while processing curve)"); + return false; + } + meshout.mVertcnt.push_back(static_cast<unsigned int>(meshout.mVerts.size())); + return true; + } + + IFCImporter::LogError("cannot use unbounded curve as profile"); + return false; +} + +// ------------------------------------------------------------------------------------------------ +void ProcessClosedProfile(const Schema_2x3::IfcArbitraryClosedProfileDef& def, TempMesh& meshout, ConversionData& conv) +{ + ProcessCurve(def.OuterCurve,meshout,conv); +} + +// ------------------------------------------------------------------------------------------------ +void ProcessOpenProfile(const Schema_2x3::IfcArbitraryOpenProfileDef& def, TempMesh& meshout, ConversionData& conv) +{ + ProcessCurve(def.Curve,meshout,conv); +} + +// ------------------------------------------------------------------------------------------------ +void ProcessParametrizedProfile(const Schema_2x3::IfcParameterizedProfileDef& def, TempMesh& meshout, ConversionData& conv) +{ + if(const Schema_2x3::IfcRectangleProfileDef* const cprofile = def.ToPtr<Schema_2x3::IfcRectangleProfileDef>()) { + const IfcFloat x = cprofile->XDim*0.5f, y = cprofile->YDim*0.5f; + + meshout.mVerts.reserve(meshout.mVerts.size()+4); + meshout.mVerts.push_back( IfcVector3( x, y, 0.f )); + meshout.mVerts.push_back( IfcVector3(-x, y, 0.f )); + meshout.mVerts.push_back( IfcVector3(-x,-y, 0.f )); + meshout.mVerts.push_back( IfcVector3( x,-y, 0.f )); + meshout.mVertcnt.push_back(4); + } + else if( const Schema_2x3::IfcCircleProfileDef* const circle = def.ToPtr<Schema_2x3::IfcCircleProfileDef>()) { + if(def.ToPtr<Schema_2x3::IfcCircleHollowProfileDef>()) { + // TODO + } + const size_t segments = conv.settings.cylindricalTessellation; + const IfcFloat delta = AI_MATH_TWO_PI_F/segments, radius = circle->Radius; + + meshout.mVerts.reserve(segments); + + IfcFloat angle = 0.f; + for(size_t i = 0; i < segments; ++i, angle += delta) { + meshout.mVerts.push_back( IfcVector3( std::cos(angle)*radius, std::sin(angle)*radius, 0.f )); + } + + meshout.mVertcnt.push_back(static_cast<unsigned int>(segments)); + } + else if( const Schema_2x3::IfcIShapeProfileDef* const ishape = def.ToPtr<Schema_2x3::IfcIShapeProfileDef>()) { + // construct simplified IBeam shape + const IfcFloat offset = (ishape->OverallWidth - ishape->WebThickness) / 2; + const IfcFloat inner_height = ishape->OverallDepth - ishape->FlangeThickness * 2; + + meshout.mVerts.reserve(12); + meshout.mVerts.push_back(IfcVector3(0,0,0)); + meshout.mVerts.push_back(IfcVector3(0,ishape->FlangeThickness,0)); + meshout.mVerts.push_back(IfcVector3(offset,ishape->FlangeThickness,0)); + meshout.mVerts.push_back(IfcVector3(offset,ishape->FlangeThickness + inner_height,0)); + meshout.mVerts.push_back(IfcVector3(0,ishape->FlangeThickness + inner_height,0)); + meshout.mVerts.push_back(IfcVector3(0,ishape->OverallDepth,0)); + meshout.mVerts.push_back(IfcVector3(ishape->OverallWidth,ishape->OverallDepth,0)); + meshout.mVerts.push_back(IfcVector3(ishape->OverallWidth,ishape->FlangeThickness + inner_height,0)); + meshout.mVerts.push_back(IfcVector3(offset+ishape->WebThickness,ishape->FlangeThickness + inner_height,0)); + meshout.mVerts.push_back(IfcVector3(offset+ishape->WebThickness,ishape->FlangeThickness,0)); + meshout.mVerts.push_back(IfcVector3(ishape->OverallWidth,ishape->FlangeThickness,0)); + meshout.mVerts.push_back(IfcVector3(ishape->OverallWidth,0,0)); + + meshout.mVertcnt.push_back(12); + } + else { + IFCImporter::LogWarn("skipping unknown IfcParameterizedProfileDef entity, type is " + def.GetClassName()); + return; + } + + IfcMatrix4 trafo; + ConvertAxisPlacement(trafo, *def.Position); + meshout.Transform(trafo); +} + +// ------------------------------------------------------------------------------------------------ +bool ProcessProfile(const Schema_2x3::IfcProfileDef& prof, TempMesh& meshout, ConversionData& conv) +{ + if(const Schema_2x3::IfcArbitraryClosedProfileDef* const cprofile = prof.ToPtr<Schema_2x3::IfcArbitraryClosedProfileDef>()) { + ProcessClosedProfile(*cprofile,meshout,conv); + } + else if(const Schema_2x3::IfcArbitraryOpenProfileDef* const copen = prof.ToPtr<Schema_2x3::IfcArbitraryOpenProfileDef>()) { + ProcessOpenProfile(*copen,meshout,conv); + } + else if(const Schema_2x3::IfcParameterizedProfileDef* const cparam = prof.ToPtr<Schema_2x3::IfcParameterizedProfileDef>()) { + ProcessParametrizedProfile(*cparam,meshout,conv); + } + else { + IFCImporter::LogWarn("skipping unknown IfcProfileDef entity, type is " + prof.GetClassName()); + return false; + } + meshout.RemoveAdjacentDuplicates(); + if (!meshout.mVertcnt.size() || meshout.mVertcnt.front() <= 1) { + return false; + } + return true; +} + +} // ! IFC +} // ! Assimp + +#endif // ASSIMP_BUILD_NO_IFC_IMPORTER diff --git a/pool/shard007/C++/0094429_reportgeneratorbase.cpp b/pool/shard007/C++/0094429_reportgeneratorbase.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c7b4104e32f20271874877388dcda41f52c0835 --- /dev/null +++ b/pool/shard007/C++/0094429_reportgeneratorbase.cpp @@ -0,0 +1,109 @@ +#include "reportgeneratorbase.h" +#include <sstream> +#include <ctime> + +namespace QtAddons { +ReportGeneratorBase::ReportGeneratorBase(std::string name) : + logger(name), + m_fLine(0.0), + m_fMargin(10.0f), + m_fLineHeight(14.0), + m_FontColor(QColor("black")) +{ + +} + +void ReportGeneratorBase::OpenDestination(QString fname) +{ + m_Printer.setOutputFormat(QPrinter::PdfFormat); + m_Printer.setPageSize(QPageSize(QPageSize::A4)); + m_Printer.setPageMargins(QMarginsF(m_fMargin,m_fMargin,m_fMargin,m_fMargin),QPageLayout::Millimeter); + m_Printer.setOutputFileName(fname); + + m_fWidth = m_Printer.width(); + m_fHeight = m_Printer.width(); +} + +int ReportGeneratorBase::DrawImage(float *pImg, int *srcdims, int *dstdims, int x,int y, bool drawframe) +{ +// size_t imgdims[4]={size_t(srcdims[0]),size_t(srcdims[1]),size_t(srcdims[2]),size_t(srcdims[3])}; + +// m_ImagePainter.setImage(pImg,imgdims); + +// m_ImagePainter.Render(m_Painter,x,y,dstdims[0],dstdims[1]); + return 0; +} + +double ReportGeneratorBase::MakeHeader(const std::string name) +{ + + std::ostringstream msg; + + QFont font("helvetic",10); + QFontMetrics fm(font); + msg<<"Reporting "<<name; + m_Painter.drawText(0,fm.height(),QString::fromStdString(msg.str())); + + char timestr[256]; + time_t currenttime=0; + time(¤ttime); + struct tm* timeinfo; + timeinfo=localtime(¤ttime); + + strftime(timestr,256,"%Y-%m-%d, %X",timeinfo); + //msg.str(""); msg<<"Processing date: "<<timestr; + msg.str(""); msg<<timestr; + QString str=QString::fromStdString(msg.str()); + int w=fm.horizontalAdvance(str); + + m_Painter.drawText(m_fWidth-w-2*m_fMargin,fm.height(),str); + m_Painter.drawLine(0,fm.height()*1.5,m_fWidth, fm.height()*1.5); + + m_fLine+=fm.height()*2.5; + return 0; +} + +double ReportGeneratorBase::Print(std::string text, double size) +{ + size_t p1=text.find('\n'); + std::string t0; + std::string t1=text; + + m_Painter.setPen(m_FontColor); + + QFont font("helvetic",size); + m_Painter.setFont(font); + + QFontMetrics fm(font); + + double height=fm.height(); + + do { + if (p1==std::string::npos) { + t0=t1; + t1.clear(); + } + else { + t0=t1.substr(0,p1); + t1=t1.substr(p1+1); + } + + Print(t0,0,m_fLine,size); + p1=t1.find('\n'); + m_fLine+=1.25*height; + + } while (!t1.empty()); + + return m_fLine; +} + +double ReportGeneratorBase::Print(std::string text, double x, double y, double size) +{ + m_Painter.setPen(m_FontColor); + m_Painter.setFont(QFont("helvetic",size)); + m_Painter.drawText(x,y,QString::fromStdString(text)); + + return 0.0; +} + +} diff --git a/pool/shard007/C++/0094433_Timer.cpp b/pool/shard007/C++/0094433_Timer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d26fe2f378e935757bdb6e1afcdb631aca32993 --- /dev/null +++ b/pool/shard007/C++/0094433_Timer.cpp @@ -0,0 +1,114 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// +// http://www.opensource.org/licenses/mit-license.php +// +//////////////////////////////////////////////////////////////////////////////// + +#include <cmake.h> +#include <iostream> +#include <iomanip> +#include <sstream> +#include <Timer.h> +#include <Context.h> + +extern Context context; + +//////////////////////////////////////////////////////////////////////////////// +// Timer starts when the object is constructed. +Timer::Timer () +: _description ("-") +, _running (false) +, _total (0) +{ +} + +//////////////////////////////////////////////////////////////////////////////// +// Timer starts when the object is constructed with a description. +Timer::Timer (const std::string& description) +: _description (description) +, _running (false) +, _total (0) +{ + start (); +} + +//////////////////////////////////////////////////////////////////////////////// +// Timer stops when the object is destructed. +Timer::~Timer () +{ + stop (); + + std::stringstream s; + s << "Timer " // No i18n + << _description + << " " + << std::setprecision (6) +#ifndef HAIKU + // Haiku fails on this - don't know why. + << std::fixed +#endif + << _total / 1000000.0 + << " sec"; + + context.debug (s.str ()); +} + +//////////////////////////////////////////////////////////////////////////////// +void Timer::start () +{ + if (!_running) + { + gettimeofday (&_start, NULL); + _running = true; + } +} + +//////////////////////////////////////////////////////////////////////////////// +void Timer::stop () +{ + if (_running) + { + struct timeval end; + gettimeofday (&end, NULL); + _running = false; + _total += (end.tv_sec - _start.tv_sec) * 1000000 + + (end.tv_usec - _start.tv_usec); + } +} + +//////////////////////////////////////////////////////////////////////////////// +unsigned long Timer::total () const +{ + return _total; +} + +//////////////////////////////////////////////////////////////////////////////// +void Timer::subtract (unsigned long value) +{ + if (value > _total) + _total = 0; + else + _total -= value; +} + +//////////////////////////////////////////////////////////////////////////////// diff --git a/pool/shard007/C++/0094436_media_item_ui_legacy_cast_footer_view.cc b/pool/shard007/C++/0094436_media_item_ui_legacy_cast_footer_view.cc new file mode 100644 index 0000000000000000000000000000000000000000..7e159dcba8a93e6b60897e8693d57bbda3fb41aa --- /dev/null +++ b/pool/shard007/C++/0094436_media_item_ui_legacy_cast_footer_view.cc @@ -0,0 +1,97 @@ +// Copyright 2021 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 "chrome/browser/ui/views/global_media_controls/media_item_ui_legacy_cast_footer_view.h" + +#include "chrome/app/vector_icons/vector_icons.h" +#include "chrome/browser/feature_engagement/tracker_factory.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/global_media_controls/cast_media_notification_item.h" +#include "chrome/browser/ui/global_media_controls/media_notification_service.h" +#include "chrome/grit/generated_resources.h" +#include "components/feature_engagement/public/tracker.h" +#include "components/global_media_controls/public/media_item_manager.h" +#include "components/media_message_center/media_notification_item.h" +#include "components/media_router/browser/media_router.h" +#include "components/media_router/browser/media_router_factory.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/gfx/paint_vector_icon.h" +#include "ui/views/animation/ink_drop.h" +#include "ui/views/background.h" +#include "ui/views/border.h" +#include "ui/views/controls/button/label_button.h" +#include "ui/views/controls/highlight_path_generator.h" +#include "ui/views/layout/box_layout.h" + +namespace { + +constexpr gfx::Insets kInsets{6, 15}; +constexpr gfx::Size kSize{400, 30}; +constexpr gfx::Insets kBorderInsets{4, 8}; + +} // anonymous namespace + +MediaItemUILegacyCastFooterView::MediaItemUILegacyCastFooterView( + base::RepeatingClosure stop_casting_callback) + : stop_casting_callback_(stop_casting_callback) { + DCHECK(!stop_casting_callback_.is_null()); + + auto* layout = SetLayoutManager(std::make_unique<views::BoxLayout>( + views::BoxLayout::Orientation::kHorizontal, kInsets)); + layout->set_main_axis_alignment(views::BoxLayout::MainAxisAlignment::kStart); + layout->set_cross_axis_alignment( + views::BoxLayout::CrossAxisAlignment::kCenter); + SetPreferredSize(kSize); + + stop_cast_button_ = AddChildView(std::make_unique<views::LabelButton>( + base::BindRepeating(&MediaItemUILegacyCastFooterView::StopCasting, + base::Unretained(this)), + l10n_util::GetStringUTF16( + IDS_GLOBAL_MEDIA_CONTROLS_STOP_CASTING_BUTTON_LABEL))); + views::InstallRoundRectHighlightPathGenerator( + stop_cast_button_, gfx::Insets(), kSize.height() / 2); + + views::InkDrop::Get(stop_cast_button_) + ->SetMode(views::InkDropHost::InkDropMode::ON); + stop_cast_button_->SetFocusBehavior(FocusBehavior::ALWAYS); + stop_cast_button_->SetBorder(views::CreatePaddedBorder( + views::CreateRoundedRectBorder(1, kSize.height() / 2, foreground_color_), + kBorderInsets)); + UpdateColors(); +} + +MediaItemUILegacyCastFooterView::~MediaItemUILegacyCastFooterView() = default; + +views::Button* +MediaItemUILegacyCastFooterView::GetStopCastingButtonForTesting() { + return stop_cast_button_; +} + +void MediaItemUILegacyCastFooterView::OnColorsChanged(SkColor foreground, + SkColor background) { + if (foreground == foreground_color_ && background == background_color_) + return; + + foreground_color_ = foreground; + background_color_ = background; + + UpdateColors(); +} + +void MediaItemUILegacyCastFooterView::StopCasting() { + stop_cast_button_->SetEnabled(false); + stop_casting_callback_.Run(); +} + +void MediaItemUILegacyCastFooterView::UpdateColors() { + // Update background. + SetBackground(views::CreateSolidBackground(background_color_)); + + // Update button icon. + stop_cast_button_->SetEnabledTextColors(foreground_color_); + views::InkDrop::Get(stop_cast_button_)->SetBaseColor(foreground_color_); + stop_cast_button_->SetBorder(views::CreatePaddedBorder( + views::CreateRoundedRectBorder(1, kSize.height() / 2, foreground_color_), + kBorderInsets)); +} diff --git a/pool/shard007/C++/0094438_formal_parameter_list_node.cpp b/pool/shard007/C++/0094438_formal_parameter_list_node.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4f0e78a626de4780c675a08146cd1de55f913fac --- /dev/null +++ b/pool/shard007/C++/0094438_formal_parameter_list_node.cpp @@ -0,0 +1,83 @@ +/************************************************************************************************************************/ +/** A Compiler for a subset of Oberon **/ +/** authors: **/ +/** ROCHA, Rodrigo Caetano de Oliveira (rcor) **/ +/** FERREIRA, Wallace Dias **/ +/************************************************************************************************************************/ + +#include "formal_parameter_list_node.h" + +FormalParameterListNode::FormalParameterListNode() + : DeclarationNode(NODE_TYPE_FORMAL_PARAMETER_LIST) +{ + +} + +FormalParameterListNode::~FormalParameterListNode() +{ + +} + +void FormalParameterListNode::addFormalParameterSequence(DeclarationSequenceNode *formalParameterSequence, + DataType type) +{ + if(formalParameterSequence->getNextDeclaration() != NULL) + { + this->addFormalParameterSequence((DeclarationSequenceNode*)formalParameterSequence->getNextDeclaration(), type); + } + + FormalParameterNode *formalParameter = (FormalParameterNode*)formalParameterSequence->getFirstDeclaration(); + formalParameter->setType(type); + + this->formalParameterList_.push_back(formalParameter); + formalParameter->getIdentifierInformation()->setOffset(this->formalParameterList_.size()); +} + +void FormalParameterListNode::typeCheck(SemanticDebugger *semanticDebugger) +{ + list<FormalParameterNode*>::iterator it = this->formalParameterList_.begin(); + + while(it != this->formalParameterList_.end()) + { + (*it)->typeCheck(semanticDebugger); + it++; + } +} + +void FormalParameterListNode::debug(ASTDebugger *astDebugger, int nodeLevel) +{ + astDebugger->openParentNode("Formal Parameter List", nodeLevel); + + if(this->formalParameterList_.size() == 0) + { + astDebugger->insertLeafNode("{Empty Formal Parameter List}", nodeLevel + 1); + } + else + { + list<FormalParameterNode *>::iterator it = this->formalParameterList_.begin(); + + while(it != this->formalParameterList_.end()) + { + (*it)->debug(astDebugger, nodeLevel + 1); + it++; + } + } + + astDebugger->closeParentNode("Formal Parameter List", nodeLevel); +} + + +void FormalParameterListNode::generateCCode(ostream &out) +{ + int count = this->formalParameterList_.size(); + + out << "("; + for(list<FormalParameterNode*>::iterator it = this->formalParameterList_.begin(); it != this->formalParameterList_.end(); it++) + { + (*it)->generateCCode(out); + if(--count) + out << ", "; + } + out << ")" << endl << "{" << endl; +} + diff --git a/pool/shard007/C++/0094447_runtime-profiler.cc b/pool/shard007/C++/0094447_runtime-profiler.cc new file mode 100644 index 0000000000000000000000000000000000000000..2d4ee9c1a888254206aa602ffce735ea4468804c --- /dev/null +++ b/pool/shard007/C++/0094447_runtime-profiler.cc @@ -0,0 +1,266 @@ +// Copyright 2012 the V8 project 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 "src/runtime-profiler.h" + +#include "src/assembler.h" +#include "src/ast/scopeinfo.h" +#include "src/base/platform/platform.h" +#include "src/bootstrapper.h" +#include "src/code-stubs.h" +#include "src/compilation-cache.h" +#include "src/execution.h" +#include "src/frames-inl.h" +#include "src/full-codegen/full-codegen.h" +#include "src/global-handles.h" + +namespace v8 { +namespace internal { + + +// Number of times a function has to be seen on the stack before it is +// optimized. +static const int kProfilerTicksBeforeOptimization = 2; +// If the function optimization was disabled due to high deoptimization count, +// but the function is hot and has been seen on the stack this number of times, +// then we try to reenable optimization for this function. +static const int kProfilerTicksBeforeReenablingOptimization = 250; +// If a function does not have enough type info (according to +// FLAG_type_info_threshold), but has seen a huge number of ticks, +// optimize it as it is. +static const int kTicksWhenNotEnoughTypeInfo = 100; +// We only have one byte to store the number of ticks. +STATIC_ASSERT(kProfilerTicksBeforeOptimization < 256); +STATIC_ASSERT(kProfilerTicksBeforeReenablingOptimization < 256); +STATIC_ASSERT(kTicksWhenNotEnoughTypeInfo < 256); + +// Maximum size in bytes of generate code for a function to allow OSR. +static const int kOSRCodeSizeAllowanceBase = + 100 * FullCodeGenerator::kCodeSizeMultiplier; + +static const int kOSRCodeSizeAllowancePerTick = + 4 * FullCodeGenerator::kCodeSizeMultiplier; + +// Maximum size in bytes of generated code for a function to be optimized +// the very first time it is seen on the stack. +static const int kMaxSizeEarlyOpt = + 5 * FullCodeGenerator::kCodeSizeMultiplier; + + +RuntimeProfiler::RuntimeProfiler(Isolate* isolate) + : isolate_(isolate), + any_ic_changed_(false) { +} + + +static void GetICCounts(SharedFunctionInfo* shared, + int* ic_with_type_info_count, int* ic_generic_count, + int* ic_total_count, int* type_info_percentage, + int* generic_percentage) { + Code* shared_code = shared->code(); + *ic_total_count = 0; + *ic_generic_count = 0; + *ic_with_type_info_count = 0; + Object* raw_info = shared_code->type_feedback_info(); + if (raw_info->IsTypeFeedbackInfo()) { + TypeFeedbackInfo* info = TypeFeedbackInfo::cast(raw_info); + *ic_with_type_info_count = info->ic_with_type_info_count(); + *ic_generic_count = info->ic_generic_count(); + *ic_total_count = info->ic_total_count(); + } + + // Harvest vector-ics as well + TypeFeedbackVector* vector = shared->feedback_vector(); + int with = 0, gen = 0; + vector->ComputeCounts(&with, &gen); + *ic_with_type_info_count += with; + *ic_generic_count += gen; + + if (*ic_total_count > 0) { + *type_info_percentage = 100 * *ic_with_type_info_count / *ic_total_count; + *generic_percentage = 100 * *ic_generic_count / *ic_total_count; + } else { + *type_info_percentage = 100; // Compared against lower bound. + *generic_percentage = 0; // Compared against upper bound. + } +} + + +void RuntimeProfiler::Optimize(JSFunction* function, const char* reason) { + if (FLAG_trace_opt && function->PassesFilter(FLAG_hydrogen_filter)) { + PrintF("[marking "); + function->ShortPrint(); + PrintF(" for recompilation, reason: %s", reason); + if (FLAG_type_info_threshold > 0) { + int typeinfo, generic, total, type_percentage, generic_percentage; + GetICCounts(function->shared(), &typeinfo, &generic, &total, + &type_percentage, &generic_percentage); + PrintF(", ICs with typeinfo: %d/%d (%d%%)", typeinfo, total, + type_percentage); + PrintF(", generic ICs: %d/%d (%d%%)", generic, total, generic_percentage); + } + PrintF("]\n"); + } + + function->AttemptConcurrentOptimization(); +} + + +void RuntimeProfiler::AttemptOnStackReplacement(JSFunction* function, + int loop_nesting_levels) { + SharedFunctionInfo* shared = function->shared(); + if (!FLAG_use_osr || function->shared()->IsBuiltin()) { + return; + } + + // If the code is not optimizable, don't try OSR. + if (shared->optimization_disabled()) return; + + // We are not prepared to do OSR for a function that already has an + // allocated arguments object. The optimized code would bypass it for + // arguments accesses, which is unsound. Don't try OSR. + if (shared->uses_arguments()) return; + + // We're using on-stack replacement: patch the unoptimized code so that + // any back edge in any unoptimized frame will trigger on-stack + // replacement for that frame. + if (FLAG_trace_osr) { + PrintF("[OSR - patching back edges in "); + function->PrintName(); + PrintF("]\n"); + } + + for (int i = 0; i < loop_nesting_levels; i++) { + BackEdgeTable::Patch(isolate_, shared->code()); + } +} + + +void RuntimeProfiler::OptimizeNow() { + HandleScope scope(isolate_); + + if (!isolate_->use_crankshaft()) return; + + DisallowHeapAllocation no_gc; + + // Run through the JavaScript frames and collect them. If we already + // have a sample of the function, we mark it for optimizations + // (eagerly or lazily). + int frame_count = 0; + int frame_count_limit = FLAG_frame_count; + for (JavaScriptFrameIterator it(isolate_); + frame_count++ < frame_count_limit && !it.done(); + it.Advance()) { + JavaScriptFrame* frame = it.frame(); + JSFunction* function = frame->function(); + + SharedFunctionInfo* shared = function->shared(); + Code* shared_code = shared->code(); + + List<JSFunction*> functions(4); + frame->GetFunctions(&functions); + for (int i = functions.length(); --i >= 0; ) { + SharedFunctionInfo* shared_function_info = functions[i]->shared(); + int ticks = shared_function_info->profiler_ticks(); + if (ticks < Smi::kMaxValue) { + shared_function_info->set_profiler_ticks(ticks + 1); + } + } + + if (shared_code->kind() != Code::FUNCTION) continue; + if (function->IsInOptimizationQueue()) continue; + + if (FLAG_always_osr) { + AttemptOnStackReplacement(function, Code::kMaxLoopNestingMarker); + // Fall through and do a normal optimized compile as well. + } else if (!frame->is_optimized() && + (function->IsMarkedForOptimization() || + function->IsMarkedForConcurrentOptimization() || + function->IsOptimized())) { + // Attempt OSR if we are still running unoptimized code even though the + // the function has long been marked or even already been optimized. + int ticks = shared_code->profiler_ticks(); + int64_t allowance = + kOSRCodeSizeAllowanceBase + + static_cast<int64_t>(ticks) * kOSRCodeSizeAllowancePerTick; + if (shared_code->CodeSize() > allowance && + ticks < Code::ProfilerTicksField::kMax) { + shared_code->set_profiler_ticks(ticks + 1); + } else { + AttemptOnStackReplacement(function); + } + continue; + } + + // Only record top-level code on top of the execution stack and + // avoid optimizing excessively large scripts since top-level code + // will be executed only once. + const int kMaxToplevelSourceSize = 10 * 1024; + if (shared->is_toplevel() && + (frame_count > 1 || shared->SourceSize() > kMaxToplevelSourceSize)) { + continue; + } + + // Do not record non-optimizable functions. + if (shared->optimization_disabled()) { + if (shared->deopt_count() >= FLAG_max_opt_count) { + // If optimization was disabled due to many deoptimizations, + // then check if the function is hot and try to reenable optimization. + int ticks = shared_code->profiler_ticks(); + if (ticks >= kProfilerTicksBeforeReenablingOptimization) { + shared_code->set_profiler_ticks(0); + shared->TryReenableOptimization(); + } else { + shared_code->set_profiler_ticks(ticks + 1); + } + } + continue; + } + if (function->IsOptimized()) continue; + + int ticks = shared_code->profiler_ticks(); + + if (ticks >= kProfilerTicksBeforeOptimization) { + int typeinfo, generic, total, type_percentage, generic_percentage; + GetICCounts(shared, &typeinfo, &generic, &total, &type_percentage, + &generic_percentage); + if (type_percentage >= FLAG_type_info_threshold && + generic_percentage <= FLAG_generic_ic_threshold) { + // If this particular function hasn't had any ICs patched for enough + // ticks, optimize it now. + Optimize(function, "hot and stable"); + } else if (ticks >= kTicksWhenNotEnoughTypeInfo) { + Optimize(function, "not much type info but very hot"); + } else { + shared_code->set_profiler_ticks(ticks + 1); + if (FLAG_trace_opt_verbose) { + PrintF("[not yet optimizing "); + function->PrintName(); + PrintF(", not enough type info: %d/%d (%d%%)]\n", typeinfo, total, + type_percentage); + } + } + } else if (!any_ic_changed_ && + shared_code->instruction_size() < kMaxSizeEarlyOpt) { + // If no IC was patched since the last tick and this function is very + // small, optimistically optimize it now. + int typeinfo, generic, total, type_percentage, generic_percentage; + GetICCounts(shared, &typeinfo, &generic, &total, &type_percentage, + &generic_percentage); + if (type_percentage >= FLAG_type_info_threshold && + generic_percentage <= FLAG_generic_ic_threshold) { + Optimize(function, "small function"); + } else { + shared_code->set_profiler_ticks(ticks + 1); + } + } else { + shared_code->set_profiler_ticks(ticks + 1); + } + } + any_ic_changed_ = false; +} + + +} // namespace internal +} // namespace v8 diff --git a/pool/shard007/C++/0094452_pbsdialog.cpp b/pool/shard007/C++/0094452_pbsdialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c45d58cdcf6375e9a39928a80857b980f8063fad --- /dev/null +++ b/pool/shard007/C++/0094452_pbsdialog.cpp @@ -0,0 +1,116 @@ +/********************************************************************** + PbsConfigDialog -- Setup for remote PBS queues + + Copyright (C) 2011 by David Lonie + + This library is free software; you can redistribute it and/or modify + it under the terms of the GNU Library General Public License as + published by the Free Software Foundation; either version 2.1 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + ***********************************************************************/ + +#ifdef ENABLE_SSH + +// Doxygen skip: +/// @cond + +#include <globalsearch/queueinterfaces/pbsdialog.h> + +#include <globalsearch/queueinterfaces/pbs.h> + +#include <globalsearch/ui/abstractdialog.h> +#include <globalsearch/optbase.h> + +#include "ui_pbsdialog.h" + +namespace GlobalSearch { + + PbsConfigDialog::PbsConfigDialog(AbstractDialog *parent, + OptBase *o, + PbsQueueInterface *p) + : QDialog(parent), + ui(new Ui::PbsConfigDialog), + m_opt(o), + m_pbs(p) + { + ui->setupUi(this); + } + + PbsConfigDialog::~PbsConfigDialog() + { + delete ui; + } + + void PbsConfigDialog::updateGUI() + { + ui->edit_description->blockSignals(true); + ui->edit_host->blockSignals(true); + ui->edit_qdel->blockSignals(true); + ui->edit_qstat->blockSignals(true); + ui->edit_qsub->blockSignals(true); + ui->edit_rempath->blockSignals(true); + ui->edit_locpath->blockSignals(true); + ui->edit_username->blockSignals(true); + ui->spin_port->blockSignals(true); + ui->spin_interval->blockSignals(true); + ui->cb_cleanRemoteOnStop->blockSignals(true); + + ui->edit_description->setText(m_opt->description); + ui->edit_host->setText(m_opt->host); + ui->edit_qdel->setText(m_pbs->m_qdel); + ui->edit_qstat->setText(m_pbs->m_qstat); + ui->edit_qsub->setText(m_pbs->m_qsub); + ui->edit_rempath->setText(m_opt->rempath); + ui->edit_locpath->setText(m_opt->filePath); + ui->edit_username->setText(m_opt->username); + ui->spin_port->setValue(m_opt->port); + ui->spin_interval->setValue(m_pbs->m_interval); + ui->cb_cleanRemoteOnStop->setChecked(m_pbs->m_cleanRemoteOnStop); + + ui->edit_description->blockSignals(false); + ui->edit_host->blockSignals(false); + ui->edit_qdel->blockSignals(false); + ui->edit_qstat->blockSignals(false); + ui->edit_qsub->blockSignals(false); + ui->edit_rempath->blockSignals(false); + ui->edit_locpath->blockSignals(false); + ui->edit_username->blockSignals(false); + ui->spin_port->blockSignals(false); + ui->spin_interval->blockSignals(false); + ui->cb_cleanRemoteOnStop->blockSignals(false); + } + + void PbsConfigDialog::accept() + { + m_opt->description = ui->edit_description->text().trimmed(); + m_opt->host = ui->edit_host->text().trimmed(); + m_pbs->m_qdel = ui->edit_qdel->text().trimmed(); + m_pbs->m_qstat = ui->edit_qstat->text().trimmed(); + m_pbs->m_qsub = ui->edit_qsub->text().trimmed(); + m_opt->rempath = ui->edit_rempath->text().trimmed(); + m_opt->filePath = ui->edit_locpath->text().trimmed(); + m_opt->username = ui->edit_username->text().trimmed(); + m_opt->port = ui->spin_port->value(); + // Use setter for interval -- mutex must be locked. + m_pbs->setInterval(ui->spin_interval->value()); + m_pbs->m_cleanRemoteOnStop = ui->cb_cleanRemoteOnStop->isChecked(); + QDialog::accepted(); + close(); + } + + void PbsConfigDialog::reject() + { + updateGUI(); + QDialog::reject(); + close(); + } + +} + +/// @endcond +#endif // ENABLE_SSH diff --git a/pool/shard007/C++/0094459_Two_Sum.cpp b/pool/shard007/C++/0094459_Two_Sum.cpp new file mode 100644 index 0000000000000000000000000000000000000000..29e020b05fac7ada6c1cd4ba4ac6c05fd13c2ffd --- /dev/null +++ b/pool/shard007/C++/0094459_Two_Sum.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector<int> twoSum(vector<int> &numbers, int target) { + unordered_map<int, int> m; + vector<int> result; + for (int i = 0;i < numbers.size();i++) { + int remain = target - numbers[i]; + if (m.count(remain) > 0) { + result.push_back(m[remain]); + result.push_back(i); + return result; + } + m[numbers[i]] = i; + } + return result; + } +}; diff --git a/pool/shard007/C++/0094468_chase.cpp b/pool/shard007/C++/0094468_chase.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3a415010b382a3f48f5947f1e7fa96d55358c4fa --- /dev/null +++ b/pool/shard007/C++/0094468_chase.cpp @@ -0,0 +1,239 @@ +/// @file chase.cpp +/// @brief Contais the implementation of the chase class. +/// @author Enrico Fraccaroli +/// @date Nov 11 2016 +/// @copyright +/// Copyright (c) 2016 Enrico Fraccaroli <enrico.fraccaroli@gmail.com> +/// Permission is hereby granted, free of charge, to any person obtaining a +/// copy of this software and associated documentation files (the "Software"), +/// to deal in the Software without restriction, including without limitation +/// the rights to use, copy, modify, merge, publish, distribute, sublicense, +/// and/or sell copies of the Software, and to permit persons to whom the +/// Software is furnished to do so, subject to the following conditions: +/// The above copyright notice and this permission notice shall be included +/// in all copies or substantial portions of the Software. +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. + +#include "chase.hpp" + +#include "structureUtils.hpp" +#include "characterUtilities.hpp" +#include "effectFactory.hpp" +#include "moveAction.hpp" +#include "logger.hpp" +#include "aStar.hpp" +#include "area.hpp" +#include "room.hpp" +#include <queue> +#include <cassert> + +Chase::Chase(Character * _actor, Character * _target) : + CombatAction(_actor), + target(_target), + lastRoom(_target->room), + RoomCheckFunction() +{ + // Debugging message. + Logger::log(LogLevel::Debug, "Created Chase."); + // Reset the cooldown of the action. + this->resetCooldown(this->getCooldown()); +} + +Chase::~Chase() +{ + Logger::log(LogLevel::Debug, "Deleted Chase."); +} + +bool Chase::check(std::string & error) const +{ + if (!CombatAction::check(error)) + { + return false; + } + if (target == nullptr) + { + error = "You don't have a valid target."; + return false; + } + if (target->room == nullptr) + { + error = "Your target is not in a valid room."; + return false; + } + return true; +} + +ActionType Chase::getType() const +{ + return ActionType::Combat; +} + +std::string Chase::getDescription() const +{ + return "Chasing"; +} + +std::string Chase::stop() +{ + return "You stop chasing your target."; +} + +ActionStatus Chase::perform() +{ + // Check the values of the action. + std::string error; + if (!this->check(error)) + { + actor->sendMsg(error + "\n\n"); + return ActionStatus::Error; + } + if (actor->room->vnum == target->room->vnum) + { + return ActionStatus::Finished; + } + // Check if the actor has enough stamina to execute the action. + auto consumedStamina = Chase::getConsumedStamina(actor); + if (consumedStamina > actor->stamina) + { + actor->sendMsg("You are too tired to chase your target.\n\n"); + } + else + { + // If the path to the target is empty or the target has changed room. + if (path.empty() || (target->room->vnum != lastRoom->vnum)) + { + Logger::log(LogLevel::Debug, "Evaluating the path..."); + // Find the path from the actor to the target. + if (!this->updatePath()) + { + actor->sendMsg("There is no path to your target.\n\n"); + return ActionStatus::Error; + } + } + // Move towards the target. + if (this->moveTowardsTarget()) + { + // Consume the stamina. + actor->remStamina(consumedStamina, true); + } + else + { + actor->sendMsg("You are not able to chase your target.\n\n"); + return ActionStatus::Error; + } + } + // Reset the cooldown. + actor->getAction()->resetCooldown(); + // Return that the action is still running. + return ActionStatus::Running; +} + +unsigned int Chase::getCooldown() +{ + assert(actor && "Actor is nullptr"); + // BASE [+4.0] + // STRENGTH [-0.0 to -1.40] + // AGILITY [-0.0 to -1.40] + // WEIGHT [+1.6 to +2.51] + // CARRIED [+0.0 to +2.48] + // WEAPON [+0.0 to +1.60] + unsigned int cooldown = 4; + cooldown = SafeSum(cooldown, -actor->getAbilityLog(Ability::Strength)); + cooldown = SafeSum(cooldown, -actor->getAbilityLog(Ability::Agility)); + cooldown = SafeSum(cooldown, SafeLog10(actor->weight)); + cooldown = SafeSum(cooldown, SafeLog10(actor->getCarryingWeight())); + return cooldown; +} + +CombatActionType Chase::getCombatActionType() const +{ + return CombatActionType::Chase; +} + +unsigned int Chase::getConsumedStamina(Character * character) +{ + auto multiplier = 1.0; + if (character->posture == CharacterPosture::Crouch) + { + multiplier = 0.75; + } + else if (character->posture == CharacterPosture::Prone) + { + multiplier = 0.50; + } + // BASE [+1.0] + // STRENGTH [-0.0 to -1.40] + // WEIGHT [+1.6 to +2.51] + // CARRIED [+0.0 to +2.48] + unsigned int consumedStamina = 1; + consumedStamina -= character->getAbilityLog(Ability::Strength); + consumedStamina = SafeSum(consumedStamina, SafeLog10(character->weight)); + consumedStamina = SafeSum(consumedStamina, + SafeLog10(character->getCarryingWeight())); + return static_cast<unsigned int>(consumedStamina * multiplier); +} + +bool Chase::updatePath() +{ + // Set the check function. + if (RoomCheckFunction == nullptr) + { + RoomCheckFunction = [&](Room * from, Room * to) + { + // Prepare the movement options. + MovementOptions options; + options.character = actor; + // Prepare the error string. + std::string error; + return StructUtils::checkConnection(options, from, to, error); + }; + } + // Find the path from the actor to the target. + AStar<Room *> aStar(RoomCheckFunction, + StructUtils::getRoomDistance, + StructUtils::roomsAreEqual, + StructUtils::getNeighbours); + return aStar.findPath(actor->room, target->room, path); +} + +bool Chase::moveTowardsTarget() +{ + if (path.empty()) + { + Logger::log(LogLevel::Debug, "Path is empty."); + return false; + } + Room * nextRoom = path.front(); + if (nextRoom == nullptr) + { + Logger::log(LogLevel::Debug, "Next room is a nullptr."); + return false; + } + // Get the direction of the next room. + auto direction = + StructUtils::getDirection(actor->room->coord, nextRoom->coord); + // Move character. + if (!MoveCharacterTo( + actor, + nextRoom, + actor->getNameCapital() + " goes " + + direction.toString() + ".\n", + actor->getNameCapital() + " arrives from " + + direction.getOpposite().toString() + ".\n")) + { + Logger::log(LogLevel::Debug, "Cannot move to the next room."); + return false; + } + // Apply the disturbed aim effect. + actor->effectManager + .forceAddEffect(EffectFactory::disturbedAim(actor, 1, -3)); + // Pop the room. + path.erase(path.begin()); + return true; +} diff --git a/pool/shard007/C++/0094471_CustomAuthCredentials.cpp b/pool/shard007/C++/0094471_CustomAuthCredentials.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d743e36549a3bd60530d03ad856fd5f0ce6b30f0 --- /dev/null +++ b/pool/shard007/C++/0094471_CustomAuthCredentials.cpp @@ -0,0 +1,82 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include <aws/appflow/model/CustomAuthCredentials.h> +#include <aws/core/utils/json/JsonSerializer.h> + +#include <utility> + +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +namespace Aws +{ +namespace Appflow +{ +namespace Model +{ + +CustomAuthCredentials::CustomAuthCredentials() : + m_customAuthenticationTypeHasBeenSet(false), + m_credentialsMapHasBeenSet(false) +{ +} + +CustomAuthCredentials::CustomAuthCredentials(JsonView jsonValue) : + m_customAuthenticationTypeHasBeenSet(false), + m_credentialsMapHasBeenSet(false) +{ + *this = jsonValue; +} + +CustomAuthCredentials& CustomAuthCredentials::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("customAuthenticationType")) + { + m_customAuthenticationType = jsonValue.GetString("customAuthenticationType"); + + m_customAuthenticationTypeHasBeenSet = true; + } + + if(jsonValue.ValueExists("credentialsMap")) + { + Aws::Map<Aws::String, JsonView> credentialsMapJsonMap = jsonValue.GetObject("credentialsMap").GetAllObjects(); + for(auto& credentialsMapItem : credentialsMapJsonMap) + { + m_credentialsMap[credentialsMapItem.first] = credentialsMapItem.second.AsString(); + } + m_credentialsMapHasBeenSet = true; + } + + return *this; +} + +JsonValue CustomAuthCredentials::Jsonize() const +{ + JsonValue payload; + + if(m_customAuthenticationTypeHasBeenSet) + { + payload.WithString("customAuthenticationType", m_customAuthenticationType); + + } + + if(m_credentialsMapHasBeenSet) + { + JsonValue credentialsMapJsonMap; + for(auto& credentialsMapItem : m_credentialsMap) + { + credentialsMapJsonMap.WithString(credentialsMapItem.first, credentialsMapItem.second); + } + payload.WithObject("credentialsMap", std::move(credentialsMapJsonMap)); + + } + + return payload; +} + +} // namespace Model +} // namespace Appflow +} // namespace Aws diff --git a/pool/shard007/C++/0094476_TextEncoding.cpp b/pool/shard007/C++/0094476_TextEncoding.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6245c9c99bc64491c43c6d0bdc746441a0cbf0a2 --- /dev/null +++ b/pool/shard007/C++/0094476_TextEncoding.cpp @@ -0,0 +1,268 @@ +/* + * Copyright (C) 2004, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. + * Copyright (C) 2006 Alexey Proskuryakov <ap@nypop.com> + * Copyright (C) 2007-2009 Torch Mobile, Inc. + * + * 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. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" +#include "TextEncoding.h" + +#include "PlatformString.h" +#include "TextCodec.h" +#include "TextEncodingRegistry.h" +#if USE(ICU_UNICODE) +#include <unicode/unorm.h> +#elif USE(QT4_UNICODE) +#include <QString> +#elif USE(GLIB_UNICODE) +#include <glib.h> +#include "GOwnPtr.h" +#endif +#include <wtf/text/CString.h> +#include <wtf/OwnPtr.h> +#include <wtf/StdLibExtras.h> + +namespace WebCore { + +static const TextEncoding& UTF7Encoding() +{ + static TextEncoding globalUTF7Encoding("UTF-7"); + return globalUTF7Encoding; +} + +TextEncoding::TextEncoding(const char* name) + : m_name(atomicCanonicalTextEncodingName(name)) + , m_backslashAsCurrencySymbol(backslashAsCurrencySymbol()) +{ +} + +TextEncoding::TextEncoding(const String& name) + : m_name(atomicCanonicalTextEncodingName(name.characters(), name.length())) + , m_backslashAsCurrencySymbol(backslashAsCurrencySymbol()) +{ +} + +String TextEncoding::decode(const char* data, size_t length, bool stopOnError, bool& sawError) const +{ + if (!m_name) + return String(); + + return newTextCodec(*this)->decode(data, length, true, stopOnError, sawError); +} + +CString TextEncoding::encode(const UChar* characters, size_t length, UnencodableHandling handling) const +{ + if (!m_name) + return CString(); + + if (!length) + return ""; + +#if USE(ICU_UNICODE) + // FIXME: What's the right place to do normalization? + // It's a little strange to do it inside the encode function. + // Perhaps normalization should be an explicit step done before calling encode. + + const UChar* source = characters; + size_t sourceLength = length; + + Vector<UChar> normalizedCharacters; + + UErrorCode err = U_ZERO_ERROR; + __asm int 3; // weolar +// if (unorm_quickCheck(source, sourceLength, UNORM_NFC, &err) != UNORM_YES) { +// // First try using the length of the original string, since normalization to NFC rarely increases length. +// normalizedCharacters.grow(sourceLength); +// int32_t normalizedLength = 0; +// +// int32_t normalizedLength = unorm_normalize(source, length, UNORM_NFC, 0, normalizedCharacters.data(), length, &err); +// if (err == U_BUFFER_OVERFLOW_ERROR) { +// err = U_ZERO_ERROR; +// normalizedCharacters.resize(normalizedLength); +// normalizedLength = unorm_normalize(source, length, UNORM_NFC, 0, normalizedCharacters.data(), normalizedLength, &err); +// } +// ASSERT(U_SUCCESS(err)); +// +// source = normalizedCharacters.data(); +// sourceLength = normalizedLength; +// } + return newTextCodec(*this)->encode(source, sourceLength, handling); +#elif USE(QT4_UNICODE) + QString str(reinterpret_cast<const QChar*>(characters), length); + str = str.normalized(QString::NormalizationForm_C); + return newTextCodec(*this)->encode(reinterpret_cast<const UChar *>(str.utf16()), str.length(), handling); +#elif USE(GLIB_UNICODE) + GOwnPtr<char> UTF8Source; + UTF8Source.set(g_utf16_to_utf8(characters, length, 0, 0, 0)); + if (!UTF8Source) { + // If conversion to UTF-8 failed, try with the string without normalization + return newTextCodec(*this)->encode(characters, length, handling); + } + + GOwnPtr<char> UTF8Normalized; + UTF8Normalized.set(g_utf8_normalize(UTF8Source.get(), -1, G_NORMALIZE_NFC)); + + long UTF16Length; + GOwnPtr<UChar> UTF16Normalized; + UTF16Normalized.set(g_utf8_to_utf16(UTF8Normalized.get(), -1, 0, &UTF16Length, 0)); + + return newTextCodec(*this)->encode(UTF16Normalized.get(), UTF16Length, handling); +#elif OS(WINCE) + // normalization will be done by Windows CE API + OwnPtr<TextCodec> textCodec = newTextCodec(*this); + return textCodec.get() ? textCodec->encode(characters, length, handling) : CString(); +#elif USE(BREWMP_UNICODE) + // FIXME: not sure if Brew MP normalizes the input string automatically + OwnPtr<TextCodec> textCodec = newTextCodec(*this); + return textCodec.get() ? textCodec->encode(characters, length, handling) : CString(); +#endif +} + +const char* TextEncoding::domName() const +{ + if (noExtendedTextEncodingNameUsed()) + return m_name; + + // We treat EUC-KR as windows-949 (its superset), but need to expose + // the name 'EUC-KR' because the name 'windows-949' is not recognized by + // most Korean web servers even though they do use the encoding + // 'windows-949' with the name 'EUC-KR'. + // FIXME: This is not thread-safe. At the moment, this function is + // only accessed in a single thread, but eventually has to be made + // thread-safe along with usesVisualOrdering(). + static const char* const a = atomicCanonicalTextEncodingName("windows-949"); + if (m_name == a) + return "EUC-KR"; + return m_name; +} + +bool TextEncoding::usesVisualOrdering() const +{ + if (noExtendedTextEncodingNameUsed()) + return false; + + static const char* const a = atomicCanonicalTextEncodingName("ISO-8859-8"); + return m_name == a; +} + +bool TextEncoding::isJapanese() const +{ + return isJapaneseEncoding(m_name); +} + +UChar TextEncoding::backslashAsCurrencySymbol() const +{ + return shouldShowBackslashAsCurrencySymbolIn(m_name) ? 0x00A5 : '\\'; +} + +bool TextEncoding::isNonByteBasedEncoding() const +{ + if (noExtendedTextEncodingNameUsed()) { + return *this == UTF16LittleEndianEncoding() + || *this == UTF16BigEndianEncoding(); + } + + return *this == UTF16LittleEndianEncoding() + || *this == UTF16BigEndianEncoding() + || *this == UTF32BigEndianEncoding() + || *this == UTF32LittleEndianEncoding(); +} + +bool TextEncoding::isUTF7Encoding() const +{ + if (noExtendedTextEncodingNameUsed()) + return false; + + return *this == UTF7Encoding(); +} + +const TextEncoding& TextEncoding::closestByteBasedEquivalent() const +{ + if (isNonByteBasedEncoding()) + return UTF8Encoding(); + return *this; +} + +// HTML5 specifies that UTF-8 be used in form submission when a form is +// is a part of a document in UTF-16 probably because UTF-16 is not a +// byte-based encoding and can contain 0x00. By extension, the same +// should be done for UTF-32. In case of UTF-7, it is a byte-based encoding, +// but it's fraught with problems and we'd rather steer clear of it. +const TextEncoding& TextEncoding::encodingForFormSubmission() const +{ + if (isNonByteBasedEncoding() || isUTF7Encoding()) + return UTF8Encoding(); + return *this; +} + +const TextEncoding& ASCIIEncoding() +{ + static TextEncoding globalASCIIEncoding("ASCII"); + return globalASCIIEncoding; +} + +const TextEncoding& Latin1Encoding() +{ + static TextEncoding globalLatin1Encoding("latin1"); + return globalLatin1Encoding; +} + +const TextEncoding& UTF16BigEndianEncoding() +{ + static TextEncoding globalUTF16BigEndianEncoding("UTF-16BE"); + return globalUTF16BigEndianEncoding; +} + +const TextEncoding& UTF16LittleEndianEncoding() +{ + static TextEncoding globalUTF16LittleEndianEncoding("UTF-16LE"); + return globalUTF16LittleEndianEncoding; +} + +const TextEncoding& UTF32BigEndianEncoding() +{ + static TextEncoding globalUTF32BigEndianEncoding("UTF-32BE"); + return globalUTF32BigEndianEncoding; +} + +const TextEncoding& UTF32LittleEndianEncoding() +{ + static TextEncoding globalUTF32LittleEndianEncoding("UTF-32LE"); + return globalUTF32LittleEndianEncoding; +} + +const TextEncoding& UTF8Encoding() +{ + static TextEncoding globalUTF8Encoding("UTF-8"); + ASSERT(globalUTF8Encoding.isValid()); + return globalUTF8Encoding; +} + +const TextEncoding& WindowsLatin1Encoding() +{ + static TextEncoding globalWindowsLatin1Encoding("WinLatin-1"); + return globalWindowsLatin1Encoding; +} + +} // namespace WebCore diff --git a/pool/shard007/C++/0094480_SubdetectorExtensionPlugin.cpp b/pool/shard007/C++/0094480_SubdetectorExtensionPlugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3348ec299a36d772bf6e6f232f100ad6615b64ce --- /dev/null +++ b/pool/shard007/C++/0094480_SubdetectorExtensionPlugin.cpp @@ -0,0 +1,30 @@ +// $Id: $ +//========================================================================== +// AIDA Detector description implementation for LCD +//-------------------------------------------------------------------------- +// Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN) +// All rights reserved. +// +// For the licensing terms see $DD4hepINSTALL/LICENSE. +// For the list of contributors see $DD4hepINSTALL/doc/CREDITS. +// +// Author : M.Frank +// +//========================================================================== +// +// Specialized generic detector plugin +// +//========================================================================== +// Framework include files +#include "DDRec/Extensions/SubdetectorExtensionImpl.h" +#define DD4HEP_USE_SURFACEINSTALL_HELPER SubdetectorExtensionPlugin +#include "DD4hep/SurfaceInstaller.h" + +/// Install volume information. Default implementation only prints! +template <typename T> void Installer<T>::install(DetElement /* layer */, PlacedVolume /* pv */) { + using namespace DD4hep::DDRec; + SubdetectorExtensionImpl* e = new SubdetectorExtensionImpl(m_det); + m_det.addExtension<SubdetectorExtension>(e); + stopScanning(); + std::cout << " Installed subdetector extension:" << m_det.name() << " id: " << m_det.id() << std::endl; +} diff --git a/pool/shard007/C++/0094482_row.cpp b/pool/shard007/C++/0094482_row.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d4d038f4295ce27baeb5c4461915bfa6636d889 --- /dev/null +++ b/pool/shard007/C++/0094482_row.cpp @@ -0,0 +1,101 @@ +/// PROJECT +#include <csapex/model/node.h> +#include <csapex/model/node_modifier.h> +#include <csapex/msg/io.h> +#include <csapex/param/parameter_factory.h> +#include <csapex/param/range_parameter.h> +#include <csapex/utility/register_apex_plugin.h> +#include <csapex_point_cloud/msg/point_cloud_message.h> + +namespace csapex +{ +using namespace connection_types; + +class StructuredRow : public Node +{ +public: + StructuredRow() + { + } + + virtual void setup(csapex::NodeModifier& node_modifier) override + { + input_cloud_ = node_modifier.addInput<PointCloudMessage>("PointCloud"); + output_cloud_ = node_modifier.addOutput<PointCloudMessage>("Row"); + output_cloud_complement_ = node_modifier.addOutput<PointCloudMessage>("Complement"); + } + + void setupParameters(Parameterizable& parameters) override + { + param::Parameter::Ptr row_ptr = param::factory::declareRange("row", 0, 0, 0, 1); + row_ = std::dynamic_pointer_cast<param::RangeParameter>(row_ptr); + addParameter(row_); + } + + virtual void process() override + { + PointCloudMessage::ConstPtr msg(msg::getMessage<PointCloudMessage>(input_cloud_)); + boost::apply_visitor(PointCloudMessage::Dispatch<StructuredRow>(this, msg), msg->value); + } + + template <class PointT> + void inputCloud(typename pcl::PointCloud<PointT>::ConstPtr cloud) + { + if (!cloud->isOrganized()) + throw std::runtime_error("Clouds have to be organized!"); + + if (row_->max<int>() == 0 || static_cast<std::size_t>(row_->max<int>()) != cloud->height) { + row_->setMax<int>(cloud->height); + } + + std::size_t selected = static_cast<std::size_t>(row_->as<int>()); + if (msg::isConnected(output_cloud_)) { + typename pcl::PointCloud<PointT>::Ptr out(new pcl::PointCloud<PointT>); + out->header = cloud->header; + out->height = 1; + out->width = cloud->width; + + for (std::size_t i = 0; i < cloud->width; ++i) { + out->points.push_back(cloud->at(i, selected)); + } + + PointCloudMessage::Ptr msg(new PointCloudMessage(cloud->header.frame_id, cloud->header.stamp)); + msg->value = out; + msg::publish(output_cloud_, msg); + } + + if (msg::isConnected(output_cloud_complement_)) { + typename pcl::PointCloud<PointT>::Ptr out(new pcl::PointCloud<PointT>); + out->header = cloud->header; + out->height = cloud->height; + out->width = cloud->width; + + for (std::size_t i = 0; i < cloud->height; ++i) { + for (std::size_t j = 0; j < cloud->width; ++j) { + PointT p = cloud->at(j, i); + if (i != selected) { + out->push_back(p); + } else { + p.x = std::numeric_limits<float>::quiet_NaN(); + p.y = std::numeric_limits<float>::quiet_NaN(); + p.z = std::numeric_limits<float>::quiet_NaN(); + out->push_back(p); + } + } + } + + PointCloudMessage::Ptr msg(new PointCloudMessage(cloud->header.frame_id, cloud->header.stamp)); + msg->value = out; + msg::publish(output_cloud_complement_, msg); + } + } + +private: + Input* input_cloud_; + Output* output_cloud_; + Output* output_cloud_complement_; + + param::RangeParameter::Ptr row_; +}; +CSAPEX_REGISTER_CLASS(csapex::StructuredRow, csapex::Node) +} // namespace csapex diff --git a/pool/shard007/C++/0094489_child_process_host_unittest.cc b/pool/shard007/C++/0094489_child_process_host_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..8e8f16d899b9526d8355865c484cb3f1c34e9740 --- /dev/null +++ b/pool/shard007/C++/0094489_child_process_host_unittest.cc @@ -0,0 +1,62 @@ +// 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. + +// Note: This file also tests child_process.*. + +#include "mojo/shell/child_process_host.h" + +#include "base/logging.h" +#include "base/macros.h" +#include "base/message_loop/message_loop.h" +#include "mojo/common/message_pump_mojo.h" +#include "mojo/shell/context.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace mojo { +namespace shell { +namespace { + +// Subclass just so we can observe |DidStart()|. +class TestChildProcessHost : public ChildProcessHost { + public: + explicit TestChildProcessHost(Context* context) : ChildProcessHost(context) {} + ~TestChildProcessHost() override {} + + void DidStart(bool success) override { + EXPECT_TRUE(success); + ChildProcessHost::DidStart(success); + base::MessageLoop::current()->QuitWhenIdle(); + } + + private: + DISALLOW_COPY_AND_ASSIGN(TestChildProcessHost); +}; + +#if defined(OS_ANDROID) +// TODO(qsr): Multiprocess shell tests are not supported on android. +#define MAYBE_StartJoin DISABLED_StartJoin +#else +#define MAYBE_StartJoin StartJoin +#endif // defined(OS_ANDROID) +// Just tests starting the child process and joining it (without starting an +// app). +TEST(ChildProcessHostTest, MAYBE_StartJoin) { + Context context; + base::MessageLoop message_loop( + scoped_ptr<base::MessagePump>(new common::MessagePumpMojo())); + context.Init(); + TestChildProcessHost child_process_host(&context); + child_process_host.Start(); + message_loop.Run(); + child_process_host.ExitNow(123); + int exit_code = child_process_host.Join(); + VLOG(2) << "Joined child: exit_code = " << exit_code; + EXPECT_EQ(123, exit_code); + + context.Shutdown(); +} + +} // namespace +} // namespace shell +} // namespace mojo diff --git a/pool/shard007/C++/0094490_editaddressdialog.cpp b/pool/shard007/C++/0094490_editaddressdialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1a5ee7dcdbeb6d6e4483df2ce76b1d4acb25446 --- /dev/null +++ b/pool/shard007/C++/0094490_editaddressdialog.cpp @@ -0,0 +1,143 @@ +#include "editaddressdialog.h" +#include "ui_editaddressdialog.h" + +#include "addresstablemodel.h" +#include "guiutil.h" + +#include <QDataWidgetMapper> +#include <QMessageBox> + +EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : + QDialog(parent), + ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) +{ + ui->setupUi(this); + + GUIUtil::setupAddressWidget(ui->addressEdit, this); + + switch(mode) + { + case NewReceivingAddress: + setWindowTitle(tr("New receiving address")); + ui->addressEdit->setEnabled(false); + break; + case NewSendingAddress: + setWindowTitle(tr("New sending address")); + break; + case EditReceivingAddress: + setWindowTitle(tr("Edit receiving address")); + ui->addressEdit->setEnabled(false); + break; + case EditSendingAddress: + setWindowTitle(tr("Edit sending address")); + break; + } + + mapper = new QDataWidgetMapper(this); + mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); +} + +EditAddressDialog::~EditAddressDialog() +{ + delete ui; +} + +void EditAddressDialog::setModel(AddressTableModel *model) +{ + this->model = model; + if(!model) + return; + + mapper->setModel(model); + mapper->addMapping(ui->labelEdit, AddressTableModel::Label); + mapper->addMapping(ui->addressEdit, AddressTableModel::Address); +} + +void EditAddressDialog::loadRow(int row) +{ + mapper->setCurrentIndex(row); +} + +bool EditAddressDialog::saveCurrentRow() +{ + if(!model) + return false; + + switch(mode) + { + case NewReceivingAddress: + case NewSendingAddress: + address = model->addRow( + mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, + ui->labelEdit->text(), + ui->addressEdit->text()); + break; + case EditReceivingAddress: + case EditSendingAddress: + if(mapper->submit()) + { + address = ui->addressEdit->text(); + } + break; + } + return !address.isEmpty(); +} + +void EditAddressDialog::accept() +{ + if(!model) + return; + + if(!saveCurrentRow()) + { + switch(model->getEditStatus()) + { + case AddressTableModel::OK: + // Failed with unknown reason. Just reject. + break; + case AddressTableModel::NO_CHANGES: + // No changes were made during edit operation. Just reject. + break; + case AddressTableModel::INVALID_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is not a valid Whitecoin address.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::DUPLICATE_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::WALLET_UNLOCK_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("Could not unlock wallet."), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::KEY_GENERATION_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("New key generation failed."), + QMessageBox::Ok, QMessageBox::Ok); + break; + + } + return; + } + QDialog::accept(); +} + +QString EditAddressDialog::getAddress() const +{ + return address; +} + +void EditAddressDialog::setAddress(const QString &address) +{ + this->address = address; + ui->addressEdit->setText(address); +} + +void EditAddressDialog::setLabel(const QString &addrLabel) +{ + this->addrLabel = addrLabel; + ui->labelEdit->setText(addrLabel); +} \ No newline at end of file diff --git a/pool/shard007/C++/0094491_MatrixMath.cpp b/pool/shard007/C++/0094491_MatrixMath.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2459ff5592ff8e0c8883c46f71b8fd588d88d802 --- /dev/null +++ b/pool/shard007/C++/0094491_MatrixMath.cpp @@ -0,0 +1,77 @@ +//******************************************************************************************** +//* +//* This file is part of Egoboo. +//* +//* Egoboo is free software: you can redistribute it and/or modify it +//* under the terms of the GNU General Public License as published by +//* the Free Software Foundation, either version 3 of the License, or +//* (at your option) any later version. +//* +//* Egoboo is distributed in the hope that it will be useful, but +//* WITHOUT ANY WARRANTY; without even the implied warranty of +//* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +//* General Public License for more details. +//* +//* You should have received a copy of the GNU General Public License +//* along with Egoboo. If not, see <http://www.gnu.org/licenses/>. +//* +//******************************************************************************************** + +#include "egolib/Tests/Math/MathTestUtilities.hpp" + +namespace Ego { +namespace Math { +namespace Test { + +EgoTest_TestCase(MatrixMath) { + +EgoTest_Test(constructor) { + Matrix4f4f a + ( + 1, 2, 3, 4, + 5, 6, 7, 8, + 9, 10,11,12, + 13,14,15,16 + ); + for (int i = 0; i < 4; ++i) { + for (int j = 0; j < 4; ++j) { + EgoTest_Assert(a(i, j) == i*4+j+1); + } + } +} + +EgoTest_Test(add) { + Matrix4f4f a, b, c; + c = a + b; + EgoTest_Assert(c - b == a); + EgoTest_Assert(c - a == b); +} + +EgoTest_Test(sub) { + Matrix4f4f a, b, c; + c = a - b; + EgoTest_Assert(c + b == a); + EgoTest_Assert(b == a - c); +} + +EgoTest_Test(trace) { + Ego::Math::Matrix<float, 3, 3> m33; + m33.trace(); +} + +EgoTest_Test(muls) { + Matrix4f4f a, b; + float s; + do + { + s = Random::nextFloat(); + } while (s == 0.0f); + b = a * s; + EgoTest_Assert(b * (1.0f/s) == a); +} + +}; + +} // namespace Test +} // namespace Math +} // namespace Ego diff --git a/pool/shard007/C++/0094492_vm_test.cc b/pool/shard007/C++/0094492_vm_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..aed6260e07c1d842b5e7c293834afe1084010257 --- /dev/null +++ b/pool/shard007/C++/0094492_vm_test.cc @@ -0,0 +1,160 @@ +// Copyright (C) 2016 Google Inc. +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +//////////////////////////////////////////////////////////////////////////////// + +#include "deepmind/lua/vm.h" + +#include <vector> + +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "deepmind/lua/call.h" +#include "deepmind/lua/n_results_or.h" +#include "deepmind/lua/n_results_or_test_util.h" +#include "deepmind/lua/push_script.h" +#include "deepmind/lua/read.h" +#include "deepmind/lua/table_ref.h" +#include "deepmind/support/test_srcdir.h" + +namespace deepmind { +namespace lab { +namespace lua { +namespace { + +using ::deepmind::lab::lua::testing::IsOkAndHolds; + +TEST(VmTest, TestVm) { + std::vector<Vm> vms; + + for (int i = 0; i != 10; ++i) { + vms.push_back(CreateVm()); + } + + for (std::size_t i = 0; i != vms.size(); ++i) { + lua_State* L = vms[i].get(); + EXPECT_EQ(0, lua_gettop(L)); + lua_pushstring(L, "Hello"); + lua_pushnumber(L, i); + } + + for (std::size_t i = 0; i != vms.size(); ++i) { + lua_State* L = vms[i].get(); + EXPECT_EQ(2, lua_gettop(L)); + EXPECT_STREQ("Hello", lua_tostring(L, 1)); + EXPECT_EQ(static_cast<int>(i), lua_tointeger(L, 2)); + } +} + +constexpr char kUseModule[] = R"( +local mod = require 'test.module' +return mod.hello +)"; + +int CModule(lua_State* L) { + auto table = TableRef::Create(L); + table.Insert("hello", 11); + Push(L, table); + return 1; +} + +TEST(VmTest, TestEmbedC) { + Vm vm = CreateVm(); + vm.AddCModuleToSearchers("test.module", CModule); + auto* L = vm.get(); + + ASSERT_THAT(PushScript(L, kUseModule, "kUseModule"), IsOkAndHolds(1)) + << "Missing script"; + + ASSERT_THAT(lua::Call(L, 0), IsOkAndHolds(1)) + << "Missing result"; + + int val; + ASSERT_TRUE(IsFound(lua::Read(L, -1, &val))); + EXPECT_EQ(11, val); +} + +int CModuleUpValue(lua_State* L) { + int* up1 = static_cast<int*>(lua_touserdata(L, lua_upvalueindex(1))); + int* up2 = static_cast<int*>(lua_touserdata(L, lua_upvalueindex(2))); + auto table = TableRef::Create(L); + table.Insert("hello", *up1 / *up2); + Push(L, table); + return 1; +} + +TEST(VmTest, TestEmbedCClosure) { + Vm vm = CreateVm(); + int val1 = 55; + int val2 = 5; + vm.AddCModuleToSearchers("test.module", CModuleUpValue, {&val1, &val2}); + + auto* L = vm.get(); + ASSERT_THAT(PushScript(L, kUseModule, "kUseModule"), IsOkAndHolds(1)); + ASSERT_THAT(lua::Call(L, 0), IsOkAndHolds(1)); + + int val; + ASSERT_TRUE(IsFound(lua::Read(L, -1, &val))); + EXPECT_EQ(11, val); +} + +constexpr char kLuaModule[] = R"( +local mod = { hello = 11 } +return mod +)"; + +TEST(VmTest, TestEmbedLua) { + Vm vm = CreateVm(); + vm.AddLuaModuleToSearchers("test.module", kLuaModule, sizeof(kLuaModule) - 1); + auto* L = vm.get(); + + ASSERT_THAT(PushScript(L, kUseModule, "kUseModule"), IsOkAndHolds(1)) + << "Missing script"; + + ASSERT_THAT(lua::Call(L, 0), IsOkAndHolds(1)) + << "Missing result"; + + int val; + ASSERT_TRUE(IsFound(lua::Read(L, -1, &val))); + EXPECT_EQ(11, val); +} + +constexpr char kUsePath[] = R"( +local mod = require 'deepmind.lua.vm_test_module' +return mod.hello +)"; + +TEST(VmTest, TestLuaPath) { + Vm vm = CreateVm(); + vm.AddPathToSearchers(TestSrcDir()); + + auto* L = vm.get(); + + ASSERT_THAT(PushScript(L, kUsePath, "kUsePath"), IsOkAndHolds(1)) + << "Missing script"; + + ASSERT_THAT(lua::Call(L, 0), IsOkAndHolds(1)) + << "Missing result"; + + int val; + ASSERT_TRUE(IsFound(lua::Read(L, -1, &val))); + EXPECT_EQ(11, val); +} + +} // namespace +} // namespace lua +} // namespace lab +} // namespace deepmind diff --git a/pool/shard007/C++/0094500_connection_file_reader.cc b/pool/shard007/C++/0094500_connection_file_reader.cc new file mode 100644 index 0000000000000000000000000000000000000000..6e1f0eb19d069a3745ebc92d41e187d36bf7b499 --- /dev/null +++ b/pool/shard007/C++/0094500_connection_file_reader.cc @@ -0,0 +1,66 @@ +// Copyright 2010-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. + +#include "data_manager/connection_file_reader.h" + +#include <string> + +#include "base/logging.h" +#include "base/number_util.h" + +namespace mozc { + +ConnectionFileReader::ConnectionFileReader(const string &filename) + : stream_(filename.c_str()), done_(false), array_index_(-1), cost_(0) { + LOG(INFO) << "Loading " << filename; + string header; + CHECK(!getline(stream_, header).fail()) << filename << " is empty."; + pos_size_ = NumberUtil::SimpleAtoi(header); + Next(); +} + +ConnectionFileReader::~ConnectionFileReader() { + stream_.close(); + LOG(INFO) << "Done"; +} + +void ConnectionFileReader::Next() { + if (done_) { + return; + } + string line; + done_ = getline(stream_, line).fail(); + if (done_) { + return; + } + ++array_index_; + cost_ = NumberUtil::SimpleAtoi(line); +} + +} // namespace mozc diff --git a/pool/shard007/C++/0094501_plugin_private_file_system_backend_unittest.cc b/pool/shard007/C++/0094501_plugin_private_file_system_backend_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..0cc2f48bb008ad56c0c57462f0c2363f26b211fe --- /dev/null +++ b/pool/shard007/C++/0094501_plugin_private_file_system_backend_unittest.cc @@ -0,0 +1,147 @@ +// Copyright 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/basictypes.h" +#include "base/file_util.h" +#include "base/files/scoped_temp_dir.h" +#include "base/memory/scoped_ptr.h" +#include "base/message_loop/message_loop.h" +#include "base/message_loop/message_loop_proxy.h" +#include "base/run_loop.h" +#include "content/public/test/test_file_system_context.h" +#include "content/public/test/test_file_system_options.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "webkit/browser/fileapi/async_file_test_helper.h" +#include "webkit/browser/fileapi/file_system_context.h" +#include "webkit/browser/fileapi/isolated_context.h" +#include "webkit/browser/fileapi/obfuscated_file_util.h" +#include "webkit/browser/fileapi/plugin_private_file_system_backend.h" +#include "webkit/common/fileapi/file_system_util.h" + +namespace fileapi { + +namespace { + +const GURL kOrigin("http://www.example.com"); +const std::string kPlugin1("plugin1"); +const std::string kPlugin2("plugin2"); +const FileSystemType kType = kFileSystemTypePluginPrivate; +const std::string kRootName = "pluginprivate"; + +void DidOpenFileSystem(base::PlatformFileError* error_out, + base::PlatformFileError error) { + *error_out = error; +} + +std::string RegisterFileSystem() { + return IsolatedContext::GetInstance()->RegisterFileSystemForVirtualPath( + kType, kRootName, base::FilePath()); +} + +} // namespace + +class PluginPrivateFileSystemBackendTest : public testing::Test { + protected: + virtual void SetUp() OVERRIDE { + ASSERT_TRUE(data_dir_.CreateUniqueTempDir()); + context_ = CreateFileSystemContextForTesting( + NULL /* quota_manager_proxy */, + data_dir_.path()); + } + + FileSystemURL CreateURL(const GURL& root_url, const std::string& relative) { + FileSystemURL root = context_->CrackURL(root_url); + return context_->CreateCrackedFileSystemURL( + root.origin(), + root.mount_type(), + root.virtual_path().AppendASCII(relative)); + } + + PluginPrivateFileSystemBackend* backend() const { + return context_->plugin_private_backend(); + } + + const base::FilePath& base_path() const { return backend()->base_path(); } + + base::ScopedTempDir data_dir_; + base::MessageLoop message_loop_; + scoped_refptr<FileSystemContext> context_; + std::string filesystem_id_; +}; + +TEST_F(PluginPrivateFileSystemBackendTest, OpenFileSystemBasic) { + const std::string filesystem_id1 = RegisterFileSystem(); + base::PlatformFileError error = base::PLATFORM_FILE_ERROR_FAILED; + backend()->OpenPrivateFileSystem( + kOrigin, kType, filesystem_id1, kPlugin1, + OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT, + base::Bind(&DidOpenFileSystem, &error)); + base::RunLoop().RunUntilIdle(); + ASSERT_EQ(base::PLATFORM_FILE_OK, error); + + // Run this again with FAIL_IF_NONEXISTENT to see if it succeeds. + const std::string filesystem_id2 = RegisterFileSystem(); + error = base::PLATFORM_FILE_ERROR_FAILED; + backend()->OpenPrivateFileSystem( + kOrigin, kType, filesystem_id2, kPlugin1, + OPEN_FILE_SYSTEM_FAIL_IF_NONEXISTENT, + base::Bind(&DidOpenFileSystem, &error)); + base::RunLoop().RunUntilIdle(); + ASSERT_EQ(base::PLATFORM_FILE_OK, error); + + const GURL root_url( + GetIsolatedFileSystemRootURIString(kOrigin, filesystem_id1, kRootName)); + FileSystemURL file = CreateURL(root_url, "foo"); + base::FilePath platform_path; + EXPECT_EQ(base::PLATFORM_FILE_OK, + AsyncFileTestHelper::CreateFile(context_.get(), file)); + EXPECT_EQ(base::PLATFORM_FILE_OK, + AsyncFileTestHelper::GetPlatformPath(context_.get(), file, + &platform_path)); + EXPECT_TRUE(base_path().AppendASCII("000").AppendASCII(kPlugin1).IsParent( + platform_path)); +} + +TEST_F(PluginPrivateFileSystemBackendTest, PluginIsolation) { + // Open filesystem for kPlugin1 and kPlugin2. + const std::string filesystem_id1 = RegisterFileSystem(); + base::PlatformFileError error = base::PLATFORM_FILE_ERROR_FAILED; + backend()->OpenPrivateFileSystem( + kOrigin, kType, filesystem_id1, kPlugin1, + OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT, + base::Bind(&DidOpenFileSystem, &error)); + base::RunLoop().RunUntilIdle(); + ASSERT_EQ(base::PLATFORM_FILE_OK, error); + + const std::string filesystem_id2 = RegisterFileSystem(); + error = base::PLATFORM_FILE_ERROR_FAILED; + backend()->OpenPrivateFileSystem( + kOrigin, kType, filesystem_id2, kPlugin2, + OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT, + base::Bind(&DidOpenFileSystem, &error)); + base::RunLoop().RunUntilIdle(); + ASSERT_EQ(base::PLATFORM_FILE_OK, error); + + // Create 'foo' in kPlugin1. + const GURL root_url1( + GetIsolatedFileSystemRootURIString(kOrigin, filesystem_id1, kRootName)); + FileSystemURL file1 = CreateURL(root_url1, "foo"); + base::FilePath platform_path; + EXPECT_EQ(base::PLATFORM_FILE_OK, + AsyncFileTestHelper::CreateFile(context_.get(), file1)); + EXPECT_TRUE(AsyncFileTestHelper::FileExists( + context_.get(), file1, AsyncFileTestHelper::kDontCheckSize)); + + // See the same path is not available in kPlugin2. + const GURL root_url2( + GetIsolatedFileSystemRootURIString(kOrigin, filesystem_id2, kRootName)); + FileSystemURL file2 = CreateURL(root_url2, "foo"); + EXPECT_FALSE(AsyncFileTestHelper::FileExists( + context_.get(), file2, AsyncFileTestHelper::kDontCheckSize)); +} + +// TODO(kinuko,nhiroki): also test if DeleteOriginDataOnFileThread +// works fine when there's multiple plugin partitions. + +} // namespace fileapi diff --git a/pool/shard007/C++/0094502_download_history.cc b/pool/shard007/C++/0094502_download_history.cc new file mode 100644 index 0000000000000000000000000000000000000000..69469999b52343ef57a6d560f084bf416cd2af76 --- /dev/null +++ b/pool/shard007/C++/0094502_download_history.cc @@ -0,0 +1,155 @@ +// Copyright (c) 2012 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 "chrome/browser/download/download_history.h" + +#include "base/logging.h" +#include "chrome/browser/download/download_crx_util.h" +#include "chrome/browser/history/history_marshaling.h" +#include "chrome/browser/history/history_service_factory.h" +#include "chrome/browser/profiles/profile.h" +#include "content/public/browser/download_item.h" +#include "content/public/browser/download_persistent_store_info.h" + +using content::DownloadItem; +using content::DownloadPersistentStoreInfo; + +DownloadHistory::DownloadHistory(Profile* profile) + : profile_(profile), + next_fake_db_handle_(DownloadItem::kUninitializedHandle - 1) { + DCHECK(profile); +} + +DownloadHistory::~DownloadHistory() {} + +void DownloadHistory::GetNextId( + const HistoryService::DownloadNextIdCallback& callback) { + HistoryService* hs = HistoryServiceFactory::GetForProfile( + profile_, Profile::EXPLICIT_ACCESS); + if (!hs) + return; + + hs->GetNextDownloadId(&history_consumer_, callback); +} + +void DownloadHistory::Load( + const HistoryService::DownloadQueryCallback& callback) { + HistoryService* hs = HistoryServiceFactory::GetForProfile( + profile_, Profile::EXPLICIT_ACCESS); + if (!hs) + return; + + hs->QueryDownloads(&history_consumer_, callback); + + // This is the initial load, so do a cleanup of corrupt in-progress entries. + hs->CleanUpInProgressEntries(); +} + +void DownloadHistory::CheckVisitedReferrerBefore( + int32 download_id, + const GURL& referrer_url, + const VisitedBeforeDoneCallback& callback) { + if (referrer_url.is_valid()) { + HistoryService* hs = HistoryServiceFactory::GetForProfileIfExists( + profile_, Profile::EXPLICIT_ACCESS); + if (hs) { + HistoryService::Handle handle = + hs->GetVisibleVisitCountToHost(referrer_url, &history_consumer_, + base::Bind(&DownloadHistory::OnGotVisitCountToHost, + base::Unretained(this))); + visited_before_requests_[handle] = callback; + return; + } + } + callback.Run(false); +} + +void DownloadHistory::AddEntry( + DownloadItem* download_item, + const HistoryService::DownloadCreateCallback& callback) { + DCHECK(download_item); + // Do not store the download in the history database for a few special cases: + // - incognito mode (that is the point of this mode) + // - extensions (users don't think of extension installation as 'downloading') + // - temporary download, like in drag-and-drop + // - history service is not available (e.g. in tests) + // We have to make sure that these handles don't collide with normal db + // handles, so we use a negative value. Eventually, they could overlap, but + // you'd have to do enough downloading that your ISP would likely stab you in + // the neck first. YMMV. + HistoryService* hs = HistoryServiceFactory::GetForProfileIfExists( + profile_, Profile::EXPLICIT_ACCESS); + if (download_item->IsOtr() || + download_crx_util::IsExtensionDownload(*download_item) || + download_item->IsTemporary() || !hs) { + callback.Run(download_item->GetId(), GetNextFakeDbHandle()); + return; + } + + int32 id = download_item->GetId(); + DownloadPersistentStoreInfo history_info = + download_item->GetPersistentStoreInfo(); + hs->CreateDownload(id, history_info, &history_consumer_, callback); +} + +void DownloadHistory::UpdateEntry(DownloadItem* download_item) { + // Don't store info in the database if the download was initiated while in + // incognito mode or if it hasn't been initialized in our database table. + if (download_item->GetDbHandle() <= DownloadItem::kUninitializedHandle) + return; + + HistoryService* hs = HistoryServiceFactory::GetForProfileIfExists( + profile_, Profile::EXPLICIT_ACCESS); + if (!hs) + return; + hs->UpdateDownload(download_item->GetPersistentStoreInfo()); +} + +void DownloadHistory::UpdateDownloadPath(DownloadItem* download_item, + const FilePath& new_path) { + // No update necessary if the download was initiated while in incognito mode. + if (download_item->GetDbHandle() <= DownloadItem::kUninitializedHandle) + return; + + HistoryService* hs = HistoryServiceFactory::GetForProfileIfExists( + profile_, Profile::EXPLICIT_ACCESS); + if (hs) + hs->UpdateDownloadPath(new_path, download_item->GetDbHandle()); +} + +void DownloadHistory::RemoveEntry(DownloadItem* download_item) { + // No update necessary if the download was initiated while in incognito mode. + if (download_item->GetDbHandle() <= DownloadItem::kUninitializedHandle) + return; + + HistoryService* hs = HistoryServiceFactory::GetForProfileIfExists( + profile_, Profile::EXPLICIT_ACCESS); + if (hs) + hs->RemoveDownload(download_item->GetDbHandle()); +} + +void DownloadHistory::RemoveEntriesBetween(const base::Time remove_begin, + const base::Time remove_end) { + HistoryService* hs = HistoryServiceFactory::GetForProfileIfExists( + profile_, Profile::EXPLICIT_ACCESS); + if (hs) + hs->RemoveDownloadsBetween(remove_begin, remove_end); +} + +int64 DownloadHistory::GetNextFakeDbHandle() { + return next_fake_db_handle_--; +} + +void DownloadHistory::OnGotVisitCountToHost(HistoryService::Handle handle, + bool found_visits, + int count, + base::Time first_visit) { + VisitedBeforeRequestsMap::iterator request = + visited_before_requests_.find(handle); + DCHECK(request != visited_before_requests_.end()); + VisitedBeforeDoneCallback callback = request->second; + visited_before_requests_.erase(request); + callback.Run(found_visits && count && + (first_visit.LocalMidnight() < base::Time::Now().LocalMidnight())); +} diff --git a/pool/shard007/C++/0094507_sync.cpp b/pool/shard007/C++/0094507_sync.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a4dbf4433e99ed4dc9aefb5f8b548c1b546fba2a --- /dev/null +++ b/pool/shard007/C++/0094507_sync.cpp @@ -0,0 +1,129 @@ +// Copyright (c) 2011-2012 The Bitcoin developers +// Copyright (c) 2011-2012 GGcoin Developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "sync.h" +#include "util.h" + +#include <boost/foreach.hpp> + +#ifdef DEBUG_LOCKCONTENTION +void PrintLockContention(const char* pszName, const char* pszFile, int nLine) +{ + printf("LOCKCONTENTION: %s\n", pszName); + printf("Locker: %s:%d\n", pszFile, nLine); +} +#endif /* DEBUG_LOCKCONTENTION */ + +#ifdef DEBUG_LOCKORDER +// +// Early deadlock detection. +// Problem being solved: +// Thread 1 locks A, then B, then C +// Thread 2 locks D, then C, then A +// --> may result in deadlock between the two threads, depending on when they run. +// Solution implemented here: +// Keep track of pairs of locks: (A before B), (A before C), etc. +// Complain if any thread tries to lock in a different order. +// + +struct CLockLocation +{ + CLockLocation(const char* pszName, const char* pszFile, int nLine) + { + mutexName = pszName; + sourceFile = pszFile; + sourceLine = nLine; + } + + std::string ToString() const + { + return mutexName+" "+sourceFile+":"+itostr(sourceLine); + } + +private: + std::string mutexName; + std::string sourceFile; + int sourceLine; +}; + +typedef std::vector< std::pair<void*, CLockLocation> > LockStack; + +static boost::mutex dd_mutex; +static std::map<std::pair<void*, void*>, LockStack> lockorders; +static boost::thread_specific_ptr<LockStack> lockstack; + + +static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2) +{ + printf("POTENTIAL DEADLOCK DETECTED\n"); + printf("Previous lock order was:\n"); + BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s2) + { + if (i.first == mismatch.first) printf(" (1)"); + if (i.first == mismatch.second) printf(" (2)"); + printf(" %s\n", i.second.ToString().c_str()); + } + printf("Current lock order is:\n"); + BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s1) + { + if (i.first == mismatch.first) printf(" (1)"); + if (i.first == mismatch.second) printf(" (2)"); + printf(" %s\n", i.second.ToString().c_str()); + } +} + +static void push_lock(void* c, const CLockLocation& locklocation, bool fTry) +{ + if (lockstack.get() == NULL) + lockstack.reset(new LockStack); + + if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str()); + dd_mutex.lock(); + + (*lockstack).push_back(std::make_pair(c, locklocation)); + + if (!fTry) { + BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, (*lockstack)) { + if (i.first == c) break; + + std::pair<void*, void*> p1 = std::make_pair(i.first, c); + if (lockorders.count(p1)) + continue; + lockorders[p1] = (*lockstack); + + std::pair<void*, void*> p2 = std::make_pair(c, i.first); + if (lockorders.count(p2)) + { + potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]); + break; + } + } + } + dd_mutex.unlock(); +} + +static void pop_lock() +{ + if (fDebug) + { + const CLockLocation& locklocation = (*lockstack).rbegin()->second; + printf("Unlocked: %s\n", locklocation.ToString().c_str()); + } + dd_mutex.lock(); + (*lockstack).pop_back(); + dd_mutex.unlock(); +} + +void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry) +{ + push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry); +} + +void LeaveCritical() +{ + pop_lock(); +} + +#endif /* DEBUG_LOCKORDER */ diff --git a/pool/shard007/C++/0094511_helloworld.cpp b/pool/shard007/C++/0094511_helloworld.cpp new file mode 100644 index 0000000000000000000000000000000000000000..52eaf2d0074db5a3f71b4d58a8cd64c106d75a61 --- /dev/null +++ b/pool/shard007/C++/0094511_helloworld.cpp @@ -0,0 +1,73 @@ +/******************************************************* + * Copyright (c) 2014, ArrayFire + * All rights reserved. + * + * This file is distributed under 3-clause BSD license. + * The complete license agreement can be obtained at: + * http://arrayfire.com/licenses/BSD-3-Clause + ********************************************************/ + +#include <arrayfire.h> +#include <cstdio> +#include <cstdlib> + +using namespace af; + +int main(int argc, char *argv[]) +{ + try { + // Select a device and display arrayfire info + int device = argc > 1 ? atoi(argv[1]) : 0; + af::setDevice(device); + af::info(); + + printf("Create a 5-by-3 matrix of random floats on the GPU\n"); + array A = randu(5,3, f32); + af_print(A); + + printf("Element-wise arithmetic\n"); + array B = sin(A) + 1.5; + af_print(B); + + printf("Negate the first three elements of second column\n"); + B(seq(0, 2), 1) = B(seq(0, 2), 1) * -1; + af_print(B); + + printf("Fourier transform the result\n"); + array C = fft(B); + af_print(C); + + printf("Grab last row\n"); + array c = C.row(end); + af_print(c); + + printf("Create 2-by-3 matrix from host data\n"); + float d[] = { 1, 2, 3, 4, 5, 6 }; + array D(2, 3, d, af::afHost); + af_print(D); + + printf("Copy last column onto first\n"); + D.col(0) = D.col(end); + af_print(D); + + // Sort A + printf("Sort A and print sorted array and corresponding indices\n"); + array vals, inds; + sort(vals, inds, A); + af_print(vals); + af_print(inds); + + } catch (af::exception& e) { + fprintf(stderr, "%s\n", e.what()); + throw; + } + + #ifdef WIN32 // pause in Windows + if (!(argc == 2 && argv[1][0] == '-')) { + printf("hit [enter]..."); + fflush(stdout); + getchar(); + } + #endif + return 0; +} diff --git a/pool/shard007/C++/0094514_MyString.cpp b/pool/shard007/C++/0094514_MyString.cpp new file mode 100644 index 0000000000000000000000000000000000000000..78b57aef12c68f7b9df8795f26880e8d6bb8b70e --- /dev/null +++ b/pool/shard007/C++/0094514_MyString.cpp @@ -0,0 +1,173 @@ +// String.c +#include <stdio.h> +#include <stdlib.h> + +#include "MyString.h" +#include "MemHeap.h" + +/* private functions, internal to the development of the String abstract type */ + +/* copy 'len' characters from 'src' to 'dst'. If there is a zero in the src array + * it is copied (i.e., we don't assume null-terminated strings */ +// true C aficionados would use the standard library function 'memcpy' instead of this function +static void copyChars(char dst[], const char src[], int len) { + int k = 0; + while (k < len) { + dst[k] = src[k]; + k = k + 1; + } +} + + +/* public functions, declarations of these functions are included in String.h */ + +/* + * c_string is a normal string (using C conventions) + * initialize a String object and return it + */ +String StringCreate(const char* c_string) { + String retVal; + + /* Step 1: determine the length of the source string */ + int k = 0; + while (c_string[k] != 0) { + k = k + 1; + } + + /* Step 2: populate our struct's components */ + retVal.len = k; + retVal.ptr = (char*) malloc(retVal.len * sizeof(char)); + + /* Step 3: don't forget! to copy the string into the buffer */ + copyChars(retVal.ptr, c_string, retVal.len); + + return retVal; +} + +/* + * initialize a String object that is an exact duplicate of src and return that string + * (NOTE: this is a deep copy) + */ +String StringDup(String* src) { + String retVal; + + retVal.len = (*src).len; + retVal.ptr = (char*) malloc(retVal.len * sizeof(char)); + + /* Step 3: don't forget! to copy the string into the buffer */ + copyChars(retVal.ptr, (*src).ptr, retVal.len); + + return retVal; +} + + +void StringDestroy(String* s) { + free((*s).ptr); +} + +void StringPrint(String* s) { + int k; + for (k = 0; k < (*s).len; k += 1) { + putchar((*s).ptr[k]); + } +} + + +/* + * Replace old_str with a copy of new_str + * This function differs from StringDup in that here we assume old_str is already + * a String (has previously been initialized). The StringDup function would be appropriate + * (instead of this function) if you have an uninitialized String struct */ +void StringReAssign(String* old_str, String* new_str) { + if (old_str == new_str) { // huh? don't know why someone would do this + /* old_str and new_str are already the same, so, just get out of town */ + return; + } + + StringDestroy(old_str); + *old_str = StringDup(new_str); +} + +/* + * replace the contents of s with the concatenation of s and suffix + * NOTE: we must reallocate a new array on the heap to have sufficient storage to hold + * thew new and longer string that results from concatenating */ +void StringAppend(String* s, String* suffix) { + int new_len = (*s).len + (*suffix).len; + char* new_ptr = (char*) malloc(new_len * sizeof(char)); + + copyChars(new_ptr, (*s).ptr, (*s).len); + copyChars(new_ptr + (*s).len, (*suffix).ptr, (*suffix).len); + + free((*s).ptr); + (*s).len = new_len; + (*s).ptr = new_ptr; +} + +/* + * return a newly created string that is initialized as a copy of the concatenation of a and b */ +String StringConcat(String* a, String* b) { + int j; // indexes into a source string (a or b) + int k; // indexes into the result string + String retVal; + retVal.len = (*a).len + (*b).len; + retVal.ptr = (char*) malloc(retVal.len * sizeof(char)); // plus one byte for the terminating zero + + j = 0; + k = 0; + while (j < (*a).len) { + retVal.ptr[k] = (*a).ptr[j]; + j += 1; + k += 1; + } + + j = 0; + while (j < (*b).len) { + retVal.ptr[k] = (*b).ptr[j]; + j += 1; + k += 1; + } + + return retVal; +} + + +bool StringIsEqualTo(String* s1, String* s2) { + int k = 0; + + if ((*s1).len != (*s2).len) { return false; } // lengths must be the same, otherwise, don't bother + + while (k < (*s1).len) { + if ((*s1).ptr[k] != (*s2).ptr[k]) { // kth character differs, so strings are not the same, quit now + return false; + } + k = k + 1; + } + // if we finish the loop, then all characters are equal + return true; +} + +bool StringIsLessThan(String* s1, String* s2) { + int k = 0; + + while (k != (*s1).len + && k != (*s2).len) { + if ((*s1).ptr[k] < (*s2).ptr[k]) { // the next character in s1 < the character from s2, so return true + return true; + } else if ((*s1).ptr[k] > (*s2).ptr[k]) { // s1 > s2, return false + return false; + } else { // the characters must be the same, so just keep going + k = k + 1; + } + } + + if ((*s1).len == (*s2).len) { // strings are equal (s1 not less than s2) + return false; + } else if ((*s1).len > (*s2).len) { /* s2 is a prefix of s1, i.e., s2 < s1 */ + return false; + } else { /* s1 is a prefix of s2, so s1 < s2 */ + return true; + } +} + + diff --git a/pool/shard007/C++/0094515_rchome.cpp b/pool/shard007/C++/0094515_rchome.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9db68c1f9fa3d60bb1bced13b20fbcb86c588847 --- /dev/null +++ b/pool/shard007/C++/0094515_rchome.cpp @@ -0,0 +1,88 @@ +#include "rchome.h" + + + +RCHome::RCHome():radio("/dev/spidev0.0",8000000 , 25) { + radio.begin(); + radio.setRetries(15,15); + radio.setChannel(1); + radio.setPALevel(RF24_PA_MAX); + radio.setAutoAck(true); + radio.startListening(); + openlog( "RCHome", LOG_PID, LOG_DAEMON); +} + +int RCHome::setBase(uint64_t base){ + baseAddr = base; + //correct check will be added + return 0; +} + +uint64_t RCHome::getBase(void){ +return baseAddr; +} + + +int RCHOME::setControllerSAddress(int sAddress){ + controllerSAddress = sAddress; + radio.stopListening(); + radio.openReadingPipe(1,baseAddr+sAddress); + radio.startListening(); + //correct check will be added + return 0; +} + +int RCHOME::getControllerSAddress(void){ + return controllerSAddress; +} + +void RCHOME::setDestinationAddress(int sAddress){ + radio.stopListening(); + radio.openWritingPipe(baseAddr+sAddress); + radio.startListening(); +} + +int RCHOME::send(char* input, char* output){ + memset(output,0,COMMAND_LENGHT); + setDestinationAddress(input[0]); + bool timeout = false; + radio.stopListening(); + bool ok = radio.write( input, sizeof(char[COMMAND_LENGHT]) ); + if (!ok){ + __msleep(10); + syslog(LOG_ERR, "Can`t send packet"); + return; + } + else{ + syslog(LOG_NOTICE, "Packet sended, wait for response..."); + radio.startListening(); + unsigned long started_waiting_at = __millis(); + while ( ! radio.available() && ! timeout ) { + __msleep(5); + if (__millis() - started_waiting_at > RESPONSE_TIMEOUT ) + { + timeout = true; + } + } + } + + if ( timeout ){ + syslog(LOG_ERR, "Timeout send packet"); + return; + } + else{ + radio.read( output, sizeof(char[COMMAND_LENGHT]) ); + syslog(LOG_NOTICE, "Packet recieved"); + return; + } +} + + +int RCHOME::listen(char* output){ + memset(output,0,COMMAND_LENGHT); + if (radio.available()){ + radio.read( output, sizeof(char[COMMAND_LENGHT]) ); + return 1; + } + return 0; +} diff --git a/pool/shard007/C++/0094517_histogram_controller.cc b/pool/shard007/C++/0094517_histogram_controller.cc new file mode 100644 index 0000000000000000000000000000000000000000..54f760b36cfa94ca49e05e0c3a3fc2841966de82 --- /dev/null +++ b/pool/shard007/C++/0094517_histogram_controller.cc @@ -0,0 +1,116 @@ +// Copyright (c) 2012 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 "content/browser/histogram_controller.h" + +#include "base/bind.h" +#include "base/metrics/histogram.h" +#include "content/browser/histogram_subscriber.h" +#include "content/common/child_process_messages.h" +#include "content/public/browser/browser_child_process_host_iterator.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/child_process_data.h" +#include "content/public/browser/render_process_host.h" +#include "content/public/common/process_type.h" + +namespace content { + +HistogramController* HistogramController::GetInstance() { + return Singleton<HistogramController>::get(); +} + +HistogramController::HistogramController() : subscriber_(NULL) { +} + +HistogramController::~HistogramController() { +} + +void HistogramController::OnPendingProcesses(int sequence_number, + int pending_processes, + bool end) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + if (subscriber_) + subscriber_->OnPendingProcesses(sequence_number, pending_processes, end); +} + +void HistogramController::OnHistogramDataCollected( + int sequence_number, + const std::vector<std::string>& pickled_histograms) { + if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::Bind(&HistogramController::OnHistogramDataCollected, + base::Unretained(this), + sequence_number, + pickled_histograms)); + return; + } + + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + if (subscriber_) { + subscriber_->OnHistogramDataCollected(sequence_number, + pickled_histograms); + } +} + +void HistogramController::Register(HistogramSubscriber* subscriber) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + DCHECK(!subscriber_); + subscriber_ = subscriber; +} + +void HistogramController::Unregister( + const HistogramSubscriber* subscriber) { + DCHECK_EQ(subscriber_, subscriber); + subscriber_ = NULL; +} + +void HistogramController::GetHistogramDataFromChildProcesses( + int sequence_number) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); + + int pending_processes = 0; + for (BrowserChildProcessHostIterator iter; !iter.Done(); ++iter) { + int type = iter.GetData().process_type; + if (type != PROCESS_TYPE_PLUGIN && type != PROCESS_TYPE_GPU) + continue; + ++pending_processes; + if (!iter.Send(new ChildProcessMsg_GetChildHistogramData(sequence_number))) + --pending_processes; + } + + BrowserThread::PostTask( + BrowserThread::UI, + FROM_HERE, + base::Bind( + &HistogramController::OnPendingProcesses, + base::Unretained(this), + sequence_number, + pending_processes, + true)); +} + +void HistogramController::GetHistogramData(int sequence_number) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + + int pending_processes = 0; + for (RenderProcessHost::iterator it(RenderProcessHost::AllHostsIterator()); + !it.IsAtEnd(); it.Advance()) { + ++pending_processes; + if (!it.GetCurrentValue()->Send( + new ChildProcessMsg_GetChildHistogramData(sequence_number))) { + --pending_processes; + } + } + OnPendingProcesses(sequence_number, pending_processes, false); + + BrowserThread::PostTask( + BrowserThread::IO, + FROM_HERE, + base::Bind(&HistogramController::GetHistogramDataFromChildProcesses, + base::Unretained(this), + sequence_number)); +} + +} // namespace content diff --git a/pool/shard007/C++/0094523_util.cpp b/pool/shard007/C++/0094523_util.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d72a742872826743ffbf70afc31cffafb5ee7e18 --- /dev/null +++ b/pool/shard007/C++/0094523_util.cpp @@ -0,0 +1,57 @@ +#include <Helium/util.h> + +#include "test.h" + +using namespace Helium; + +void test_factorial() +{ + COMPARE(1, factorial(0)); + COMPARE(1, factorial(1)); + COMPARE(2, factorial(2)); + COMPARE(6, factorial(3)); + COMPARE(24, factorial(4)); +} + +void test_num_combinations() +{ + COMPARE(8, num_combinations(8, 1)); + COMPARE(28, num_combinations(8, 2)); + COMPARE(56, num_combinations(8, 3)); +} + +void test_combinations() +{ + std::string s = "ABCDEFGH"; + + // 1 element + int count = 0; + do { + ++count; + } while (next_combination(s.begin(), s.begin() + 1, s.end())); + + COMPARE(8, count); + + // 2 elements + count = 0; + do { + ++count; + } while (next_combination(s.begin(), s.begin() + 2, s.end())); + + COMPARE(28, count); + + // 3 elements + count = 0; + do { + ++count; + } while (next_combination(s.begin(), s.begin() + 3, s.end())); + + COMPARE(56, count); +} + +int main() +{ + test_factorial(); + test_num_combinations(); + test_combinations(); +} diff --git a/pool/shard007/C++/0094531_tooltip_manager.cc b/pool/shard007/C++/0094531_tooltip_manager.cc new file mode 100644 index 0000000000000000000000000000000000000000..b2e68271c1a585dd8e5ef0d4afe199be5869fa2e --- /dev/null +++ b/pool/shard007/C++/0094531_tooltip_manager.cc @@ -0,0 +1,36 @@ +// Copyright (c) 2011 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 "ui/views/widget/tooltip_manager.h" + +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/screen.h" +#include "ui/gfx/text_elider.h" + +namespace views { + +const size_t kMaxTooltipLength = 1024; + +// static +const char TooltipManager::kGroupingPropertyKey[] = "GroupingPropertyKey"; + +// static +int TooltipManager::GetMaxWidth(int x, int y, gfx::NativeView context) { + return GetMaxWidth(gfx::Screen::GetScreenFor(context)->GetDisplayNearestPoint( + gfx::Point(x, y))); +} + +// static +int TooltipManager::GetMaxWidth(const gfx::Display& display) { + return (display.bounds().width() + 1) / 2; +} + +// static +void TooltipManager::TrimTooltipText(base::string16* text) { + // Clamp the tooltip length to kMaxTooltipLength so that we don't + // accidentally DOS the user with a mega tooltip. + *text = gfx::TruncateString(*text, kMaxTooltipLength, gfx::WORD_BREAK); +} + +} // namespace views diff --git a/pool/shard007/C++/0094532_lxcmconfigfile.cc b/pool/shard007/C++/0094532_lxcmconfigfile.cc new file mode 100644 index 0000000000000000000000000000000000000000..00548b62699249bedc8f6e67d5319b8fd5bb7ab3 --- /dev/null +++ b/pool/shard007/C++/0094532_lxcmconfigfile.cc @@ -0,0 +1,119 @@ +/* This file is part of LXCManager. + * + * LXCManager is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * LXCManager is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with LXCManager. If not, see <http://www.gnu.org/licenses/>. */ + +#include "lxcmconfigfile.hh" +#include "exceptions.hh" +#include "logger.hh" +#include "lxcmjsonparser.hh" +#include <fstream> + +LXCMConfigFile* LXCMConfigFile::_instance = NULL; + +LXCMConfigFile::LXCMConfigFile () + : LXCMCoreModule ("core::LXCMConfigFile") + , _dom (NULL) +{ + LXCMOptions* opts = LXCMOptions::getOptions (); + + opts->addModule (this); + opts->addOption ("config,f", po::value<std::string> (), + "path to configuration file"); +} + +LXCMConfigFile::~LXCMConfigFile () +{ + LXCMConfigFile::_instance = NULL; +} + +void LXCMConfigFile::init () +{ + if (!LXCMConfigFile::_instance) + { + LXCMConfigFile::_instance = new LXCMConfigFile (); + } +} + +void LXCMConfigFile::checkOptions (po::variables_map& vm) +{ + std::string filename (CONFIG_DEFAULT_CONFIGFILE); + LXCMJsonParser tmp; + std::ifstream ifs; + char line_buffer[256]; + unsigned int line_counter = 0; + + if (vm.count ("config")) + { + filename = (vm["config"].as<std::string> ()); + } + + ifs.open (filename.c_str (), std::ifstream::in); + + do + { + memset (line_buffer, 0, sizeof (line_buffer)); + ifs.getline (line_buffer, sizeof (line_buffer) - 1); + try + { + std::string theLine (line_buffer); + tmp.parse (line_counter++, theLine); + } + catch (LXCMException& e) + { + THROW_FORWARD_ERROR (e); + } + } + while (ifs.good ()); + + this->_dom = tmp.getDom (); +#if defined (CONFIG_DEBUG) && CONFIG_DEBUG + this->print (std::cout); +#endif + ifs.close (); +} + +LXCMJsonVal const* LXCMConfigFile::getModuleOptions (LXCMModule const* module) +{ + LXCMConfigFile const *instance = LXCMConfigFile::_instance; + if (instance->_dom) + { + return instance->_dom->getObject (module->moduleName ()); + } + + return NULL; +} + +void LXCMConfigFile::print (std::ostream& os) const +{ + if (this->_dom) + { + os << *this->_dom; + } +} + +LXCMJsonVal const* lxcm_configfile_get_my_config (LXCMModule const* module) +{ + return LXCMConfigFile::getModuleOptions (module); +} + +std::ostream& operator<< (std::ostream& os, LXCMConfigFile const& obj) +{ + obj.print (os); + return os; +} + +static void __attribute__ ((constructor)) coremodule_init_configfile (void) +{ + LXCMConfigFile::init (); +} diff --git a/pool/shard007/C++/0094535_QVPieModelMapperSlots.cpp b/pool/shard007/C++/0094535_QVPieModelMapperSlots.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6491c201c898fbe67518a3d059dc4d7515cbac92 --- /dev/null +++ b/pool/shard007/C++/0094535_QVPieModelMapperSlots.cpp @@ -0,0 +1,156 @@ +/* + + Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5 + + Copyright (C) 2020 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com> + +*/ + +/* + DO NOT EDIT THIS FILE - the content was created using a source code generator +*/ + +#include "QVPieModelMapperSlots.h" + +QVPieModelMapperSlots::QVPieModelMapperSlots( QObject *parent ) : QObject( parent ) +{ +} + +QVPieModelMapperSlots::~QVPieModelMapperSlots() +{ +} + +#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0)) +void QVPieModelMapperSlots::firstRowChanged() +{ + QObject *object = qobject_cast<QObject *>(sender()); + + PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "firstRowChanged()" ); + + if( cb ) + { + PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QVPIEMODELMAPPER" ); + + hb_vmEvalBlockV( cb, 1, psender ); + + hb_itemRelease( psender ); + } +} +#endif + +#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0)) +void QVPieModelMapperSlots::labelsColumnChanged() +{ + QObject *object = qobject_cast<QObject *>(sender()); + + PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "labelsColumnChanged()" ); + + if( cb ) + { + PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QVPIEMODELMAPPER" ); + + hb_vmEvalBlockV( cb, 1, psender ); + + hb_itemRelease( psender ); + } +} +#endif + +#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0)) +void QVPieModelMapperSlots::modelReplaced() +{ + QObject *object = qobject_cast<QObject *>(sender()); + + PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "modelReplaced()" ); + + if( cb ) + { + PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QVPIEMODELMAPPER" ); + + hb_vmEvalBlockV( cb, 1, psender ); + + hb_itemRelease( psender ); + } +} +#endif + +#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0)) +void QVPieModelMapperSlots::rowCountChanged() +{ + QObject *object = qobject_cast<QObject *>(sender()); + + PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "rowCountChanged()" ); + + if( cb ) + { + PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QVPIEMODELMAPPER" ); + + hb_vmEvalBlockV( cb, 1, psender ); + + hb_itemRelease( psender ); + } +} +#endif + +#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0)) +void QVPieModelMapperSlots::seriesReplaced() +{ + QObject *object = qobject_cast<QObject *>(sender()); + + PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "seriesReplaced()" ); + + if( cb ) + { + PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QVPIEMODELMAPPER" ); + + hb_vmEvalBlockV( cb, 1, psender ); + + hb_itemRelease( psender ); + } +} +#endif + +#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0)) +void QVPieModelMapperSlots::valuesColumnChanged() +{ + QObject *object = qobject_cast<QObject *>(sender()); + + PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "valuesColumnChanged()" ); + + if( cb ) + { + PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QVPIEMODELMAPPER" ); + + hb_vmEvalBlockV( cb, 1, psender ); + + hb_itemRelease( psender ); + } +} +#endif + +void QVPieModelMapperSlots_connect_signal( const QString & signal, const QString & slot ) +{ +#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0)) + QVPieModelMapper * obj = (QVPieModelMapper *) Qt5xHb::itemGetPtrStackSelfItem(); + + if( obj ) + { + QVPieModelMapperSlots * s = QCoreApplication::instance()->findChild<QVPieModelMapperSlots *>(); + + if( s == NULL ) + { + s = new QVPieModelMapperSlots(); + s->moveToThread( QCoreApplication::instance()->thread() ); + s->setParent( QCoreApplication::instance() ); + } + + hb_retl( Qt5xHb::Signals_connection_disconnection( s, signal, slot ) ); + } + else + { + hb_retl( false ); + } +#else + hb_retl( false ); +#endif +} diff --git a/pool/shard007/C++/0094536_snake.cpp b/pool/shard007/C++/0094536_snake.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e4db6b2a0c6fcd44831cf6360d56a426cda8577b --- /dev/null +++ b/pool/shard007/C++/0094536_snake.cpp @@ -0,0 +1,45 @@ +#include "snake.h" + +void debugOutput(const QVector<int> &elementsOfArray) +{ + std::cout << "DEBUG OUTPUT: " << std::endl; + for (int i = 0; i < elementsOfArray.size(); ++i) + std::cout << elementsOfArray[i] << " "; + std::cout << std::endl; +} + +bool Snake::check(const int ¤tX, const int ¤tY, const int &size) +{ + return ((0 <= currentX && currentX < size) && + (0 <= currentY && currentY < size)); +} + +QVector<int> Snake::bypassSnake(int &size, int **array) +{ + const int numberOfDimensions = 4; + const int stepInit = 1; + const int indexOfDimensionInit = 0; + int currentX = size / 2; + int currentY = size / 2; + int step = stepInit; + int indexOfDimension = indexOfDimensionInit; + int x[numberOfDimensions] = {1, 0, -1, 0}; + int y[numberOfDimensions] = {0, 1, 0, -1}; + QVector<int> elementsOfArray; + elementsOfArray.clear(); + elementsOfArray.push_back(array[currentX][currentY]); + while (check(currentX, currentY, size)) + { + for (int i = 0; i < step; ++i) + { + currentX += x[indexOfDimension]; + currentY += y[indexOfDimension]; + if (!check(currentX, currentY, size)) + break; + elementsOfArray.push_back(array[currentX][currentY]); + } + step += (indexOfDimension % 2); + indexOfDimension = (indexOfDimension + 1) % numberOfDimensions; + } + return elementsOfArray; +} diff --git a/pool/shard007/C++/0094538_OperationChangeUUID.cc b/pool/shard007/C++/0094538_OperationChangeUUID.cc new file mode 100644 index 0000000000000000000000000000000000000000..71e4577ef84966beffa080d435fcdac63aea5ee6 --- /dev/null +++ b/pool/shard007/C++/0094538_OperationChangeUUID.cc @@ -0,0 +1,72 @@ +/* Copyright (C) 2012 Rogier Goossens + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see <http://www.gnu.org/licenses/>. + */ + +#include "../include/OperationChangeUUID.h" + +namespace GParted +{ + +OperationChangeUUID::OperationChangeUUID( const Device & device + , const Partition & partition_orig + , const Partition & partition_new + ) +{ + type = OPERATION_CHANGE_UUID ; + + this->device = device.get_copy_without_partitions(); + this ->partition_original = partition_orig ; + this ->partition_new = partition_new ; +} + +void OperationChangeUUID::apply_to_visual( std::vector<Partition> & partitions ) +{ + if ( partition_original .inside_extended ) + { + index_extended = find_index_extended( partitions ) ; + + if ( index_extended >= 0 ) + index = find_index_original( partitions[ index_extended ] .logicals ) ; + + if ( index >= 0 ) + partitions[ index_extended ] .logicals[ index ] = partition_new ; + } + else + { + index = find_index_original( partitions ) ; + + if ( index >= 0 ) + partitions[ index ] = partition_new ; + } +} + +void OperationChangeUUID::create_description() +{ + if ( partition_new .uuid == UUID_RANDOM_NTFS_HALF ) { + /*TO TRANSLATORS: looks like Set half the UUID to a new random value on ntfs file system on /dev/sda1 */ + description = String::ucompose( _("Set half the UUID to a new random value on %1 file system on %2") + , Utils::get_filesystem_string( partition_new .filesystem ) + , partition_new .get_path() + ) ; + } else { + /*TO TRANSLATORS: looks like Set a new random UUID on ext4 file system on /dev/sda1 */ + description = String::ucompose( _("Set a new random UUID on %1 file system on %2") + , Utils::get_filesystem_string( partition_new .filesystem ) + , partition_new .get_path() + ) ; + } +} + +} //GParted diff --git a/pool/shard007/C++/0094542_cpuset_controller_test.cc b/pool/shard007/C++/0094542_cpuset_controller_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..ad932efd3713ee8133619f973a4b6a87e55c421f --- /dev/null +++ b/pool/shard007/C++/0094542_cpuset_controller_test.cc @@ -0,0 +1,172 @@ +// Copyright 2014 Google Inc. 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 "lmctfy/controllers/cpuset_controller.h" + +#include <memory> + +#include "base/integral_types.h" +#include "system_api/kernel_api_mock.h" +#include "file/base/path.h" +#include "lmctfy/controllers/eventfd_notifications_mock.h" +#include "lmctfy/kernel_files.h" +#include "util/cpu_mask.h" +#include "util/cpu_mask_test_util.h" +#include "util/errors_test_util.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +using ::system_api::KernelAPIMock; +using ::util::ResSet; +using ::file::JoinPath; +using ::std::unique_ptr; +using ::testing::NotNull; +using ::testing::Return; +using ::testing::SetArgPointee; +using ::testing::StrictMock; +using ::testing::_; +using ::util::Status; +using ::util::StatusOr; +using ::util::error::NOT_FOUND; + +namespace containers { +namespace lmctfy { + +using ::util::CpuMask; + +static const char kParentMountPoint[] = "/dev/cgroup/cpuset"; +static const char kMountPoint[] = "/dev/cgroup/cpuset/test"; +static const char kHierarchyPath[] = "/test"; + +class CpusetControllerTest : public ::testing::Test { + public: + virtual void SetUp() { + mock_kernel_.reset(new StrictMock<KernelAPIMock>()); + mock_eventfd_notifications_.reset(MockEventFdNotifications::NewStrict()); + controller_.reset(new CpusetController(kHierarchyPath, kMountPoint, true, + mock_kernel_.get(), + mock_eventfd_notifications_.get())); + } + + protected: + unique_ptr<KernelAPIMock> mock_kernel_; + unique_ptr<CpusetController> controller_; + unique_ptr<MockEventFdNotifications> mock_eventfd_notifications_; +}; + +TEST_F(CpusetControllerTest, Type) { + EXPECT_EQ(CGROUP_CPUSET, controller_->type()); +} + +TEST_F(CpusetControllerTest, SetsCpuMask) { + const string kResFile = JoinPath(kMountPoint, KernelFiles::CPUSet::kCPUs); + CpuMask cpu_mask(0xF40FF); + string expected_cpu_string = "0-7,14,16-19"; + EXPECT_CALL(*mock_kernel_, SafeWriteResFile(expected_cpu_string, kResFile, + NotNull(), NotNull())) + .WillOnce(Return(0)); + EXPECT_OK(controller_->SetCpuMask(cpu_mask)); +} + +TEST_F(CpusetControllerTest, SetCpuMaskFails) { + const string kResFile = JoinPath(kMountPoint, KernelFiles::CPUSet::kCPUs); + CpuMask cpu_mask(0xF40FF); + string expected_cpu_string = "0-7,14,16-19"; + EXPECT_CALL(*mock_kernel_, SafeWriteResFile(expected_cpu_string, kResFile, + NotNull(), NotNull())) + .WillOnce(DoAll(SetArgPointee<3>(true), Return(0))); + EXPECT_NOT_OK(controller_->SetCpuMask(cpu_mask)); +} + +TEST_F(CpusetControllerTest, GetsCpuMask) { + const string kResFile = JoinPath(kMountPoint, KernelFiles::CPUSet::kCPUs); + EXPECT_CALL(*mock_kernel_, Access(kResFile, F_OK)) + .WillRepeatedly(Return(0)); + EXPECT_CALL(*mock_kernel_, ReadFileToString(kResFile, NotNull())) + .WillOnce(DoAll(SetArgPointee<1>("0-4,7,10,12-15"), Return(true))); + StatusOr<CpuMask> statusor = controller_->GetCpuMask(); + ASSERT_OK(statusor); + CpuMask cpu_mask = statusor.ValueOrDie(); + EXPECT_EQ(0xF49F, cpu_mask); +} + +TEST_F(CpusetControllerTest, GetCpuMaskNotFound) { + const string kResFile = JoinPath(kMountPoint, KernelFiles::CPUSet::kCPUs); + EXPECT_CALL(*mock_kernel_, Access(kResFile, F_OK)) + .WillRepeatedly(Return(1)); + EXPECT_ERROR_CODE(NOT_FOUND, controller_->GetCpuMask()); +} + +TEST_F(CpusetControllerTest, GetCpuMaskFails) { + const string kResFile = JoinPath(kMountPoint, KernelFiles::CPUSet::kCPUs); + EXPECT_CALL(*mock_kernel_, Access(kResFile, F_OK)) + .WillRepeatedly(Return(0)); + EXPECT_CALL(*mock_kernel_, ReadFileToString(kResFile, NotNull())) + .WillOnce(Return(false)); + EXPECT_NOT_OK(controller_->GetCpuMask()); +} + +TEST_F(CpusetControllerTest, SetsMemoryNodes) { + const string kResFile = JoinPath(kMountPoint, KernelFiles::CPUSet::kMemNodes); + string expected_memory_nodes_string = "0-1"; + EXPECT_CALL(*mock_kernel_, SafeWriteResFile(expected_memory_nodes_string, + kResFile, NotNull(), NotNull())) + .WillOnce(Return(0)); + ResSet memory_nodes; + memory_nodes.ReadSetString(expected_memory_nodes_string, ","); + EXPECT_OK(controller_->SetMemoryNodes(memory_nodes)); +} + +TEST_F(CpusetControllerTest, SetMemoryNodesFails) { + const string kResFile = JoinPath(kMountPoint, KernelFiles::CPUSet::kMemNodes); + string expected_memory_nodes_string = "0-1"; + EXPECT_CALL(*mock_kernel_, SafeWriteResFile(expected_memory_nodes_string, + kResFile, NotNull(), NotNull())) + .WillOnce(DoAll(SetArgPointee<3>(true), Return(0))); + ResSet memory_nodes; + memory_nodes.ReadSetString(expected_memory_nodes_string, ","); + EXPECT_NOT_OK(controller_->SetMemoryNodes(memory_nodes)); +} + +TEST_F(CpusetControllerTest, GetsMemoryNodes) { + const string kResFile = JoinPath(kMountPoint, KernelFiles::CPUSet::kMemNodes); + EXPECT_CALL(*mock_kernel_, Access(kResFile, F_OK)) + .WillRepeatedly(Return(0)); + EXPECT_CALL(*mock_kernel_, ReadFileToString(kResFile, NotNull())) + .WillOnce(DoAll(SetArgPointee<1>("0-1"), Return(true))); + StatusOr<ResSet> statusor = controller_->GetMemoryNodes(); + ASSERT_OK(statusor); + string result_string; + statusor.ValueOrDie().Format(&result_string); + EXPECT_EQ("0-1", result_string); +} + +TEST_F(CpusetControllerTest, GetMemoryNodesNotFound) { + const string kResFile = JoinPath(kMountPoint, KernelFiles::CPUSet::kMemNodes); + EXPECT_CALL(*mock_kernel_, Access(kResFile, F_OK)) + .WillRepeatedly(Return(1)); + EXPECT_ERROR_CODE(NOT_FOUND, controller_->GetMemoryNodes()); +} + +TEST_F(CpusetControllerTest, GetMemoryNodesFails) { + const string kResFile = JoinPath(kMountPoint, KernelFiles::CPUSet::kMemNodes); + EXPECT_CALL(*mock_kernel_, Access(kResFile, F_OK)) + .WillRepeatedly(Return(0)); + EXPECT_CALL(*mock_kernel_, ReadFileToString(kResFile, NotNull())) + .WillOnce(Return(false)); + EXPECT_NOT_OK(controller_->GetMemoryNodes()); +} + +} // namespace lmctfy +} // namespace containers diff --git a/pool/shard007/C++/0094543_MessagingStubFactoryTest.cpp b/pool/shard007/C++/0094543_MessagingStubFactoryTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bc619e62b2f5d2dfad36689d0b24d1e2c98f7df6 --- /dev/null +++ b/pool/shard007/C++/0094543_MessagingStubFactoryTest.cpp @@ -0,0 +1,114 @@ +/* + * #%L + * %% + * Copyright (C) 2011 - 2017 BMW Car IT GmbH + * %% + * 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. + * #L% + */ +#include <gtest/gtest.h> +#include <gmock/gmock.h> + +#include "joynr/system/RoutingTypes/Address.h" +#include "joynr/MessagingStubFactory.h" +#include "joynr/IMiddlewareMessagingStubFactory.h" + +#include "tests/utils/MockObjects.h" + +using namespace joynr; +using namespace testing; + +struct MockMiddlewareMessagingStubFactory : public joynr::IMiddlewareMessagingStubFactory { + MOCK_METHOD1(create, std::shared_ptr<joynr::IMessagingStub>(const joynr::system::RoutingTypes::Address& destAddress)); + MOCK_METHOD1(canCreate, bool(const joynr::system::RoutingTypes::Address& destAddress)); + MOCK_METHOD1(registerOnMessagingStubClosedCallback, + void(std::function<void(std::shared_ptr<const joynr::system::RoutingTypes::Address> destinationAddress)> onMessagingStubClosedCallback)); +}; + +class MessagingStubFactoryTest : public Test { +public: + MessagingStubFactoryTest() : messagingStubFactory(), expectedStub(std::make_shared<MockMessagingStub>()) + { + auto mockMiddlewareMessagingStubFactory = std::make_shared<MockMiddlewareMessagingStubFactory>(); + // retain a pointer for later use in EXPECT_CALL, unique_ptr will be moved when registering + this->mockMiddlewareMessagingStubFactory = mockMiddlewareMessagingStubFactory.get(); + ON_CALL(*(this->mockMiddlewareMessagingStubFactory), create(_)).WillByDefault(Return(expectedStub)); + ON_CALL(*(this->mockMiddlewareMessagingStubFactory), canCreate(_)).WillByDefault(Return(true)); + messagingStubFactory.registerStubFactory(mockMiddlewareMessagingStubFactory); + + std::string host = "test.domain"; + address = std::make_shared<joynr::system::RoutingTypes::WebSocketAddress>(); + address->setHost(host); + addressCopy = std::make_shared<joynr::system::RoutingTypes::WebSocketAddress>(); + addressCopy->setHost(host); + } + +protected: + MessagingStubFactory messagingStubFactory; + std::shared_ptr<MockMessagingStub> expectedStub; + std::shared_ptr<joynr::system::RoutingTypes::WebSocketAddress> address; + std::shared_ptr<joynr::system::RoutingTypes::WebSocketAddress> addressCopy; + MockMiddlewareMessagingStubFactory* mockMiddlewareMessagingStubFactory; +}; + + +TEST_F(MessagingStubFactoryTest, emptyAtBegin) +{ + EXPECT_FALSE(messagingStubFactory.contains(address)); +} + +TEST_F(MessagingStubFactoryTest, createReturnsStub) +{ + std::shared_ptr<IMessagingStub> returnedStub = messagingStubFactory.create(address); + EXPECT_EQ(expectedStub, returnedStub); +} + +TEST_F(MessagingStubFactoryTest, repeatedCreateReturnsSameStub) +{ + EXPECT_CALL(*mockMiddlewareMessagingStubFactory, create(_)).Times(1); + std::shared_ptr<IMessagingStub> stub1 = messagingStubFactory.create(address); + ASSERT_TRUE(stub1 != nullptr); + std::shared_ptr<IMessagingStub> stub2 = messagingStubFactory.create(address); + EXPECT_TRUE(stub1 == stub2); + std::shared_ptr<IMessagingStub> stub3 = messagingStubFactory.create(addressCopy); + EXPECT_TRUE(stub1 == stub3); +} + +TEST_F(MessagingStubFactoryTest, containsFindsStub) +{ + messagingStubFactory.create(address); + EXPECT_TRUE(messagingStubFactory.contains(address)); + EXPECT_TRUE(messagingStubFactory.contains(addressCopy)); +} + +TEST_F(MessagingStubFactoryTest, nullptrIsNotInsertedIntoCache) +{ + EXPECT_CALL(*(this->mockMiddlewareMessagingStubFactory), create(_)).WillOnce(Return(std::shared_ptr<IMessagingStub>())); + messagingStubFactory.create(address); + EXPECT_FALSE(messagingStubFactory.contains(address)); + EXPECT_FALSE(messagingStubFactory.contains(addressCopy)); +} + +TEST_F(MessagingStubFactoryTest, emptyAfterRemove) +{ + messagingStubFactory.create(address); + messagingStubFactory.remove(address); + EXPECT_FALSE(messagingStubFactory.contains(address)); + EXPECT_FALSE(messagingStubFactory.contains(addressCopy)); + + messagingStubFactory.create(address); + messagingStubFactory.remove(addressCopy); + EXPECT_FALSE(messagingStubFactory.contains(address)); + EXPECT_FALSE(messagingStubFactory.contains(addressCopy)); +} + diff --git a/pool/shard007/C++/0094545_usermanager.cpp b/pool/shard007/C++/0094545_usermanager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4c9937bdd41804e7968703440f4957aa741c24a3 --- /dev/null +++ b/pool/shard007/C++/0094545_usermanager.cpp @@ -0,0 +1,47 @@ + +#include "usermanager.hpp" +#include <iostream> +#include <string> +#include "superUser.hpp" +#include "commonUser.hpp" + +UserManager::UserManager() { + this->users = new list<User*>(); + this->users->push_back(new SuperUser("root", "root")); + this->users->push_back(new CommonUser("user", "user")); +} + +UserManager::UserManager(list<User*> *_users) { + this->users = _users; +} + +bool UserManager::exclude(string *usr) { + std::list<User*>::iterator it=users->begin(); + for (; it != users->end(); ++it) { + if (!(*it)->getName()->compare(*usr)) { + users->erase(it); + return true; + } + } + return false; +} + +void UserManager::create(void *usr) { + this->users->push_back((User*)usr); +} + +User *UserManager::login(string *name, string *password) { + std::list<User*>::iterator it=users->begin(); + for (; it != users->end(); ++it) { + if (!(*it)->getName()->compare(*name)) { + if ( (*it)->getAuth(password) ) { + return *it; + } + } + } + return NULL; +} + +void UserManager::save() { + // must save in a file ".users.q" +} diff --git a/pool/shard007/C++/0094548_imagesf2data.cpp b/pool/shard007/C++/0094548_imagesf2data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fd4bcbf9d6e057c7859e806849234515e9755adb --- /dev/null +++ b/pool/shard007/C++/0094548_imagesf2data.cpp @@ -0,0 +1,169 @@ +#include <OpenImageIO/imageio.h> +OIIO_NAMESPACE_USING + +// #define STB_IMAGE_IMPLEMENTATION +// #include "stb_image.h" + +#include "writeTexture.h" + +#include <iostream> +#include <cassert> +#include <algorithm> // copy() + +#include "../pythonlike.h" +using namespace pythonlike; + +namespace +{ +void usage( const char* argv0 ) +{ + std::cerr << "Usage: " << argv0 << " path/to/image1 path/to/image2 path/to/image3 ... path/to/output.data [--tiff]" << std::endl; +} +} + +int main( int argc, char* argv[] ) { + assert( argc >= 1 ); + + std::vector<std::string> args( argv + 1, argv + argc ); + const bool is_tiff = pythonlike::get_optional_parameter( args, "--tiff" ); + + if( args.size() < 2 ) { + usage( argv[0] ); + return -1; + } + + const std::string outpath( args.back() ); + args.pop_back(); + + // The remaining arguments are the image names. + const auto& image_names = args; + assert( image_names.size() >= 1 ); + + if( is_tiff && image_names.size() > 1 ) { + std::cerr << "When converting an RGB TIFF (the --tiff flag), there must only be one image." << std::endl; + usage( argv[0] ); + return -1; + } + + // Read the input. + int num_channels = -1; + int width = -1; + int height = -1; + std::vector< float > data; + if( !is_tiff ) { + + num_channels = image_names.size(); + + int index = -1; + for( const auto& name : image_names ) { + index += 1; + + std::cout << "Loading: " << name << std::endl; + + // OpenImageIO documentation PDF Section 4.1 Image Input Made Simple + ImageInput *in = ImageInput::open( name ); + if( !in ) { + std::cerr << "ERROR: Image " << index << " could not be loaded: " << name << std::endl; + exit(-1); + } + const ImageSpec &spec = in->spec(); + int xres = spec.width; + int yres = spec.height; + int channels = spec.nchannels; + std::vector<float> image(xres*yres*channels); + in->read_image( TypeDesc::FLOAT, &image[0] ); + in->close(); +#if OIIO_VERSION_MAJOR >= 1 && OIIO_VERSION_MINOR >= 6 + ImageInput::destroy(in); +#else + delete in; +#endif + + // Warn if the image has more than 1 channel. + std::cout << "channels: " << channels << std::endl; + if( 1 != channels ) { + std::cerr << "Warning: Image has more than 1 channel. Using only the first channel: " << name << std::endl; + } + + // Allocate space when we load the first image and learn the dimensions. + if( data.empty() ) { + assert( -1 == width && -1 == height ); + width = xres; + height = yres; + assert( num_channels > 0 ); + data.resize( width*height*num_channels ); + } + + // All images must have the same dimensions. + if( xres != width || yres != height ) { + std::cerr << "ERROR: Image " << index << " does not have the same dimensions as its predecessors: " << name << std::endl; + exit(-1); + } + + // Copy the data. We don't have to worry about dividing by 255, + // because (a) these are floating point images and (b) we will normalize. + for( int i = 0; i < width*height; ++i ) { + data[ index*width*height + i ] = image[i]; + } + } + } + else + { + assert( image_names.size() == 1 ); + auto name = image_names.front(); + + std::cout << "Loading: " << name << std::endl; + + // OpenImageIO documentation PDF Section 4.1 Image Input Made Simple + ImageInput *in = ImageInput::open( name ); + if( !in ) { + std::cerr << "ERROR: Image '" << name << "' could not be loaded: " << name << std::endl; + exit(-1); + } + const ImageSpec &spec = in->spec(); + int xres = spec.width; + int yres = spec.height; + int channels = spec.nchannels; + std::vector<float> image(xres*yres*channels); + in->read_image( TypeDesc::FLOAT, &image[0] ); + in->close(); +#if OIIO_VERSION_MAJOR >= 1 && OIIO_VERSION_MINOR >= 6 + ImageInput::destroy(in); +#else + delete in; +#endif + + std::cout << "# channels: " << channels << std::endl; + if( 3 > channels ) { + std::cerr << "ERROR: Image does not have 3 channels yet --tiff flag was passed: " << name << std::endl; + return -1; + } + + width = xres; + height = yres; + num_channels = 3; + + data.resize( channels*width*height ); + for( int i=0; i<width; ++i ) { + for( int j=0; j<height; ++j ) { + for( int n=0; n<num_channels; ++n ) { + data[ n*width*height + j*width + i ] = image[ j*width*channels + i*channels + n ]; + } + } + } + // This might be doing a memcpy(), because I get bogus data. + // std::copy( data + index*width*height, data + (index+1)*width*height, image ); + } + + assert( !data.empty() ); + + // Normalize data. Divide each row,col by the sum of values in all channels. + // UPDATE: No. Our floating point image format is a lossless conversion (bit exact). + // We only normalized 8-bit image loading, because that is lossy and leads to + // denormalization. + + // Save the output. + hrw::save_framebuffer_to_disk( outpath, data.data(), width, height, num_channels ); + + return 0; +} diff --git a/pool/shard007/C++/0094549_hdfs_builder_test.cc b/pool/shard007/C++/0094549_hdfs_builder_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..147cfee6be82c67cb4d0848fada0d90bca050e36 --- /dev/null +++ b/pool/shard007/C++/0094549_hdfs_builder_test.cc @@ -0,0 +1,137 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hdfspp/hdfs_ext.h" +#include "configuration_test.h" +#include <gmock/gmock.h> +#include <google/protobuf/stubs/common.h> + +using ::testing::_; + +using namespace hdfs; + +TEST(HdfsBuilderTest, TestStubBuilder) { + { + TempDir tempDir1; + + hdfsBuilder * builder = hdfsNewBuilderFromDirectory(tempDir1.path.c_str()); + hdfsFreeBuilder(builder); + } + + { + hdfsBuilder * builder = hdfsNewBuilderFromDirectory("/this/path/does/not/exist"); + hdfsFreeBuilder(builder); + } +} + +TEST(HdfsBuilderTest, TestRead) +{ + // Reading string values + { + TempDir tempDir1; + TempFile tempFile1(tempDir1.path + "/core-site.xml"); + writeSimpleConfig(tempFile1.GetFileName(), "key1", "value1"); + + hdfsBuilder * builder = hdfsNewBuilderFromDirectory(tempDir1.path.c_str()); + + char * readVal = nullptr; + int result = hdfsBuilderConfGetStr(builder, "key1", &readVal); + ASSERT_EQ(0, result); + ASSERT_NE(nullptr, readVal); + EXPECT_EQ("value1", std::string(readVal)); + hdfsConfStrFree(readVal); + + readVal = nullptr; + result = hdfsBuilderConfGetStr(builder, "key2", &readVal); + ASSERT_EQ(0, result); + EXPECT_EQ(nullptr, readVal); + + hdfsFreeBuilder(builder); + } + + // Reading int values + { + TempDir tempDir1; + TempFile tempFile1(tempDir1.path + "/core-site.xml"); + writeSimpleConfig(tempFile1.GetFileName(), "key1", "100"); + + hdfsBuilder * builder = hdfsNewBuilderFromDirectory(tempDir1.path.c_str()); + + int readVal = -1; + int result = hdfsBuilderConfGetInt(builder, "key1", &readVal); + EXPECT_EQ(0, result); + EXPECT_EQ(100, readVal); + + readVal = -1; + result = hdfsBuilderConfGetInt(builder, "key2", &readVal); + EXPECT_EQ(0, result); + EXPECT_EQ(-1, readVal); + + hdfsFreeBuilder(builder); + } +} + +TEST(HdfsBuilderTest, TestSet) +{ + { + // Setting values in an empty builder + // Don't use default, or it will load any data in /etc/hadoop + hdfsBuilder * builder = hdfsNewBuilderFromDirectory("/this/path/does/not/exist"); + + int result = hdfsBuilderConfSetStr(builder, "key1", "100"); + EXPECT_EQ(0, result); + + int readVal = -1; + result = hdfsBuilderConfGetInt(builder, "key1", &readVal); + EXPECT_EQ(0, result); + EXPECT_EQ(100, readVal); + + // Set value in non-empty builder + result = hdfsBuilderConfSetStr(builder, "key2", "200"); + EXPECT_EQ(0, result); + + readVal = -1; + result = hdfsBuilderConfGetInt(builder, "key2", &readVal); + EXPECT_EQ(0, result); + EXPECT_EQ(200, readVal); + + // Overwrite value + result = hdfsBuilderConfSetStr(builder, "key2", "300"); + EXPECT_EQ(0, result); + + readVal = -1; + result = hdfsBuilderConfGetInt(builder, "key2", &readVal); + EXPECT_EQ(0, result); + EXPECT_EQ(300, readVal); + + hdfsFreeBuilder(builder); + } +} + +int main(int argc, char *argv[]) { + /* + * The following line must be executed to initialize Google Mock + * (and Google Test) before running the tests. + */ + ::testing::InitGoogleMock(&argc, argv); + int exit_code = RUN_ALL_TESTS(); + + // Clean up static data and prevent valgrind memory leaks + google::protobuf::ShutdownProtobufLibrary(); + return exit_code; +} diff --git a/pool/shard007/C++/0094551_qkbdnitpicker_qws.cpp b/pool/shard007/C++/0094551_qkbdnitpicker_qws.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fee7d42d6ac11ce36d50f535de5039947c71e68f --- /dev/null +++ b/pool/shard007/C++/0094551_qkbdnitpicker_qws.cpp @@ -0,0 +1,73 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial Usage +** Licensees holding valid Qt Commercial licenses may use this file in +** accordance with the Qt Commercial License Agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Nokia. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qkbdnitpicker_qws.h" + +#ifndef QT_NO_QWS_KEYBOARD +#ifndef QT_NO_QWS_KBD_NITPICKER + +#include <qdebug.h> +#include <qwindowsystem_qws.h> + +QNitpickerKeyboardHandler::QNitpickerKeyboardHandler(const QString &device) + : QWSPC101KeyboardHandler(device) +{ +} + +QNitpickerKeyboardHandler::~QNitpickerKeyboardHandler() +{ +} + +void QNitpickerKeyboardHandler::processKeyEvent(Input::Event *ev) +{ +// qDebug() << "processKeyEvent(): keycode ==" << ev->keycode(); + + int keycode = ev->keycode(); + + if (ev->type() == Input::Event::RELEASE) { + keycode |= 0x80; + } + + doKey(keycode); +} + +#endif // QT_NO_QWS_KBD_NITPICKER +#endif // QT_NO_QWS_KEYBOARD diff --git a/pool/shard007/C++/0094555_SaveData.cpp b/pool/shard007/C++/0094555_SaveData.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b5197210035059b2f3f5ce26507523192b782223 --- /dev/null +++ b/pool/shard007/C++/0094555_SaveData.cpp @@ -0,0 +1,159 @@ +/* +SaveData: + データを保存するためのライブラリ。 + 保存対象のデバイスに依存せずデータを保存することを目的とする。 + + なお現時点では、ATMEGA328Pの内蔵EEPROM(1KByte)に保存する。 + +The MIT License (MIT) + +Copyright (c) 2015 Uematsu Electric Co.,Ltd. Toru OHTSUKA <t-ohtsuka@jupiter.ocn.ne.jp> + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +#include "SaveData.h" +#include "EEPROM.h" + +#define DEBUG +#ifdef DEBUG +#include "DigiUSB.h" +#define DBG_PRINT(...) DigiUSB.print(__VA_ARGS__) +#endif + +extern EEPROMClass EEPROM; + +#define EEPROM_MAX_328P 1000 +#define EEPROM_MAX_328P_SAVE2BYTE (1000/2) + +/****************************************************************************/ +void EEPROM_clear() { + int i; + + for(i=0; i<EEPROM_MAX_328P; i++) { + EEPROM.write(i , 0) ; + } +} + +/****************************************************************************/ +int EEPROM_save2byte(unsigned short address, unsigned short data) { + byte upper8bit,lower8bit; + lower8bit = data & 0x00FF; // 下位8bitのみ取得 + upper8bit = (data >> 8) & 0xFF; // 上位8bitのみ取得 + + if(address >= EEPROM_MAX_328P_SAVE2BYTE) { // 範囲外アクセス防止 + return -1; + } + +#if 0 + DBG_PRINT("EEPROM_save2byte:"); + DBG_PRINT("L8:"); + DBG_PRINT(lower8bit, DEC); + DBG_PRINT(",H8:"); + DBG_PRINT(upper8bit, DEC); +#endif + + EEPROM.write(address*2, lower8bit); + EEPROM.write(address*2+1, upper8bit); + + return 0; +} + +/****************************************************************************/ +int EEPROM_load2byte(unsigned short address, unsigned short *data) { + unsigned short upper8bit,lower8bit; + + if(address >= EEPROM_MAX_328P_SAVE2BYTE) { // 範囲外アクセス防止 + return -1; + } + + lower8bit = EEPROM.read(address*2); + upper8bit = EEPROM.read(address*2+1); + +#if 0 + DBG_PRINT("EEPROM_load2byte:"); + DBG_PRINT("READ lower8bit:"); + DBG_PRINT(lower8bit, DEC); + DBG_PRINT(", upper8bit:"); + DBG_PRINT(upper8bit, DEC); + DBG_PRINT("\r\n"); +#endif + + *data = (upper8bit << 8) + lower8bit; + + return 0; +} + +/****************************************************************************/ +SaveDataClass::SaveDataClass(void) +{ + EEPROM_load2byte(0, &count); +} + +/****************************************************************************/ +void SaveDataClass::clear(void) +{ + EEPROM_clear(); + count = 0; +} + +/****************************************************************************/ +void SaveDataClass::init(void) +{ + int ret; + ret = EEPROM_load2byte(0, &count); +} +/****************************************************************************/ +unsigned short SaveDataClass::get_count(void) { + return count; +} + +/****************************************************************************/ +int SaveDataClass::save_2byte(unsigned short address, unsigned short data) { + + return EEPROM_save2byte(address, data); +} + +/****************************************************************************/ +int SaveDataClass::load_2byte(unsigned short address, unsigned short *pdata) { + + return EEPROM_load2byte(address, pdata); +} + +/****************************************************************************/ +int SaveDataClass::add_2byte(unsigned short data) { + + // カウンタの更新と保存 + if(count+1 < EEPROM_MAX_328P_SAVE2BYTE) { + EEPROM_save2byte(count+1, data); // 先頭2byteは管理領域。スキップするため +1 する + + count++; + DBG_PRINT("add_2byte:"); + DBG_PRINT(count, DEC); + DBG_PRINT("\r\n"); + EEPROM_save2byte(0, count); + + return 0; + } else { + return -1; + } +} + +SaveDataClass SaveData; + diff --git a/pool/shard007/C++/0094557_ProtectionHandler.cpp b/pool/shard007/C++/0094557_ProtectionHandler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..da7e9efabd7468da423ce61751d4a73c43edf513 --- /dev/null +++ b/pool/shard007/C++/0094557_ProtectionHandler.cpp @@ -0,0 +1,153 @@ +/* + * Copyright 2015 Facebook, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include <thrift/lib/cpp2/async/ProtectionHandler.h> +#include <thrift/lib/cpp/transport/TTransportException.h> +#include <folly/Logging.h> + +namespace apache { namespace thrift { + +void ProtectionHandler::read(Context* ctx, folly::IOBufQueue& q) { + if (&inputQueue_ != &q) { + // If not the same queue + inputQueue_.append(q); + } + + auto e = folly::try_and_catch<std::exception>([&]() { + while (!closing_) { + if (protectionState_ == ProtectionState::INVALID) { + throw transport::TTransportException("protection state is invalid"); + } + + if (protectionState_ == ProtectionState::INPROGRESS) { + // security is still doing stuff, let's return blank. + break; + } + + if (protectionState_ != ProtectionState::VALID) { + // not an encrypted message, so pass-through + ctx->fireRead(inputQueue_); + break; + } + + assert(saslEndpoint_ != nullptr); + size_t remaining = 0; + + if (!inputQueue_.front() || inputQueue_.front()->empty()) { + break; + } + + std::unique_ptr<folly::IOBuf> unwrapped; + // If this is the first message after protection state was set to valid, + // allow the ability to fall back to plaintext. + if (allowFallback_) { + if (inputQueue_.chainLength() < 6) { + // 4 for frame length + 2 for header magic 0x0fff + // If less than that, continue buffering + break; + } + folly::io::Cursor c(inputQueue_.front()); + if (c.readBE<uint32_t>() >= 2 && c.readBE<uint16_t>() == 0x0fff) { + // Frame length is at least 2 and first 2 bytes are the header + // magic 0x0fff. This is potentially a plaintext message on an + // encrypted channel because the client timed out and fallen back. + // Make a copy of inputQueue_. + // If decryption fails, we try to read again without decrypting. + // The copy is necessary since a decryption attempt modifies the + // queue. + folly::IOBufQueue inputQueueCopy; + auto copyBuf = inputQueue_.front()->clone(); + copyBuf->unshare(); + inputQueueCopy.append(std::move(copyBuf)); + + // decrypt inputQueue_ + auto decryptEx = folly::try_and_catch<std::exception>([&]() { + unwrapped = saslEndpoint_->unwrap(&inputQueue_, &remaining); + }); + + if (remaining == 0) { + // If we got an entire frame, make sure we try the fallback + // only once. If we only got a partial frame, we have to try + // falling back again until we get the full first frame. + allowFallback_ = false; + } + + if (decryptEx) { + // If decrypt fails, try reading again without decrypting. This + // allows a fallback to happen if the timeout happened in the last + // leg of the handshake. + inputQueue_ = std::move(inputQueueCopy); + ctx->fireRead(inputQueue_); + break; + } + } else { + // This is definitely not a plaintext header message. We can try + // decrypting without a copy. unwrap() will handle buffering if + // we only received a chunk. + allowFallback_ = false; + unwrapped = saslEndpoint_->unwrap(&inputQueue_, &remaining); + } + } else { + unwrapped = saslEndpoint_->unwrap(&inputQueue_, &remaining); + } + + assert(bool(unwrapped) ^ (remaining > 0)); // 1 and only 1 should be true + if (unwrapped) { + queue_.append(std::move(unwrapped)); + ctx->fireRead(queue_); + } else { + break; + } + } + }); + if (e) { + FB_LOG_EVERY_MS(ERROR, 1000) + << "Exception in ProtectionHandler::read(): " << e.what(); + ctx->fireReadException(std::move(e)); + } + // Give ownership back to the main queue if we're not in the inprogress + // state + if (&inputQueue_ != &q && + protectionState_ != ProtectionState::INPROGRESS) { + q.append(inputQueue_); + } +} + +folly::Future<folly::Unit> ProtectionHandler::write( + Context* ctx, + std::unique_ptr<folly::IOBuf> buf) { + if (protectionState_ == ProtectionState::VALID) { + assert(saslEndpoint_); + buf = saslEndpoint_->wrap(std::move(buf)); + } + return ctx->fireWrite(std::move(buf)); +} + + +void ProtectionHandler::protectionStateChanged() { + // We only want to do this callback in the case where we're switching + // to a valid protection state. + if (getContext() && !inputQueue_.empty() && + protectionState_ == ProtectionState::VALID) { + read(getContext(), inputQueue_); + } +} + +folly::Future<folly::Unit> ProtectionHandler::close(Context* ctx) { + closing_ = true; + return ctx->fireClose(); +} + +}} diff --git a/pool/shard007/C++/0094560_CProxyDirectInput8.cpp b/pool/shard007/C++/0094560_CProxyDirectInput8.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f775cb8b9a85bd7e308c7bd134c681b3a44ce664 --- /dev/null +++ b/pool/shard007/C++/0094560_CProxyDirectInput8.cpp @@ -0,0 +1,121 @@ +/***************************************************************************** +* +* PROJECT: Multi Theft Auto v1.0 +* LICENSE: See LICENSE in the top level directory +* FILE: core/CProxyDirectInput8.cpp +* PURPOSE: DirectInput 8 function hooking proxy +* DEVELOPERS: Derek Abdine <> +* +* Multi Theft Auto is available from http://www.multitheftauto.com/ +* +*****************************************************************************/ + +#include "StdInc.h" + +CProxyDirectInput8::CProxyDirectInput8 ( IDirectInput8* pDevice ) +{ + WriteDebugEvent ( "CProxyDirectInput8::CProxyDirectInput8" ); + + // Initalize our local variable. + m_pDevice = pDevice; + m_dwRefCount = 0; +} + +CProxyDirectInput8::~CProxyDirectInput8 ( ) +{ + WriteDebugEvent ( "CProxyDirectInput8::~CProxyDirectInput8" ); +} + +/*** IUnknown methods ***/ +HRESULT CProxyDirectInput8::QueryInterface ( REFIID riid, LPVOID * ppvObj ) +{ + return m_pDevice->QueryInterface ( riid, ppvObj ); +} + +ULONG CProxyDirectInput8::AddRef ( VOID ) +{ + // Incrase our refcount + m_dwRefCount++; + + return m_pDevice->AddRef ( ); +} + +ULONG CProxyDirectInput8::Release ( VOID ) +{ + ULONG ulRefCount; + IUnknown * pDestroyedDevice; + + // Determine if we should self destruct + if ( m_dwRefCount-- == 0 ) + { + WriteDebugEvent ( "Releasing IDirectInput8 Proxy..." ); + + // Save device so we can destroy it after. + pDestroyedDevice = m_pDevice; + + delete this; + + // Call the release routine and get the refcount. + ulRefCount = pDestroyedDevice->Release ( ); + + return ulRefCount; + } + + // Call the release routine and get the refcount. + ulRefCount = m_pDevice->Release ( ); + + return ulRefCount; +} + +/*** IDirectInput8A methods ***/ +HRESULT CProxyDirectInput8::CreateDevice ( REFGUID a, LPDIRECTINPUTDEVICE8A *b, LPUNKNOWN c ) +{ + HRESULT hResult; + + // Create the new IDirect3DDevice8 object. + hResult = m_pDevice->CreateDevice ( a, b, c ); + + // Make sure CreateDevice returned a valid object. + if ( hResult == DI_OK ) + { + // Object created; feed the application our proxy interface. + *b = new CProxyDirectInputDevice8 ( *b ); + } + + return hResult; +} + +HRESULT CProxyDirectInput8::EnumDevices ( DWORD a, LPDIENUMDEVICESCALLBACKA b, LPVOID c, DWORD d ) +{ + return m_pDevice->EnumDevices ( a, b, c, d ); +} + +HRESULT CProxyDirectInput8::GetDeviceStatus ( REFGUID a ) +{ + return m_pDevice->GetDeviceStatus ( a ); +} + +HRESULT CProxyDirectInput8::RunControlPanel ( HWND a, DWORD b ) +{ + return m_pDevice->RunControlPanel ( a, b ); +} + +HRESULT CProxyDirectInput8::Initialize ( HINSTANCE a, DWORD b ) +{ + return m_pDevice->Initialize ( a, b ); +} + +HRESULT CProxyDirectInput8::FindDevice ( REFGUID a, LPCSTR b, LPGUID c ) +{ + return m_pDevice->FindDevice ( a, b, c ); +} + +HRESULT CProxyDirectInput8::EnumDevicesBySemantics ( LPCSTR a, LPDIACTIONFORMATA b, LPDIENUMDEVICESBYSEMANTICSCBA c, LPVOID d, DWORD e ) +{ + return m_pDevice->EnumDevicesBySemantics ( a, b, c, d, e ); +} + +HRESULT CProxyDirectInput8::ConfigureDevices ( LPDICONFIGUREDEVICESCALLBACK a, LPDICONFIGUREDEVICESPARAMSA b, DWORD c, LPVOID d ) +{ + return m_pDevice->ConfigureDevices ( a, b, c, d ); +} \ No newline at end of file diff --git a/pool/shard007/C++/0094562_DVDSubtitleParserSSA.cpp b/pool/shard007/C++/0094562_DVDSubtitleParserSSA.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5f960153dda895f4372ab80d607e4824f846f76d --- /dev/null +++ b/pool/shard007/C++/0094562_DVDSubtitleParserSSA.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2005-2012 Team XBMC + * http://www.xbmc.org + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XBMC; see the file COPYING. If not, see + * <http://www.gnu.org/licenses/>. + * + */ + +#include "DVDSubtitleParserSSA.h" +#include "DVDCodecs/Overlay/DVDOverlaySSA.h" +#include "DVDClock.h" +#include "utils/log.h" + +CDVDSubtitleParserSSA::CDVDSubtitleParserSSA(CDVDSubtitleStream* pStream, const std::string& strFile) + : CDVDSubtitleParserText(pStream, strFile) +{ + m_libass = new CDVDSubtitlesLibass(); +} + +CDVDSubtitleParserSSA::~CDVDSubtitleParserSSA() +{ + Dispose(); +} + +bool CDVDSubtitleParserSSA::Open(CDVDStreamInfo &hints) +{ + + if (!CDVDSubtitleParserText::Open()) + return false; + + std::string buffer = m_pStream->m_stringstream.str(); + if(!m_libass->CreateTrack((char*) buffer.c_str(), buffer.length())) + return false; + + //Creating the overlays by going through the list of ass_events + ASS_Event* assEvent = m_libass->GetEvents(); + int numEvents = m_libass->GetNrOfEvents(); + + for(int i=0; i < numEvents; i++) + { + ASS_Event* curEvent = (assEvent+i); + if (curEvent) + { + CDVDOverlaySSA* overlay = new CDVDOverlaySSA(m_libass); + overlay->Acquire(); // increase ref count with one so that we can hold a handle to this overlay + + overlay->iPTSStartTime = (double)curEvent->Start * (DVD_TIME_BASE / 1000); + overlay->iPTSStopTime = (double)(curEvent->Start + curEvent->Duration) * (DVD_TIME_BASE / 1000); + + overlay->replace = true; + m_collection.Add(overlay); + } + } + m_collection.Sort(); + return true; +} + +void CDVDSubtitleParserSSA::Dispose() +{ + if(m_libass) + { + SAFE_RELEASE(m_libass); + CLog::Log(LOGINFO, "SSA Parser: Releasing reference to ASS Library"); + } + CDVDSubtitleParserCollection::Dispose(); +} diff --git a/pool/shard007/C++/0094566_Resonate.cpp b/pool/shard007/C++/0094566_Resonate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7627d40a7e373f2e4cacabaf4645cb99569469b0 --- /dev/null +++ b/pool/shard007/C++/0094566_Resonate.cpp @@ -0,0 +1,113 @@ +/***************************************************/ +/*! \class Resonate + \brief STK noise driven formant filter. + + This instrument contains a noise source, which + excites a biquad resonance filter, with volume + controlled by an ADSR. + + Control Change Numbers: + - Resonance Frequency (0-Nyquist) = 2 + - Pole Radii = 4 + - Notch Frequency (0-Nyquist) = 11 + - Zero Radii = 1 + - Envelope Gain = 128 + + by Perry R. Cook and Gary P. Scavone, 1995-2012. +*/ +/***************************************************/ + +#include "Resonate.h" +#include "SKINI.msg" + +namespace stk { + +Resonate :: Resonate( void ) +{ + poleFrequency_ = 4000.0; + poleRadius_ = 0.95; + // Set the filter parameters. + filter_.setResonance( poleFrequency_, poleRadius_, true ); + zeroFrequency_ = 0.0; + zeroRadius_ = 0.0; +} + +Resonate :: ~Resonate( void ) +{ +} + +void Resonate :: noteOn( StkFloat frequency, StkFloat amplitude ) +{ + adsr_.setTarget( amplitude ); + this->keyOn(); + this->setResonance( frequency, poleRadius_ ); +} + +void Resonate :: noteOff( StkFloat amplitude ) +{ + this->keyOff(); +} + +void Resonate :: setResonance( StkFloat frequency, StkFloat radius ) +{ + if ( frequency < 0.0 ) { + oStream_ << "Resonate::setResonance: frequency parameter is less than zero!"; + handleError( StkError::WARNING ); return; + } + + if ( radius < 0.0 || radius >= 1.0 ) { + std::cerr << "Resonate::setResonance: radius parameter is out of range!"; + handleError( StkError::WARNING ); return; + } + + poleFrequency_ = frequency; + poleRadius_ = radius; + filter_.setResonance( poleFrequency_, poleRadius_, true ); +} + +void Resonate :: setNotch( StkFloat frequency, StkFloat radius ) +{ + if ( frequency < 0.0 ) { + oStream_ << "Resonate::setNotch: frequency parameter is less than zero ... setting to 0.0!"; + handleError( StkError::WARNING ); return; + } + + if ( radius < 0.0 ) { + oStream_ << "Resonate::setNotch: radius parameter is less than 0.0!"; + handleError( StkError::WARNING ); return; + } + + zeroFrequency_ = frequency; + zeroRadius_ = radius; + filter_.setNotch( zeroFrequency_, zeroRadius_ ); +} + +void Resonate :: controlChange( int number, StkFloat value ) +{ +#if defined(_STK_DEBUG_) + if ( Stk::inRange( value, 0.0, 128.0 ) == false ) { + oStream_ << "Resonate::controlChange: value (" << value << ") is out of range!"; + handleError( StkError::WARNING ); return; + } +#endif + + StkFloat normalizedValue = value * ONE_OVER_128; + if (number == 2) // 2 + setResonance( normalizedValue * Stk::sampleRate() * 0.5, poleRadius_ ); + else if (number == 4) // 4 + setResonance( poleFrequency_, normalizedValue * 0.9999 ); + else if (number == 11) // 11 + this->setNotch( normalizedValue * Stk::sampleRate() * 0.5, zeroRadius_ ); + else if (number == 1) + this->setNotch( zeroFrequency_, normalizedValue ); + else if (number == __SK_AfterTouch_Cont_) // 128 + adsr_.setTarget( normalizedValue ); +#if defined(_STK_DEBUG_) + else { + oStream_ << "Resonate::controlChange: undefined control number (" << number << ")!"; + handleError( StkError::WARNING ); + } +#endif +} + +} // stk namespace diff --git a/pool/shard007/C++/0094573_Subgraph.cpp b/pool/shard007/C++/0094573_Subgraph.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dc599d0d3c851e29e69b34570e59c3c9ac6310c7 --- /dev/null +++ b/pool/shard007/C++/0094573_Subgraph.cpp @@ -0,0 +1,222 @@ +/** + Superbubbles + Copyright (C) 2016 Ritu Kundu, Fatima Vayani, Manal Mohamed, Solon P. Pissis + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +**/ + +/** Implements class Subraph + */ +#include "Subgraph.hpp" + +namespace supbub{ + + Subgraph::Subgraph(int64_t n):Graph(n) { + //super(); + _reverseMapId = new int64_t[_numVertices]; + std::fill_n(_reverseMapId, _numVertices, -1); // set to -1 + _offSet = n-2; + _dag = nullptr; + _discovery = nullptr; + _finish = nullptr; + + } + + Subgraph::~Subgraph() { + delete[] _reverseMapId; + if (_dag != nullptr) { + delete _dag; + delete[] _discovery; + delete[] _finish; + } + } + + int64_t + Subgraph::getGlobalId(int64_t v){ + if (v < _numVertices && v >=0 ) { + return _reverseMapId[v]; + } else { + log("Invalid v : ", v); + return -1; + } + } + + void + Subgraph::setGlobalId(int64_t localId, int64_t globalId){ + if (localId <_numVertices && localId >=0 ) { + _reverseMapId[localId] = globalId; + } else { + log("Invalid localId : ", localId); + } + } + + int64_t + Subgraph::getSourceId(){ + return _numVertices-2; // second last vertex + } + + int64_t + Subgraph::getTerminalId(){ + return _numVertices-1; // last vertex + } + + int64_t + Subgraph::getDuplicateId(int64_t v){ + if (v < _numVertices && v >=0 ) { + return v + _offSet; + } else { + log("Invalid v : ", v); + return -1; + } + } + + int64_t + Subgraph::getOriginalId(int64_t v){ + if (v < 2*_offSet && v >= _offSet ) { + return v - _offSet; + } else { + log("Invalid v'' : ", v); + return -1; + } + } + + bool + Subgraph::isDuplicateId(int64_t v){ + if (v < _numVertices && v >=0 ) { + return !(v < _offSet); + } else { + log("Invalid v : ", v); + return false; + } + } + + bool + Subgraph::isAncestor(int64_t anc, int64_t des){ + if (anc < _numVertices && anc >=0 && des < _numVertices && des > 0) { + if (_dag != nullptr) { + return (_discovery[des] > _discovery[anc] && _finish[des] < _finish[anc]); + } else { + log("DFS Traversal not made yet. Call getDAG() before making call to this function.", 0); + return false; + } + } else { + log("Invalid ancestor or descendent id : ", anc, des); + return false; + } + } + + int64_t Subgraph::getOffset(){ + return _offSet; + } + + + DAG* + Subgraph::getDAG(){ + _dag = new DAG(2*_offSet + 2); + _discovery = new int64_t[_numVertices]; + _finish = new int64_t[_numVertices]; + int64_t_LIST_ITERATOR i; + int64_t newSource = _dag->getSourceId(); + int64_t thisSource = getSourceId(); + int64_t newTerminal = _dag->getTerminalId(); + int64_t thisTerminal = getTerminalId(); + + + /* Add {(r, v' ) | (r, v) ∈ E(G)} */ + if (! _adjList[thisSource].empty()) { + for (i = _adjList[thisSource].begin(); i != _adjList[thisSource].end(); ++i) { + if (*i != thisTerminal) { + _dag->addEdge(newSource, *i); // as v and v' have same local-id + } + } + } + + /* Add {(v'' , r' ) | (v, r' ) ∈ E(G)} */ + if (! _parentList[thisTerminal].empty()) { + for (i = _parentList[thisTerminal].begin(); i != _parentList[thisTerminal].end(); ++i) { + if (*i != thisSource) { + _dag->addEdge(getDuplicateId(*i), newTerminal); + } + } + } + + /* Add {(u', v'), (u'', v'') |(u, v) ∈ E(G), (u, v) is not a back edge } and {(u', v'') | (u, v) ∈ E(G), (u, v) is a back edge} */ + int64_t source = thisSource; + if (_outDegree[thisSource] == 0) { // no source r, select a random vertex to be source/root + source = 0; // 0 is chosen + } + Subgraph::Color* color = new Subgraph::Color[_numVertices]; + std::fill_n( color, _numVertices, WHITE ); // set to false + DFSVisit(source, 0, color); + + /* Adjust source and terminal vertices */ + int64_t lastDAGID = _dag->numVertices()-2; + if (_outDegree[thisSource] == 0) { // G does not contain r + for (int64_t u=0; u < lastDAGID; ++u) { + if (_dag->getInDegree(u) == 0) { // for every u ∈ V (G ) such that u has no incoming edge in G' + _dag->addEdge(newSource, u);//create an edge (r, u) + } + } + } + if (_inDegree[thisTerminal] == 0) { // G does not contain r' + for (int64_t u=0; u < lastDAGID; ++u) { + if (_dag->getOutDegree(u) == 0) { // for every u ∈ V (G ) such that u has no outgoing edge in G' + _dag->addEdge(u, newTerminal);//create an edge (u, r') + } + } + } + //clean-up + delete[] color; + + return _dag; + } + + + //////////////////////// private //////////////////////// + + + void + Subgraph::DFSVisit(int64_t u, int64_t& tick, Subgraph::Color* color){ + color[u] = GRAY; + _discovery[u] = ++tick; + int64_t_LIST_ITERATOR i; + int64_t thisSource = getSourceId(); + int64_t thisTERMINAL = getTerminalId(); + if (! _adjList[u].empty()) { + for (i = _adjList[u].begin(); i != _adjList[u].end(); ++i) { + int64_t v = *i; + if (color[v] == WHITE){ // u-v is tree-edge + if (v != thisTERMINAL && u!= thisTERMINAL && v!=thisSource && u!=thisSource) { + _dag->addEdge(u, v); // add u'-v' + _dag->addEdge(getDuplicateId(u), getDuplicateId(v)); // add u''-v'' + } + DFSVisit(v, tick, color); + } + else if (color[v] == GRAY) { // u-v is back edge + if (v != thisTERMINAL && u!= thisTERMINAL && v!=thisSource && u!=thisSource) { + _dag->addEdge(u, getDuplicateId(v)); // add u'-v'' + } + } + else{// forward or cross edge + if (v != thisTERMINAL && u!= thisTERMINAL && v!=thisSource && u!=thisSource) { + _dag->addEdge(u, v); // add u'-v' + _dag->addEdge(getDuplicateId(u), getDuplicateId(v)); // add u''-v'' + } + } + } + } + color[u] = BLACK; + _finish[u] = ++tick; + } + + +}// end namespace + diff --git a/pool/shard007/C++/0094574_extract_boundary_mesh_01.cc b/pool/shard007/C++/0094574_extract_boundary_mesh_01.cc new file mode 100644 index 0000000000000000000000000000000000000000..a6d41772d20d14684027471fb005b30011d64532 --- /dev/null +++ b/pool/shard007/C++/0094574_extract_boundary_mesh_01.cc @@ -0,0 +1,128 @@ +// --------------------------------------------------------------------- +// +// Copyright (C) 2010 - 2013 by the deal.II authors +// +// This file is part of the deal.II library. +// +// The deal.II library is free software; you can use it, redistribute +// it, and/or modify it under the terms of the GNU Lesser General +// Public License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// The full text of the license can be found in the file LICENSE at +// the top level of the deal.II distribution. +// +// --------------------------------------------------------------------- + + +/* + Code for testing the function + GridGenerator::extract_boundary_mesh (...). + We test that the order of cells and the orientation + of the vertices is consistent between the two meshes. + + Compared to the _00 test, we here test things with the surface of a + 3d sphere. There is no surface object attached, so the surface is + topologically a sphere but not geometrically. The _02 test checks the + same with a boundary object attached. +*/ + +#include "../tests.h" + +#include <deal.II/grid/tria.h> +#include <deal.II/grid/grid_generator.h> +#include <deal.II/grid/tria_boundary_lib.h> +#include <deal.II/grid/grid_out.h> +#include <deal.II/grid/grid_tools.h> + +using namespace std; + + +template <int s_dim, int spacedim> +bool test_vertices_orientation(const Triangulation<s_dim,spacedim> &boundary_mesh, + map< typename Triangulation<s_dim,spacedim>::cell_iterator, + typename Triangulation<s_dim+1,spacedim>::face_iterator > + &surface_to_volume_mapping, + const int verbosity = 1) +{ + typename Triangulation<s_dim,spacedim>::active_cell_iterator + cell = boundary_mesh.begin_active(), + endc = boundary_mesh.end(); + typename Triangulation<s_dim+1,spacedim>::face_iterator face; + + bool success = true; + + if (verbosity>1) + { + deallog << "The last column should be 0" <<endl; + deallog << "Vol faces" << "\t\t" << "Surf cell" << + "\t\t" << "Distance" <<endl<<endl; + } + + for (; cell!=endc; ++cell) + { + + face = surface_to_volume_mapping [cell]; + + for (unsigned int k=0; k<GeometryInfo<s_dim>::vertices_per_cell; ++k) + { + Point<spacedim> diff(face->vertex(k)); + diff -= cell->vertex(k); + if (verbosity>1) + { + deallog << face->vertex(k) << "\t\t"; + deallog << cell->vertex(k) << "\t\t\t" << diff.square() << endl; + } + if (diff.square()>0) + { + success = false; + break; + } + } + if (verbosity>1) deallog << endl; + } + return success; +} + +template <int dim, int spacedim> +void save_mesh(const Triangulation<dim,spacedim> &tria) +{ + GridOut grid_out; + grid_out.write_gnuplot (tria, deallog.get_file_stream()); +} + + +int main () +{ + + ofstream logfile("output"); + deallog.attach(logfile); + deallog.depth_console(0); + + + { + // Extract the boundary of a hyper-sphere + + const int dim = 3; + deallog << "Testing hyper_cube in dim: " << dim << "..."<< endl; + + map< Triangulation<dim-1,dim>::cell_iterator, + Triangulation<dim,dim>::face_iterator> + surface_to_volume_mapping; + Triangulation<dim> volume_mesh; + GridGenerator::hyper_ball(volume_mesh); + + volume_mesh.refine_global (1); + + Triangulation<dim-1,dim> boundary_mesh; + + surface_to_volume_mapping + = GridGenerator::extract_boundary_mesh (volume_mesh, boundary_mesh); + + if (!test_vertices_orientation(boundary_mesh, surface_to_volume_mapping,2)) + Assert (false, ExcInternalError()); + save_mesh(boundary_mesh); + } + + + return 0; +} diff --git a/pool/shard007/C++/0094576_DPadSoftKeyboard.cpp b/pool/shard007/C++/0094576_DPadSoftKeyboard.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3a7e5da1d8ee2d2ee8796544693f9d7d1e004518 --- /dev/null +++ b/pool/shard007/C++/0094576_DPadSoftKeyboard.cpp @@ -0,0 +1,115 @@ +/* GemRB - Infinity Engine Emulator + * Copyright (C) 2003-2020 The GemRB Project + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * + */ + +#include "DPadSoftKeyboard.h" + +using namespace GemRB; + +void DPadSoftKeyboard::StartInput() +{ + inputActive = true; + emptyInput = true; + currentUpper = true; + currentCharIndex = 0; + inputIndexes.clear(); +} + +void DPadSoftKeyboard::StopInput() +{ + inputActive = false; +} + +bool DPadSoftKeyboard::IsInputActive() const +{ + return inputActive; +} + +Event DPadSoftKeyboard::GetTextEvent() const +{ + char modKeyValue = dpadKeys[currentCharIndex]; + + if (currentUpper && dpadKeys[currentCharIndex] >= 97 && dpadKeys[currentCharIndex] <= 122) { + modKeyValue -= 32; + } + + char string[2] = { modKeyValue, '\0' }; + return EventMgr::CreateTextEvent(string); +} + +void DPadSoftKeyboard::ToggleUppercase() +{ + if (emptyInput) { + emptyInput = false; + } + + if (dpadKeys[currentCharIndex] >= 97 && dpadKeys[currentCharIndex] <= 122) { + currentUpper = !currentUpper; + } +} + +void DPadSoftKeyboard::RemoveCharacter() +{ + if (inputIndexes.empty()) { + emptyInput = true; + currentUpper = true; + currentCharIndex = 0; + } else { + currentCharIndex = inputIndexes.back(); + inputIndexes.pop_back(); + if (inputIndexes.empty()) { + currentUpper = true; + } + } +} + +void DPadSoftKeyboard::AddCharacter() +{ + if (emptyInput) { + emptyInput = false; + } else { + currentUpper = false; + inputIndexes.push_back(currentCharIndex); + currentCharIndex = 0; + } +} + +void DPadSoftKeyboard::NextCharacter() +{ + if (emptyInput) { + emptyInput = false; + } else { + ++currentCharIndex; + if (currentCharIndex >= TOTAL_CHARACTERS_DPAD) { + currentCharIndex = 0; + } + } +} + +void DPadSoftKeyboard::PreviousCharacter() +{ + if (emptyInput) { + emptyInput = false; + } else { + --currentCharIndex; + if (currentCharIndex < 0) { + currentCharIndex = TOTAL_CHARACTERS_DPAD - 1; + } + } +} diff --git a/pool/shard007/C++/0094578_AdvancedSettings.cpp b/pool/shard007/C++/0094578_AdvancedSettings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..48346ebf04a06d1b21f78cbd28c6443c8629a26d --- /dev/null +++ b/pool/shard007/C++/0094578_AdvancedSettings.cpp @@ -0,0 +1,114 @@ +#include <fstream> +#include <process.h> +#include "EasyRexx.h" +#include "DockingFeature\SettingsDialog.h" +#include "AdvancedSettings.h" +#include "menuCmdID.h" +#include "Scintilla.h" + +#pragma comment(lib, "User32.lib") + + +bool isTimerOn = false; +int msgTimer; + +bool ReadSettings(WCHAR* addy, WCHAR* id, WCHAR* pw, WCHAR* path, bool& ck1, bool& ck2, bool& ck3) +{ + std::wstring userPath = _wgetenv(L"USERPROFILE"); + userPath.append(L"\\EasyREXX.ini"); + std::wifstream in(userPath.c_str()); + + in >> addy; + in >> id; + in >> pw; + in >> path; + in >> ck1; + in >> ck2; + in >> ck3; + + return true; +} + +bool WriteSettings(WCHAR* addy, WCHAR* id, WCHAR* pw, WCHAR* path, bool ck1, bool ck2, bool ck3) +{ + using namespace std; + wstring userPath = _wgetenv(L"USERPROFILE"); + userPath.append(L"\\EasyREXX.ini"); + wofstream out(userPath.c_str()); + + out << addy << endl << id << endl << pw << endl << path << endl << ck1 << endl << ck2 << endl << ck3 << endl; + + return true; +} + +void ConvertTab(HWND handle) +{ + SendMessage(handle, NPPM_MENUCOMMAND, 0, IDM_EDIT_TAB2SW); +} + +void ConvertCRLF(HWND handle) +{ + SendMessage(handle, SCI_CONVERTEOLS, SC_EOL_CRLF, 0); +} + +HWND getCurrentScintilla(NppData nppData) +{ + int which = -1; + ::SendMessage(nppData._nppHandle, NPPM_GETCURRENTSCINTILLA, 0, (LPARAM)&which); + if (which == -1) + return NULL; + HWND curScintilla = (which == 0) ? nppData._scintillaMainHandle : nppData._scintillaSecondHandle; + + return curScintilla; +} + +unsigned WINAPI msgboxThread(void *) +{ + MessageBox(NULL, L"Successfully uploaded file to ftp server!", L"Ftp Upload", MB_ICONINFORMATION | MB_OK); + return 0; +} + +void CALLBACK f(HWND hwnd, UINT uMsg, UINT timerId, DWORD dwTime) +{ + hwnd = NULL; + uMsg = NULL; + timerId = NULL; + dwTime = NULL; + + HWND msghwnd = FindWindow(NULL, L"Ftp Upload"); + if (msghwnd != NULL) + { + SendMessage(msghwnd, WM_CLOSE, NULL, NULL); + isTimerOn = true; + } +} + +int MessageBoxTimeout(HWND hWnd, LPCSTR lpText, + LPCSTR lpCaption, UINT uType, WORD wLanguageId, + DWORD dwMilliseconds) +{ + static MSGBOXAAPI MsgBoxTOA = NULL; + + if (!MsgBoxTOA) + { + HMODULE hUser32 = GetModuleHandle(_T("user32.dll")); + if (hUser32) + { + MsgBoxTOA = (MSGBOXAAPI)GetProcAddress(hUser32, "MessageBoxTimeoutA"); + //fall through to 'if (MsgBoxTOA)...' + } + else + { + //stuff happened, add code to handle it here + //(possibly just call MessageBox()) + return 0; + } + } + + if (MsgBoxTOA) + { + return MsgBoxTOA(hWnd, lpText, lpCaption, uType, wLanguageId, dwMilliseconds); + } + + return 0; +} diff --git a/pool/shard007/C++/0094580_accelerator_interactive_uitest_chromeos.cc b/pool/shard007/C++/0094580_accelerator_interactive_uitest_chromeos.cc new file mode 100644 index 0000000000000000000000000000000000000000..74cfe1c40defa820f6339fd6c903552c389b6a14 --- /dev/null +++ b/pool/shard007/C++/0094580_accelerator_interactive_uitest_chromeos.cc @@ -0,0 +1,223 @@ +// 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. + +#include "ash/accelerators/accelerator_controller.h" + +#include "ash/shell.h" +#include "ash/shell_observer.h" +#include "ash/system/chromeos/network/network_observer.h" +#include "ash/system/tray/system_tray_delegate.h" +#include "ash/system/tray/system_tray_notifier.h" +#include "ash/test/ash_test_base.h" +#include "ash/test/test_screenshot_delegate.h" +#include "ash/test/test_volume_control_delegate.h" +#include "ash/wm/window_state.h" +#include "ash/wm/window_util.h" +#include "base/path_service.h" +#include "base/run_loop.h" +#include "chromeos/network/network_handler.h" +#include "ui/base/resource/resource_bundle.h" +#include "ui/base/test/ui_controls.h" +#include "ui/base/ui_base_paths.h" +#include "ui/gl/gl_surface.h" + +namespace ash { +namespace test { + +namespace { + +// A network observer to watch for the toggle wifi events. +class TestNetworkObserver : public NetworkObserver { + public: + TestNetworkObserver() : wifi_enabled_status_(false) {} + + // ash::NetworkObserver: + void RequestToggleWifi() override { + wifi_enabled_status_ = !wifi_enabled_status_; + } + + bool wifi_enabled_status() const { return wifi_enabled_status_; } + + private: + bool wifi_enabled_status_; + + DISALLOW_COPY_AND_ASSIGN(TestNetworkObserver); +}; + +} // namespace + +//////////////////////////////////////////////////////////////////////////////// + +// This is intended to test few samples from each category of accelerators to +// make sure they work properly. The test is done as an interactive ui test +// using ui_controls::Send*() functions. +// This is to catch any future regressions (crbug.com/469235). +class AcceleratorInteractiveUITest : public AshTestBase, public ShellObserver { + public: + AcceleratorInteractiveUITest() : is_in_overview_mode_(false) {} + + void SetUp() override { + gfx::GLSurface::InitializeOneOffForTests(); + + ui::RegisterPathProvider(); + ui::ResourceBundle::InitSharedInstanceWithLocale( + "en-US", NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES); + base::FilePath resources_pack_path; + PathService::Get(base::DIR_MODULE, &resources_pack_path); + resources_pack_path = + resources_pack_path.Append(FILE_PATH_LITERAL("resources.pak")); + ResourceBundle::GetSharedInstance().AddDataPackFromPath( + resources_pack_path, ui::SCALE_FACTOR_NONE); + + AshTestBase::SetUp(); + + Shell::GetInstance()->AddShellObserver(this); + + chromeos::NetworkHandler::Initialize(); + } + + void TearDown() override { + chromeos::NetworkHandler::Shutdown(); + + Shell::GetInstance()->RemoveShellObserver(this); + + AshTestBase::TearDown(); + } + + // Sends a key press event and waits synchronously until it's completely + // processed. + void SendKeyPressSync(ui::KeyboardCode key, + bool control, + bool shift, + bool alt) { + base::RunLoop loop; + ui_controls::SendKeyPressNotifyWhenDone(root_window(), key, control, shift, + alt, false, loop.QuitClosure()); + loop.Run(); + } + + // ash::ShellObserver: + void OnOverviewModeStarting() override { is_in_overview_mode_ = true; } + void OnOverviewModeEnded() override { is_in_overview_mode_ = false; } + + Shell* shell() const { return Shell::GetInstance(); } + aura::Window* root_window() const { return Shell::GetPrimaryRootWindow(); } + + protected: + bool is_in_overview_mode_; + + private: + DISALLOW_COPY_AND_ASSIGN(AcceleratorInteractiveUITest); +}; + +//////////////////////////////////////////////////////////////////////////////// + +#if defined(OFFICIAL_BUILD) +#define MAYBE_NonRepeatableNeedingWindowActions \ + DISABLED_NonRepeatableNeedingWindowActions +#define MAYBE_ChromeOsAccelerators DISABLED_ChromeOsAccelerators +#define MAYBE_ToggleAppList DISABLED_ToggleAppList +#else +#define MAYBE_NonRepeatableNeedingWindowActions \ + NonRepeatableNeedingWindowActions +#define MAYBE_ChromeOsAccelerators ChromeOsAccelerators +#define MAYBE_ToggleAppList ToggleAppList +#endif // defined(OFFICIAL_BUILD) + +// Tests a sample of the non-repeatable accelerators that need windows to be +// enabled. +TEST_F(AcceleratorInteractiveUITest, MAYBE_NonRepeatableNeedingWindowActions) { + // Create a bunch of windows to work with. + aura::Window* window_1 = + CreateTestWindowInShellWithBounds(gfx::Rect(0, 0, 100, 100)); + aura::Window* window_2 = + CreateTestWindowInShellWithBounds(gfx::Rect(0, 0, 100, 100)); + window_1->Show(); + wm::ActivateWindow(window_1); + window_2->Show(); + wm::ActivateWindow(window_2); + + // Test TOGGLE_OVERVIEW. + EXPECT_FALSE(is_in_overview_mode_); + SendKeyPressSync(ui::VKEY_MEDIA_LAUNCH_APP1, false, false, false); + EXPECT_TRUE(is_in_overview_mode_); + SendKeyPressSync(ui::VKEY_MEDIA_LAUNCH_APP1, false, false, false); + EXPECT_FALSE(is_in_overview_mode_); + + // Test CYCLE_FORWARD_MRU and CYCLE_BACKWARD_MRU. + wm::ActivateWindow(window_1); + EXPECT_TRUE(wm::IsActiveWindow(window_1)); + EXPECT_FALSE(wm::IsActiveWindow(window_2)); + SendKeyPressSync(ui::VKEY_TAB, false, false, true); // CYCLE_FORWARD_MRU. + EXPECT_TRUE(wm::IsActiveWindow(window_2)); + EXPECT_FALSE(wm::IsActiveWindow(window_1)); + SendKeyPressSync(ui::VKEY_TAB, false, true, true); // CYCLE_BACKWARD_MRU. + EXPECT_TRUE(wm::IsActiveWindow(window_1)); + EXPECT_FALSE(wm::IsActiveWindow(window_2)); + + // Test TOGGLE_FULLSCREEN. + wm::WindowState* active_window_state = wm::GetActiveWindowState(); + EXPECT_FALSE(active_window_state->IsFullscreen()); + SendKeyPressSync(ui::VKEY_MEDIA_LAUNCH_APP2, false, false, false); + EXPECT_TRUE(active_window_state->IsFullscreen()); + SendKeyPressSync(ui::VKEY_MEDIA_LAUNCH_APP2, false, false, false); + EXPECT_FALSE(active_window_state->IsFullscreen()); +} + +// Tests a sample of ChromeOS specific accelerators. +TEST_F(AcceleratorInteractiveUITest, MAYBE_ChromeOsAccelerators) { + // Test TAKE_SCREENSHOT and TAKE_PARTIAL_SCREENSHOT. + TestScreenshotDelegate* screenshot_delegate = GetScreenshotDelegate(); + screenshot_delegate->set_can_take_screenshot(true); + EXPECT_EQ(0, screenshot_delegate->handle_take_screenshot_count()); + SendKeyPressSync(ui::VKEY_MEDIA_LAUNCH_APP1, true, false, false); + EXPECT_EQ(1, screenshot_delegate->handle_take_screenshot_count()); + SendKeyPressSync(ui::VKEY_PRINT, false, false, false); + EXPECT_EQ(2, screenshot_delegate->handle_take_screenshot_count()); + SendKeyPressSync(ui::VKEY_MEDIA_LAUNCH_APP1, true, true, false); + EXPECT_EQ(2, screenshot_delegate->handle_take_screenshot_count()); + // Press ESC to go out of the partial screenshot mode. + SendKeyPressSync(ui::VKEY_ESCAPE, false, false, false); + + // Test VOLUME_MUTE, VOLUME_DOWN, and VOLUME_UP. + TestVolumeControlDelegate* volume_delegate = new TestVolumeControlDelegate; + shell()->system_tray_delegate()->SetVolumeControlDelegate( + scoped_ptr<VolumeControlDelegate>(volume_delegate).Pass()); + // VOLUME_MUTE. + EXPECT_EQ(0, volume_delegate->handle_volume_mute_count()); + SendKeyPressSync(ui::VKEY_VOLUME_MUTE, false, false, false); + EXPECT_EQ(1, volume_delegate->handle_volume_mute_count()); + // VOLUME_DOWN. + EXPECT_EQ(0, volume_delegate->handle_volume_down_count()); + SendKeyPressSync(ui::VKEY_VOLUME_DOWN, false, false, false); + EXPECT_EQ(1, volume_delegate->handle_volume_down_count()); + // VOLUME_UP. + EXPECT_EQ(0, volume_delegate->handle_volume_up_count()); + SendKeyPressSync(ui::VKEY_VOLUME_UP, false, false, false); + EXPECT_EQ(1, volume_delegate->handle_volume_up_count()); + + // Test TOGGLE_WIFI. + TestNetworkObserver network_observer; + shell()->system_tray_notifier()->AddNetworkObserver(&network_observer); + + EXPECT_FALSE(network_observer.wifi_enabled_status()); + SendKeyPressSync(ui::VKEY_WLAN, false, false, false); + EXPECT_TRUE(network_observer.wifi_enabled_status()); + SendKeyPressSync(ui::VKEY_WLAN, false, false, false); + EXPECT_FALSE(network_observer.wifi_enabled_status()); + + shell()->system_tray_notifier()->RemoveNetworkObserver(&network_observer); +} + +// Tests the app list accelerator. +TEST_F(AcceleratorInteractiveUITest, MAYBE_ToggleAppList) { + EXPECT_FALSE(shell()->GetAppListTargetVisibility()); + SendKeyPressSync(ui::VKEY_LWIN, false, false, false); + EXPECT_TRUE(shell()->GetAppListTargetVisibility()); + SendKeyPressSync(ui::VKEY_LWIN, false, false, false); + EXPECT_FALSE(shell()->GetAppListTargetVisibility()); +} + +} // namespace test +} // namespace ash diff --git a/pool/shard007/C++/0094582_ThreadIdTest.cpp b/pool/shard007/C++/0094582_ThreadIdTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5970ea26ca6ab96633b1a85cbed4f458ccff6e51 --- /dev/null +++ b/pool/shard007/C++/0094582_ThreadIdTest.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Make sure we include ThreadId.h before anything else. +// There is no ThreadId.cpp file, so this test is the only thing that verifies +// that ThreadId.h compiles by itself when included first. +#include <folly/system/ThreadId.h> + +#include <thread> + +#include <folly/portability/GTest.h> + +TEST(ThreadId, getCurrentID) { + auto thisThreadID = folly::getCurrentThreadID(); + uint64_t otherThreadID; + std::thread otherThread{[&] { otherThreadID = folly::getCurrentThreadID(); }}; + otherThread.join(); + EXPECT_NE(thisThreadID, otherThreadID); +} + +TEST(ThreadId, getOSThreadID) { + auto thisThreadID = folly::getOSThreadID(); + uint64_t otherThreadID; + std::thread otherThread{[&] { otherThreadID = folly::getOSThreadID(); }}; + otherThread.join(); + EXPECT_NE(thisThreadID, otherThreadID); +} diff --git a/pool/shard007/C++/0094583_MagicalGCD.cpp b/pool/shard007/C++/0094583_MagicalGCD.cpp new file mode 100644 index 0000000000000000000000000000000000000000..310f21933cb41233c21f4a12004c736581c6c493 --- /dev/null +++ b/pool/shard007/C++/0094583_MagicalGCD.cpp @@ -0,0 +1,66 @@ +/* + By: facug91 + From: https://acm.javeriana.edu.co/maratones/2015/07 + Name: Magical GCD + Date: 08/08/2015 +*/ + +#include <bits/stdc++.h> + +using namespace std; +#define prev d392rhbcdgausidhdsadasda + +typedef long long ll; + +ll n, a[100005], ans, g, c, l; +map<ll, ll> prev, curr; + +ll gcd (ll a, ll b) { + if (b == 0) return a; + return gcd(b, a%b); +} + +int main() { + int tc, i, j; + + cin>>tc; + while (tc--) { + cin>>n; + for (i=0; i<n; i++) cin>>a[i]; + ans = 1ll; + prev.clear(); + for (i=0; i<n; i++) { + curr.clear(); + for (auto it : prev) { + g = gcd(a[i], it.first); + l = it.second+1ll; + c = (it.second+1ll)*g; + if (curr.find(g) == curr.end()) { + curr[g] = l; + ans = max(c, ans); + } else { + if (curr[g] < l) { + curr[g] = l; + ans = max(c, ans); + } + } + } + g = a[i]; + l = 1ll; + c = a[i]; + if (curr.find(g) == curr.end()) { + curr[g] = l; + ans = max(c, ans); + } else { + if (curr[g] < l) { + curr[g] = l; + ans = max(c, ans); + } + } + prev = curr; + } + cout<<ans<<endl; + } + +} + diff --git a/pool/shard007/C++/0094584_BaLog.cpp b/pool/shard007/C++/0094584_BaLog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..46c35b55284e05b6a389cac2195cb773b15e5a13 --- /dev/null +++ b/pool/shard007/C++/0094584_BaLog.cpp @@ -0,0 +1,201 @@ +/*------------------------------------------------------------------------------ + Includes + -----------------------------------------------------------------------------*/ +#include <stdarg.h> + +#include "CBaLog.h" +#include "BaUtils.hpp" + + +/*------------------------------------------------------------------------------ + Defines + -----------------------------------------------------------------------------*/ +#define C_HDL_ ((IBaLog*) hdl) + +/*------------------------------------------------------------------------------ + Type definitions + -----------------------------------------------------------------------------*/ + +/*------------------------------------------------------------------------------ + C Interface + -----------------------------------------------------------------------------*/ + +// +TBaLogHdl BaLogCreateDef(const char *name) { + return CBaLog::Create(name); +} + +// +void BaLogSetDefOpts(TBaLogOptions *pOpts ) { + if (pOpts) { + pOpts->name = ""; + pOpts->path = ""; + pOpts->prioFilt = eBaLogPrio_Trace; + pOpts->out = eBaLogOut_LogAndConsole; + pOpts->maxFileSizeB = 1048576; // 1 MiB + pOpts->maxNoFiles = 3; + pOpts->maxBufLength = 0; + } +} + +// +TBaLogHdl BaLogCreate(const TBaLogOptions *pOpts) { + return pOpts ? CBaLog::Create(*pOpts) : 0; +} + +// +TBaBoolRC BaLogDestroy(TBaLogHdl hld, TBaBool saveCfg) { + CBaLog *p = dynamic_cast<CBaLog*>((IBaLog*)hld); + if (!p) { + return false; + } + return CBaLog::Destroy(p, saveCfg) ? eBaBoolRC_Success : eBaBoolRC_Error; +} + +// +TBaBoolRC BaLogLog(TBaLogHdl hdl, EBaLogPrio prio, const char* tag, const char* msg) { + if (!hdl) { + return eBaBoolRC_Error; + } + + return C_HDL_->Log(prio, tag, msg) ? eBaBoolRC_Success : eBaBoolRC_Error; +} + +// +TBaBoolRC BaLogTrace(TBaLogHdl hdl, const char* tag, const char* msg) { + if (!hdl) { + return eBaBoolRC_Error; + } + + return C_HDL_->Trace(tag, msg) ? eBaBoolRC_Success : eBaBoolRC_Error; +} + +// +TBaBoolRC BaLogWarning(TBaLogHdl hdl, const char* tag, const char* msg) { + if (!hdl) { + return eBaBoolRC_Error; + } + + return C_HDL_->Warning(tag, msg) ? eBaBoolRC_Success : eBaBoolRC_Error; +} + +// +TBaBoolRC BaLogError(TBaLogHdl hdl, const char* tag, const char* msg) { + if (!hdl) { + return eBaBoolRC_Error; + } + + return C_HDL_->Error(tag, msg) ? eBaBoolRC_Success : eBaBoolRC_Error; +} + +// +TBaBoolRC BaLogLogF(TBaLogHdl hdl, EBaLogPrio prio, const char* tag, const char* fmt, ...) { + if (!hdl) { + return eBaBoolRC_Error; + } + + va_list arg; + va_start(arg, fmt); + TBaBoolRC ret = C_HDL_->LogF(prio, tag, fmt, arg) ? eBaBoolRC_Success : eBaBoolRC_Error; + va_end(arg); + return ret; +} + +// +TBaBoolRC BaLogTraceF(TBaLogHdl hdl, const char* tag, const char* fmt, ...) { + if (!hdl) { + return eBaBoolRC_Error; + } + + va_list arg; + va_start(arg, fmt); + TBaBoolRC ret = C_HDL_->TraceF(tag, fmt, arg) ? eBaBoolRC_Success : eBaBoolRC_Error; + va_end(arg); + return ret; +} + +// +TBaBoolRC BaLogWarningF(TBaLogHdl hdl, const char* tag, const char* fmt, ...) { + if (!hdl) { + return eBaBoolRC_Error; + } + + va_list arg; + va_start(arg, fmt); + TBaBoolRC ret = C_HDL_->WarningF(tag, fmt, arg) ? eBaBoolRC_Success : eBaBoolRC_Error; + va_end(arg); + return ret; +} + +// +TBaBoolRC BaLogErrorF(TBaLogHdl hdl, const char* tag, const char* fmt, ...) { + if (!hdl) { + return eBaBoolRC_Error; + } + + va_list arg; + va_start(arg, fmt); + TBaBoolRC ret = C_HDL_->ErrorF(tag, fmt, arg) ? eBaBoolRC_Success : eBaBoolRC_Error; + va_end(arg); + return ret; +} + +// +void BaLogGetLogInfo(TBaLogHdl hdl, TBaLogInfo *pInfo) { + C_HDL_->GetLogInfo(pInfo); +} + +// +void BaLogFlush(TBaLogHdl hdl) { + C_HDL_->Flush(); +} + +// +void BaLogSysLogF(const char *tag, int line, const char *fmt, ...) { + va_list arg; + va_start(arg, fmt); + std::string s = BaFString(fmt, arg); + va_end(arg); + CBaLog::SysLog(tag, line, s.c_str()); +} + +// +void BaLogSysLog(const char *tag, int line, const char *msg) { + CBaLog::SysLog(tag, line, msg); +} + + +/*------------------------------------------------------------------------------ + C++ Factories + -----------------------------------------------------------------------------*/ + +// +IBaLog * IBaLogCreateDef(const char *name) { + return CBaLog::Create(name); +} + +// +IBaLog * IBaLogCreate(const TBaLogOptions *pOpts) { + return pOpts ? CBaLog::Create(*pOpts) : 0; +} + +// +TBaBoolRC IBaLogDestroy(IBaLog *pHdl, TBaBool saveCfg) { + CBaLog *p = dynamic_cast<CBaLog*>(pHdl); + if (!p) { + return false; + } + + return CBaLog::Destroy(p, saveCfg); +} + + +/*------------------------------------------------------------------------------ + C++ Interface + -----------------------------------------------------------------------------*/ + + +/*------------------------------------------------------------------------------ + Local functions + -----------------------------------------------------------------------------*/ + diff --git a/pool/shard007/C++/0094586_signals_service_impl_unittest.cc b/pool/shard007/C++/0094586_signals_service_impl_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..e4b223c64981967fe5c7303cb1378e11f89f7cdf --- /dev/null +++ b/pool/shard007/C++/0094586_signals_service_impl_unittest.cc @@ -0,0 +1,75 @@ +// Copyright 2021 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 "chrome/browser/enterprise/connectors/device_trust/signals/signals_service_impl.h" + +#include <memory> +#include <string> +#include <utility> +#include <vector> + +#include "base/callback.h" +#include "base/test/bind.h" +#include "base/test/metrics/histogram_tester.h" +#include "chrome/browser/enterprise/connectors/device_trust/signals/decorators/common/mock_signals_decorator.h" +#include "chrome/browser/enterprise/connectors/device_trust/signals/decorators/common/signals_decorator.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace enterprise_connectors { + +using test::MockSignalsDecorator; +using ::testing::_; + +namespace { + +constexpr char kLatencyHistogram[] = + "Enterprise.DeviceTrust.SignalsDecorator.Latency.Full"; + +} // namespace + +TEST(SignalsServiceImplTest, CollectSignals_CallsAllDecorators) { + base::HistogramTester histogram_tester; + std::string fake_obfuscated_customer_id = "fake_obfuscated_customer_id"; + std::unique_ptr<MockSignalsDecorator> first_decorator = + std::make_unique<MockSignalsDecorator>(); + EXPECT_CALL(*first_decorator.get(), Decorate(_, _)) + .WillOnce([&fake_obfuscated_customer_id](SignalsType& signals, + base::OnceClosure done_closure) { + signals.set_obfuscated_customer_id(fake_obfuscated_customer_id); + std::move(done_closure).Run(); + }); + + std::string fake_device_id = "fake_device_id"; + std::unique_ptr<MockSignalsDecorator> second_decorator = + std::make_unique<MockSignalsDecorator>(); + EXPECT_CALL(*second_decorator.get(), Decorate(_, _)) + .WillOnce([&fake_device_id](SignalsType& signals, + base::OnceClosure done_closure) { + signals.set_device_id(fake_device_id); + std::move(done_closure).Run(); + }); + + std::vector<std::unique_ptr<SignalsDecorator>> decorators; + decorators.push_back(std::move(first_decorator)); + decorators.push_back(std::move(second_decorator)); + + SignalsServiceImpl service(std::move(decorators)); + + bool callback_called = false; + auto callback = + base::BindLambdaForTesting([&](std::unique_ptr<SignalsType> signals) { + EXPECT_EQ(signals->obfuscated_customer_id(), + fake_obfuscated_customer_id); + EXPECT_EQ(signals->device_id(), fake_device_id); + callback_called = true; + }); + + service.CollectSignals(std::move(callback)); + + EXPECT_TRUE(callback_called); + histogram_tester.ExpectTotalCount(kLatencyHistogram, 1); +} + +} // namespace enterprise_connectors diff --git a/pool/shard007/C++/0094593_istest.cpp b/pool/shard007/C++/0094593_istest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e368b9c1073d10fcd3dbe431e02d5b3ceef8f81e --- /dev/null +++ b/pool/shard007/C++/0094593_istest.cpp @@ -0,0 +1,33 @@ +#include "istest.h" + +#include <QtTest/QtTest> + +#include <matcher/is.h> +#include <matcher/isequal.h> +#include <matcher.h> +using namespace HamcrestQt; + +#include "abstractmatcher.h" + + +void IsTest::matchesTheSameWayTheUnderlyingMatcherDoes() +{ + const QSharedPointer<Matcher<bool> > matcher = is(equalTo(true)); + + ASSERT_MATCHES(matcher, true); + ASSERT_DOES_NOT_MATCH(matcher, false); +} + +void IsTest::generatesIsPrefixInDescription() +{ + ASSERT_DESCRIPTION("is <true>", is(equalTo(true))); + ASSERT_DESCRIPTION("is \"A\"", is("A")); +} + +void IsTest::providesConvenientShortcutForIsEqualTo() +{ + QSharedPointer<Matcher<const char*> > matcher = is("A"); + + ASSERT_MATCHES(matcher, "A"); + ASSERT_DOES_NOT_MATCH(is("A"), "B"); +} diff --git a/pool/shard007/C++/0094599_Scenario2_ManageAccount.xaml.cpp b/pool/shard007/C++/0094599_Scenario2_ManageAccount.xaml.cpp new file mode 100644 index 0000000000000000000000000000000000000000..88ea7fe5583689826f76069fc6728832cc723f10 --- /dev/null +++ b/pool/shard007/C++/0094599_Scenario2_ManageAccount.xaml.cpp @@ -0,0 +1,64 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "pch.h" +#include "Scenario2_ManageAccount.xaml.h" +#include <ppltasks.h> + +using namespace SDKTemplate; +using namespace concurrency; + +using namespace Platform; +using namespace Windows::Foundation; +using namespace Windows::Foundation::Collections; +using namespace Windows::UI::Xaml; +using namespace Windows::UI::Xaml::Controls; +using namespace Windows::UI::Xaml::Controls::Primitives; +using namespace Windows::UI::Xaml::Data; +using namespace Windows::UI::Xaml::Input; +using namespace Windows::UI::Xaml::Media; +using namespace Windows::UI::Xaml::Navigation; +using namespace Windows::ApplicationModel; +using namespace Windows::ApplicationModel::UserDataAccounts; + +// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 + +Scenario2_ManageAccount::Scenario2_ManageAccount() : rootPage(MainPage::Current) +{ + InitializeComponent(); +} + +void Scenario2_ManageAccount::OnNavigatedTo(NavigationEventArgs^ e) +{ + rootPage->LoadDataAccountsAsync(AccountsListComboBox); + +} + +void Scenario2_ManageAccount::Manage_Click(Object^ sender, RoutedEventArgs^ e) +{ + auto selectedAccount = safe_cast<UserDataAccountViewModel^>(AccountsListComboBox->SelectedValue); + if (selectedAccount != nullptr) + { + // only one instance of the UserDataAccountManager pane can be launched at once per thread + if (isLaunched == false) + { + isLaunched = true; + create_task(UserDataAccounts::UserDataAccountManager::ShowAccountSettingsAsync(selectedAccount->Account->Id)).then([this]() + { + // User may have deleted the account + return rootPage->LoadDataAccountsAsync(AccountsListComboBox); + }).then([this]() + { + isLaunched = false; + }); + } + } +} diff --git a/pool/shard007/C++/0094604_GrGLExtensions.cpp b/pool/shard007/C++/0094604_GrGLExtensions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bf5a321f4fe72f9782fdafb9089693932f320f68 --- /dev/null +++ b/pool/shard007/C++/0094604_GrGLExtensions.cpp @@ -0,0 +1,171 @@ +/* + * Copyright 2013 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include "gl/GrGLExtensions.h" +#include "gl/GrGLDefines.h" +#include "gl/GrGLUtil.h" + +#include "SkJSONWriter.h" +#include "SkMakeUnique.h" +#include "SkTSearch.h" +#include "SkTSort.h" + +namespace { // This cannot be static because it is used as a template parameter. +inline bool extension_compare(const SkString& a, const SkString& b) { + return strcmp(a.c_str(), b.c_str()) < 0; +} +} + +// finds the index of ext in strings or a negative result if ext is not found. +static int find_string(const SkTArray<SkString>& strings, const char ext[]) { + if (strings.empty()) { + return -1; + } + SkString extensionStr(ext); + int idx = SkTSearch<SkString, extension_compare>(&strings.front(), + strings.count(), + extensionStr, + sizeof(SkString)); + return idx; +} + +GrGLExtensions::GrGLExtensions(const GrGLExtensions& that) { + *this = that; +} + +GrGLExtensions& GrGLExtensions::operator=(const GrGLExtensions& that) { + if (this != &that) { + fStrings = that.fStrings; + fInitialized = that.fInitialized; + } + return *this; +} + +static void eat_space_sep_strings(SkTArray<SkString>* out, const char in[]) { + if (!in) { + return; + } + while (true) { + // skip over multiple spaces between extensions + while (' ' == *in) { + ++in; + } + // quit once we reach the end of the string. + if ('\0' == *in) { + break; + } + // we found an extension + size_t length = strcspn(in, " "); + out->push_back().set(in, length); + in += length; + } +} + +bool GrGLExtensions::init(GrGLStandard standard, + GrGLFunction<GrGLGetStringFn> getString, + GrGLFunction<GrGLGetStringiFn> getStringi, + GrGLFunction<GrGLGetIntegervFn> getIntegerv, + GrGLFunction<GrEGLQueryStringFn> queryString, + GrEGLDisplay eglDisplay) { + fInitialized = false; + fStrings.reset(); + + if (!getString) { + return false; + } + + const GrGLubyte* verString = getString(GR_GL_VERSION); + GrGLVersion version = GrGLGetVersionFromString((const char*) verString); + if (GR_GL_INVALID_VER == version) { + return false; + } + + bool indexed = false; + if (GR_IS_GR_GL(standard) || GR_IS_GR_GL_ES(standard)) { + // glGetStringi and indexed extensions were added in version 3.0 of desktop GL and ES. + indexed = version >= GR_GL_VER(3, 0); + } else if (GR_IS_GR_WEBGL(standard)) { + // WebGL (1.0 or 2.0) doesn't natively support glGetStringi, but enscripten adds it in + // https://github.com/emscripten-core/emscripten/issues/3472 + indexed = version >= GR_GL_VER(2, 0); + } + + if (indexed) { + if (!getStringi || !getIntegerv) { + return false; + } + GrGLint extensionCnt = 0; + getIntegerv(GR_GL_NUM_EXTENSIONS, &extensionCnt); + fStrings.push_back_n(extensionCnt); + for (int i = 0; i < extensionCnt; ++i) { + const char* ext = (const char*) getStringi(GR_GL_EXTENSIONS, i); + fStrings[i] = ext; + } + } else { + const char* extensions = (const char*) getString(GR_GL_EXTENSIONS); + if (!extensions) { + return false; + } + eat_space_sep_strings(&fStrings, extensions); + } + if (queryString) { + const char* extensions = queryString(eglDisplay, GR_EGL_EXTENSIONS); + + eat_space_sep_strings(&fStrings, extensions); + } + if (!fStrings.empty()) { + SkTLessFunctionToFunctorAdaptor<SkString, extension_compare> cmp; + SkTQSort(&fStrings.front(), &fStrings.back(), cmp); + } + fInitialized = true; + return true; +} + +bool GrGLExtensions::has(const char ext[]) const { + SkASSERT(fInitialized); + return find_string(fStrings, ext) >= 0; +} + +bool GrGLExtensions::remove(const char ext[]) { + SkASSERT(fInitialized); + int idx = find_string(fStrings, ext); + if (idx < 0) { + return false; + } + + // This is not terribly effecient but we really only expect this function to be called at + // most a handful of times when our test programs start. + fStrings.removeShuffle(idx); + if (idx != fStrings.count()) { + SkTLessFunctionToFunctorAdaptor<SkString, extension_compare> cmp; + SkTInsertionSort(&(fStrings.operator[](idx)), &fStrings.back(), cmp); + } + return true; +} + +void GrGLExtensions::add(const char ext[]) { + int idx = find_string(fStrings, ext); + if (idx < 0) { + // This is not the most effecient approach since we end up looking at all of the + // extensions after the add + fStrings.emplace_back(ext); + SkTLessFunctionToFunctorAdaptor<SkString, extension_compare> cmp; + SkTInsertionSort(&fStrings.front(), &fStrings.back(), cmp); + } +} + +#ifdef SK_ENABLE_DUMP_GPU +void GrGLExtensions::dumpJSON(SkJSONWriter* writer) const { + writer->beginArray(); + for (int i = 0; i < fStrings.count(); ++i) { + writer->appendString(fStrings[i].c_str()); + } + writer->endArray(); +} +#else +void GrGLExtensions::dumpJSON(SkJSONWriter* writer) const { } +#endif diff --git a/pool/shard007/C++/0094607_precache_referrer_host_table.cc b/pool/shard007/C++/0094607_precache_referrer_host_table.cc new file mode 100644 index 0000000000000000000000000000000000000000..e6acbbad8aa5522f33810974984763f4f76cd48b --- /dev/null +++ b/pool/shard007/C++/0094607_precache_referrer_host_table.cc @@ -0,0 +1,123 @@ +// Copyright 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 "components/precache/core/precache_referrer_host_table.h" + +#include "sql/connection.h" +#include "sql/statement.h" + +using sql::Statement; + +namespace precache { + +const int64_t PrecacheReferrerHostEntry::kInvalidId = -1; + +bool PrecacheReferrerHostEntry::operator==( + const PrecacheReferrerHostEntry& entry) const { + return id == entry.id && referrer_host == entry.referrer_host && + manifest_id == entry.manifest_id && time == entry.time; +} + +PrecacheReferrerHostTable::PrecacheReferrerHostTable() : db_(NULL) {} + +PrecacheReferrerHostTable::~PrecacheReferrerHostTable() {} + +bool PrecacheReferrerHostTable::Init(sql::Connection* db) { + DCHECK(!db_); // Init must only be called once. + DCHECK(db); // The database connection must be non-NULL. + db_ = db; + return CreateTableIfNonExistent(); +} + +PrecacheReferrerHostEntry PrecacheReferrerHostTable::GetReferrerHost( + const std::string& referrer_host) { + Statement statement(db_->GetCachedStatement( + SQL_FROM_HERE, + "SELECT id, referrer_host, manifest_id, time " + "FROM precache_referrer_hosts WHERE referrer_host=?")); + + statement.BindString(0, referrer_host); + if (statement.Step()) { + return PrecacheReferrerHostEntry( + statement.ColumnInt64(0), statement.ColumnString(1), + statement.ColumnInt64(2), + base::Time::FromInternalValue(statement.ColumnInt64(3))); + } + return PrecacheReferrerHostEntry(PrecacheReferrerHostEntry::kInvalidId, + std::string(), 0, base::Time()); +} + +int64_t PrecacheReferrerHostTable::UpdateReferrerHost( + const std::string& referrer_host, + int64_t manifest_id, + const base::Time& time) { + int64_t referrer_host_id = GetReferrerHost(referrer_host).id; + if (referrer_host_id == PrecacheReferrerHostEntry::kInvalidId) { + Statement statement( + db_->GetCachedStatement(SQL_FROM_HERE, + "INSERT INTO precache_referrer_hosts " + "(id, referrer_host, manifest_id, time) " + "VALUES(NULL, ?, ?, ?)")); + + statement.BindString(0, referrer_host); + statement.BindInt64(1, manifest_id); + statement.BindInt64(2, time.ToInternalValue()); + if (statement.Run()) + return db_->GetLastInsertRowId(); + } else { + Statement statement( + db_->GetCachedStatement(SQL_FROM_HERE, + "UPDATE precache_referrer_hosts " + "SET manifest_id=?, time=? " + "WHERE id=?")); + + statement.BindInt64(0, manifest_id); + statement.BindInt64(1, time.ToInternalValue()); + ; + statement.BindInt64(2, referrer_host_id); + if (statement.Run()) + return referrer_host_id; + } + return -1; +} + +void PrecacheReferrerHostTable::DeleteAllEntriesBefore( + const base::Time& delete_end) { + Statement statement(db_->GetCachedStatement( + SQL_FROM_HERE, "DELETE FROM precache_referrer_hosts WHERE time < ?")); + statement.BindInt64(0, delete_end.ToInternalValue()); + statement.Run(); +} + +void PrecacheReferrerHostTable::DeleteAll() { + Statement statement(db_->GetCachedStatement( + SQL_FROM_HERE, "DELETE FROM precache_referrer_hosts")); + + statement.Run(); +} + +bool PrecacheReferrerHostTable::CreateTableIfNonExistent() { + return db_->Execute( + "CREATE TABLE IF NOT EXISTS precache_referrer_hosts " + "(id INTEGER PRIMARY KEY, referrer_host TEXT KEY, manifest_id INTEGER, " + "time INTEGER)"); +} + +std::map<std::string, PrecacheReferrerHostEntry> +PrecacheReferrerHostTable::GetAllDataForTesting() { + std::map<std::string, PrecacheReferrerHostEntry> all_data; + Statement statement( + db_->GetCachedStatement(SQL_FROM_HERE, + "SELECT id, referrer_host, manifest_id, time " + "FROM precache_referrer_hosts")); + while (statement.Step()) { + all_data[statement.ColumnString(1)] = PrecacheReferrerHostEntry( + statement.ColumnInt64(0), statement.ColumnString(1), + statement.ColumnInt64(2), + base::Time::FromInternalValue(statement.ColumnInt64(3))); + } + return all_data; +} + +} // namespace precache diff --git a/pool/shard007/C++/0094608_language_selection.cpp b/pool/shard007/C++/0094608_language_selection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..00ed0a8d0c79911b0389e594cd27168a1f4e0a78 --- /dev/null +++ b/pool/shard007/C++/0094608_language_selection.cpp @@ -0,0 +1,94 @@ +/* + Copyright (C) 2008 - 2016 by Mark de Wever <koraq@xs4all.nl> + Part of the Battle for Wesnoth Project http://www.wesnoth.org/ + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY. + + See the COPYING file for more details. +*/ + +#define GETTEXT_DOMAIN "wesnoth-lib" + +#include "gui/dialogs/language_selection.hpp" + +#include "gui/auxiliary/find_widget.hpp" +#ifdef GUI2_EXPERIMENTAL_LISTBOX +#include "gui/widgets/list.hpp" +#else +#include "gui/widgets/listbox.hpp" +#endif +#include "gui/widgets/settings.hpp" +#include "gui/widgets/window.hpp" +#include "language.hpp" +#include "preferences.hpp" + +namespace gui2 +{ + +/*WIKI + * @page = GUIWindowDefinitionWML + * @order = 2_language_selection + * + * == Language selection == + * + * This shows the dialog to select the language to use. When the dialog is + * closed with the OK button it also updates the selected language in the + * preferences. + * + * @begin{table}{dialog_widgets} + * + * language_list & & listbox & m & + * This listbox contains the list with available languages. $ + * + * - & & control & o & + * Show the name of the language in the current row. $ + * + * @end{table} + */ + +/** + * @todo show we also reset the translations and is the tips of day call + * really needed? + */ + +REGISTER_DIALOG(language_selection) + +void tlanguage_selection::pre_show(twindow& window) +{ + tlistbox& list = find_widget<tlistbox>(&window, "language_list", false); + window.keyboard_capture(&list); + + const std::vector<language_def>& languages = get_languages(); + const language_def& current_language = get_language(); + for(const auto & lang : languages) + { + string_map item; + item.insert(std::make_pair("label", lang.language)); + + list.add_row(item); + if(lang == current_language) { + list.select_row(list.get_item_count() - 1); + } + } +} + +void tlanguage_selection::post_show(twindow& window) +{ + if(get_retval() == twindow::OK) { + const int res = find_widget<tlistbox>(&window, "language_list", false) + .get_selected_row(); + + assert(res != -1); + + const std::vector<language_def>& languages = get_languages(); + ::set_language(languages[res]); + preferences::set_language(languages[res].localename); + } +} + +} // namespace gui2 diff --git a/pool/shard007/C++/0094609_crosscall_server.cc b/pool/shard007/C++/0094609_crosscall_server.cc new file mode 100644 index 0000000000000000000000000000000000000000..f40b6778af64cd3a086624614e9ca965f015e158 --- /dev/null +++ b/pool/shard007/C++/0094609_crosscall_server.cc @@ -0,0 +1,283 @@ +// Copyright (c) 2012 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 <string> +#include <vector> + +#include "sandbox/src/crosscall_server.h" +#include "sandbox/src/crosscall_params.h" +#include "sandbox/src/crosscall_client.h" +#include "base/logging.h" + +// This code performs the ipc message validation. Potential security flaws +// on the ipc are likelier to be found in this code than in the rest of +// the ipc code. + +namespace { + +// The buffer for a message must match the max channel size. +const size_t kMaxBufferSize = sandbox::kIPCChannelSize; + +} + +namespace sandbox { + +// Returns the actual size for the parameters in an IPC buffer. Returns +// zero if the |param_count| is zero or too big. +uint32 GetActualBufferSize(uint32 param_count, void* buffer_base) { + // The template types are used to calculate the maximum expected size. + typedef ActualCallParams<1, kMaxBufferSize> ActualCP1; + typedef ActualCallParams<2, kMaxBufferSize> ActualCP2; + typedef ActualCallParams<3, kMaxBufferSize> ActualCP3; + typedef ActualCallParams<4, kMaxBufferSize> ActualCP4; + typedef ActualCallParams<5, kMaxBufferSize> ActualCP5; + typedef ActualCallParams<6, kMaxBufferSize> ActualCP6; + typedef ActualCallParams<7, kMaxBufferSize> ActualCP7; + typedef ActualCallParams<8, kMaxBufferSize> ActualCP8; + typedef ActualCallParams<9, kMaxBufferSize> ActualCP9; + + // Retrieve the actual size and the maximum size of the params buffer. + switch (param_count) { + case 0: + return 0; + case 1: + return reinterpret_cast<ActualCP1*>(buffer_base)->GetSize(); + case 2: + return reinterpret_cast<ActualCP2*>(buffer_base)->GetSize(); + case 3: + return reinterpret_cast<ActualCP3*>(buffer_base)->GetSize(); + case 4: + return reinterpret_cast<ActualCP4*>(buffer_base)->GetSize(); + case 5: + return reinterpret_cast<ActualCP5*>(buffer_base)->GetSize(); + case 6: + return reinterpret_cast<ActualCP6*>(buffer_base)->GetSize(); + case 7: + return reinterpret_cast<ActualCP7*>(buffer_base)->GetSize(); + case 8: + return reinterpret_cast<ActualCP8*>(buffer_base)->GetSize(); + case 9: + return reinterpret_cast<ActualCP9*>(buffer_base)->GetSize(); + default: + NOTREACHED(); + return 0; + } +} + +CrossCallParamsEx::CrossCallParamsEx() + :CrossCallParams(0, 0) { +} + +// We override the delete operator because the object's backing memory +// is hand allocated in CreateFromBuffer. We don't override the new operator +// because the constructors are private so there is no way to mismatch +// new & delete. +void CrossCallParamsEx::operator delete(void* raw_memory) throw() { + if (NULL == raw_memory) { + // C++ standard allows 'delete 0' behavior. + return; + } + delete[] reinterpret_cast<char*>(raw_memory); +} + +// This function uses a SEH try block so cannot use C++ objects that +// have destructors or else you get Compiler Error C2712. So no DCHECKs +// inside this function. +CrossCallParamsEx* CrossCallParamsEx::CreateFromBuffer(void* buffer_base, + uint32 buffer_size, + uint32* output_size) { + // IMPORTANT: Everything inside buffer_base and derived from it such + // as param_count and declared_size is untrusted. + if (NULL == buffer_base) { + return NULL; + } + if (buffer_size < sizeof(CrossCallParams)) { + return NULL; + } + if (buffer_size > kMaxBufferSize) { + return NULL; + } + + char* backing_mem = NULL; + uint32 param_count = 0; + uint32 declared_size; + uint32 min_declared_size; + CrossCallParamsEx* copied_params = NULL; + + // Touching the untrusted buffer is done under a SEH try block. This + // will catch memory access violations so we don't crash. + __try { + CrossCallParams* call_params = + reinterpret_cast<CrossCallParams*>(buffer_base); + + // Check against the minimum size given the number of stated params + // if too small we bail out. + param_count = call_params->GetParamsCount(); + min_declared_size = sizeof(CrossCallParams) + + ((param_count + 1) * sizeof(ParamInfo)); + + if ((buffer_size < min_declared_size) || + (sizeof(CrossCallParamsEx) > min_declared_size)) { + // Minimal computed size bigger than existing buffer or param_count + // integer overflow. + return NULL; + } + + // Retrieve the declared size which if it fails returns 0. + declared_size = GetActualBufferSize(param_count, buffer_base); + + if ((declared_size > buffer_size) || + (declared_size < min_declared_size)) { + // Declared size is bigger than buffer or smaller than computed size + // or param_count 0 or bigger than 9. + return NULL; + } + + // Now we copy the actual amount of the message. + *output_size = declared_size; + backing_mem = new char[declared_size]; + copied_params = reinterpret_cast<CrossCallParamsEx*>(backing_mem); + memcpy(backing_mem, call_params, declared_size); + + // Check params count in case it got changed right before the memcpy. + if (copied_params->GetParamsCount() != param_count) { + delete [] backing_mem; + return NULL; + } + + } __except(EXCEPTION_EXECUTE_HANDLER) { + // In case of a windows exception we know it occurred while touching the + // untrusted buffer so we bail out as is. + delete [] backing_mem; + return NULL; + } + + const char* last_byte = &backing_mem[declared_size]; + const char* first_byte = &backing_mem[min_declared_size]; + + // Verify here that all and each parameters make sense. This is done in the + // local copy. + for (uint32 ix =0; ix != param_count; ++ix) { + uint32 size = 0; + ArgType type; + char* address = reinterpret_cast<char*>( + copied_params->GetRawParameter(ix, &size, &type)); + if ((NULL == address) || // No null params. + (INVALID_TYPE >= type) || (LAST_TYPE <= type) || // Unknown type. + (address < backing_mem) || // Start cannot point before buffer. + (address < first_byte) || // Start cannot point too low. + (address > last_byte) || // Start cannot point past buffer. + ((address + size) < address) || // Invalid size. + ((address + size) > last_byte)) { // End cannot point past buffer. + // Malformed. + delete[] backing_mem; + return NULL; + } + } + // The parameter buffer looks good. + return copied_params; +} + +// Accessors to the parameters in the raw buffer. +void* CrossCallParamsEx::GetRawParameter(uint32 index, uint32* size, + ArgType* type) { + if (index >= GetParamsCount()) { + return NULL; + } + // The size is always computed from the parameter minus the next + // parameter, this works because the message has an extra parameter slot + *size = param_info_[index].size_; + *type = param_info_[index].type_; + + return param_info_[index].offset_ + reinterpret_cast<char*>(this); +} + +// Covers common case for 32 bit integers. +bool CrossCallParamsEx::GetParameter32(uint32 index, uint32* param) { + uint32 size = 0; + ArgType type; + void* start = GetRawParameter(index, &size, &type); + if ((NULL == start) || (4 != size) || (ULONG_TYPE != type)) { + return false; + } + // Copy the 4 bytes. + *(reinterpret_cast<uint32*>(param)) = *(reinterpret_cast<uint32*>(start)); + return true; +} + +bool CrossCallParamsEx::GetParameterVoidPtr(uint32 index, void** param) { + uint32 size = 0; + ArgType type; + void* start = GetRawParameter(index, &size, &type); + if ((NULL == start) || (sizeof(void*) != size) || (VOIDPTR_TYPE != type)) { + return false; + } + *param = *(reinterpret_cast<void**>(start)); + return true; +} + +// Covers the common case of reading a string. Note that the string is not +// scanned for invalid characters. +bool CrossCallParamsEx::GetParameterStr(uint32 index, std::wstring* string) { + uint32 size = 0; + ArgType type; + void* start = GetRawParameter(index, &size, &type); + if (WCHAR_TYPE != type) { + return false; + } + + // Check if this is an empty string. + if (size == 0) { + *string = L""; + return true; + } + + if ((NULL == start) || ((size % sizeof(wchar_t)) != 0)) { + return false; + } + string->append(reinterpret_cast<wchar_t*>(start), size/(sizeof(wchar_t))); + return true; +} + +bool CrossCallParamsEx::GetParameterPtr(uint32 index, uint32 expected_size, + void** pointer) { + uint32 size = 0; + ArgType type; + void* start = GetRawParameter(index, &size, &type); + + if ((size != expected_size) || (INOUTPTR_TYPE != type)) { + return false; + } + + if (NULL == start) { + return false; + } + + *pointer = start; + return true; +} + +void SetCallError(ResultCode error, CrossCallReturn* call_return) { + call_return->call_outcome = error; + call_return->extended_count = 0; +} + +void SetCallSuccess(CrossCallReturn* call_return) { + call_return->call_outcome = SBOX_ALL_OK; +} + +Dispatcher* Dispatcher::OnMessageReady(IPCParams* ipc, + CallbackGeneric* callback) { + DCHECK(callback); + std::vector<IPCCall>::iterator it = ipc_calls_.begin(); + for (; it != ipc_calls_.end(); ++it) { + if (it->params.Matches(ipc)) { + *callback = it->callback; + return this; + } + } + return NULL; +} + +} // namespace sandbox diff --git a/pool/shard007/C++/0094619_index_view.cpp b/pool/shard007/C++/0094619_index_view.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f1e92811006797c3d74210542db0658c67b5e869 --- /dev/null +++ b/pool/shard007/C++/0094619_index_view.cpp @@ -0,0 +1,140 @@ +// Copyright 2017 MongoDB Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include <bsoncxx/stdx/make_unique.hpp> +#include <bsoncxx/string/to_string.hpp> +#include <mongocxx/client_session.hpp> +#include <mongocxx/exception/private/mongoc_error.hh> +#include <mongocxx/index_view.hpp> +#include <mongocxx/options/index_view.hpp> +#include <mongocxx/private/index_view.hh> + +#include <mongocxx/config/private/prelude.hh> + +namespace mongocxx { +MONGOCXX_INLINE_NAMESPACE_BEGIN + +index_view::index_view(void* coll, void* client) + : _impl{stdx::make_unique<impl>(static_cast<mongoc_collection_t*>(coll), + static_cast<mongoc_client_t*>(client))} {} + +index_view::index_view(index_view&&) noexcept = default; +index_view& index_view::operator=(index_view&&) noexcept = default; +index_view::~index_view() = default; + +cursor index_view::list() { + return _get_impl().list(nullptr); +} + +cursor index_view::list(const client_session& session) { + return _get_impl().list(&session); +} + +bsoncxx::stdx::optional<std::string> index_view::create_one( + const bsoncxx::document::view_or_value& keys, + const bsoncxx::document::view_or_value& index_options, + const options::index_view& options) { + return create_one(index_model{keys, index_options}, options); +} + +bsoncxx::stdx::optional<std::string> index_view::create_one( + const client_session& session, + const bsoncxx::document::view_or_value& keys, + const bsoncxx::document::view_or_value& index_options, + const options::index_view& options) { + return create_one(session, index_model{keys, index_options}, options); +} + +bsoncxx::stdx::optional<std::string> index_view::create_one(const index_model& model, + const options::index_view& options) { + return _get_impl().create_one(nullptr, model, options); +} + +bsoncxx::stdx::optional<std::string> index_view::create_one(const client_session& session, + const index_model& model, + const options::index_view& options) { + return _get_impl().create_one(&session, model, options); +} + +bsoncxx::document::value index_view::create_many(const std::vector<index_model>& indexes, + const options::index_view& options) { + return _get_impl().create_many(nullptr, indexes, options); +} + +bsoncxx::document::value index_view::create_many(const client_session& session, + const std::vector<index_model>& indexes, + const options::index_view& options) { + return _get_impl().create_many(&session, indexes, options); +} + +void index_view::drop_one(bsoncxx::stdx::string_view name, const options::index_view& options) { + return _get_impl().drop_one(nullptr, name, options); +} + +void index_view::drop_one(const client_session& session, + bsoncxx::stdx::string_view name, + const options::index_view& options) { + return _get_impl().drop_one(&session, name, options); +} + +void index_view::drop_one(const bsoncxx::document::view_or_value& keys, + const bsoncxx::document::view_or_value& index_options, + const options::index_view& options) { + bsoncxx::document::view opts_view = index_options.view(); + + if (opts_view["name"]) { + drop_one(bsoncxx::string::to_string(opts_view["name"].get_string().value), options); + } else { + drop_one(_get_impl().get_index_name_from_keys(keys), options); + } +} + +void index_view::drop_one(const client_session& session, + const bsoncxx::document::view_or_value& keys, + const bsoncxx::document::view_or_value& index_options, + const options::index_view& options) { + bsoncxx::document::view opts_view = index_options.view(); + + if (opts_view["name"]) { + drop_one( + session, bsoncxx::string::to_string(opts_view["name"].get_string().value), options); + } else { + drop_one(session, _get_impl().get_index_name_from_keys(keys), options); + } +} + +void index_view::drop_one(const index_model& model, const options::index_view& options) { + drop_one(model.keys(), model.options(), options); +} + +void index_view::drop_one(const client_session& session, + const index_model& model, + const options::index_view& options) { + drop_one(session, model.keys(), model.options(), options); +} + +void index_view::drop_all(const options::index_view& options) { + _get_impl().drop_all(nullptr, options); +} + +void index_view::drop_all(const client_session& session, const options::index_view& options) { + _get_impl().drop_all(&session, options); +} + +index_view::impl& index_view::_get_impl() { + return *_impl; +} + +MONGOCXX_INLINE_NAMESPACE_END +} // namespace mongocxx diff --git a/pool/shard007/C++/0094620_back_forward_cache_commit_deferring_condition.cc b/pool/shard007/C++/0094620_back_forward_cache_commit_deferring_condition.cc new file mode 100644 index 0000000000000000000000000000000000000000..7b92ef04740e557c0d8aa1a0d5050b4a17ac7ee4 --- /dev/null +++ b/pool/shard007/C++/0094620_back_forward_cache_commit_deferring_condition.cc @@ -0,0 +1,61 @@ +// Copyright 2021 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 "content/browser/renderer_host/back_forward_cache_commit_deferring_condition.h" + +#include "base/memory/ptr_util.h" +#include "content/browser/renderer_host/back_forward_cache_impl.h" +#include "content/browser/renderer_host/frame_tree_node.h" +#include "content/browser/renderer_host/navigation_request.h" +#include "content/browser/renderer_host/navigator.h" + +namespace content { + +// static +std::unique_ptr<CommitDeferringCondition> +BackForwardCacheCommitDeferringCondition::MaybeCreate( + NavigationRequest& navigation_request) { + if (!navigation_request.IsServedFromBackForwardCache()) + return nullptr; + + // Currently only navigations in the primary main frame can restore pages + // from BFCache. + DCHECK(navigation_request.IsInPrimaryMainFrame()); + + return base::WrapUnique( + new BackForwardCacheCommitDeferringCondition(navigation_request)); +} + +BackForwardCacheCommitDeferringCondition:: + BackForwardCacheCommitDeferringCondition( + NavigationRequest& navigation_request) + : CommitDeferringCondition(navigation_request) {} + +BackForwardCacheCommitDeferringCondition:: + ~BackForwardCacheCommitDeferringCondition() = default; + +CommitDeferringCondition::Result +BackForwardCacheCommitDeferringCondition::WillCommitNavigation( + base::OnceClosure resume) { + DCHECK(GetNavigationHandle().IsServedFromBackForwardCache()); + + BackForwardCacheImpl& bfcache = + NavigationRequest::From(&GetNavigationHandle()) + ->frame_tree_node() + ->navigator() + .controller() + .GetBackForwardCache(); + + // If an entry doesn't exist (it was evicted?) there's no need to defer the + // commit as we'll end up performing a new navigation. + BackForwardCacheImpl::Entry* bfcache_entry = bfcache.GetEntry( + NavigationRequest::From(&GetNavigationHandle())->nav_entry_id()); + if (!bfcache_entry) + return Result::kProceed; + + bfcache.WillCommitNavigationToCachedEntry(*bfcache_entry, std::move(resume)); + return Result::kDefer; +} + +} // namespace content diff --git a/pool/shard007/C++/0094621_OXPropertyDescriptionPane.cpp b/pool/shard007/C++/0094621_OXPropertyDescriptionPane.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ca2be6ba59f5f9ad1337883f26a2f1eccc4bf14 --- /dev/null +++ b/pool/shard007/C++/0094621_OXPropertyDescriptionPane.cpp @@ -0,0 +1,84 @@ +// Version: 9.3 +// OXPropertyDescriptionPane.cpp : implementation file +// + +#include "stdafx.h" +#include "OXPropertyDescriptionPane.h" +#include "OXPropertiesWnd.h" +#include "OXSkins.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// COXPropertyDescriptionPane + +COXPropertyDescriptionPane::COXPropertyDescriptionPane() +{ + // Create the fonts + m_fontProperty.CreatePointFont(85, _T("Tahoma,,BOLD")); + m_fontDescription.CreatePointFont(85, _T("Tahoma")); +} + +COXPropertyDescriptionPane::~COXPropertyDescriptionPane() +{ +} + + +BEGIN_MESSAGE_MAP(COXPropertyDescriptionPane, CWnd) + //{{AFX_MSG_MAP(COXPropertyDescriptionPane) + ON_WM_PAINT() + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + + +///////////////////////////////////////////////////////////////////////////// +// COXPropertyDescriptionPane message handlers + +void COXPropertyDescriptionPane::SetDescription(LPCTSTR lpszProperty, LPCTSTR lpszDescription) +{ + m_strProperty = lpszProperty; + m_strDescription = lpszDescription; + Invalidate(); +} + + + +void COXPropertyDescriptionPane::OnPaint() +{ + CPaintDC dc(this); // device context for painting + + COXPropertiesWnd* pPropertiesWnd = (COXPropertiesWnd*) GetParent(); + COLORREF clrBackground = pPropertiesWnd->GetFrameSkin()->GetBackgroundColor(); + + CRect rectClient; + GetClientRect(rectClient); + dc.FillSolidRect(rectClient, clrBackground); + + // Draw the frame rectangle + rectClient.top += 4; + CBrush brush; + brush.CreateSolidBrush(clrBackground); + CPen pen; + pen.CreatePen(PS_SOLID, 1, pPropertiesWnd->GetFrameSkin()->GetBorderColor()); + CBrush* pOldBrush = dc.SelectObject(&brush); + CPen* pOldPen = dc.SelectObject(&pen); + dc.Rectangle(rectClient); + dc.SelectObject(pOldPen); + dc.SelectObject(pOldBrush); + + // Draw the text - property name first + CFont* pOldFont = dc.SelectObject(&m_fontProperty); + rectClient.DeflateRect(5, 3); + dc.DrawText(m_strProperty, rectClient, DT_SINGLELINE); + + // Draw the description + rectClient.top += 25; + dc.SelectObject(&m_fontDescription); + dc.DrawText(m_strDescription, rectClient, DT_SINGLELINE); + + dc.SelectObject(pOldFont); +} diff --git a/pool/shard007/C++/0094623_i420_video_frame.cc b/pool/shard007/C++/0094623_i420_video_frame.cc new file mode 100644 index 0000000000000000000000000000000000000000..b3943d54eb9069341399289880824c03693c44aa --- /dev/null +++ b/pool/shard007/C++/0094623_i420_video_frame.cc @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +#include "webrtc/common_video/interface/i420_video_frame.h" + +#include <string.h> + +#include <algorithm> // swap + +#include "webrtc/base/checks.h" + +namespace webrtc { + +I420VideoFrame::I420VideoFrame() + : timestamp_(0), + ntp_time_ms_(0), + render_time_ms_(0), + rotation_(kVideoRotation_0) { +} + +I420VideoFrame::I420VideoFrame( + const rtc::scoped_refptr<VideoFrameBuffer>& buffer, + uint32_t timestamp, + int64_t render_time_ms, + VideoRotation rotation) + : video_frame_buffer_(buffer), + timestamp_(timestamp), + ntp_time_ms_(0), + render_time_ms_(render_time_ms), + rotation_(rotation) { +} + +I420VideoFrame::~I420VideoFrame() {} + +int I420VideoFrame::CreateEmptyFrame(int width, int height, + int stride_y, int stride_u, int stride_v) { + const int half_width = (width + 1) / 2; + if (width <= 0 || height <= 0 || stride_y < width || stride_u < half_width || + stride_v < half_width) { + return -1; + } + // Creating empty frame - reset all values. + timestamp_ = 0; + ntp_time_ms_ = 0; + render_time_ms_ = 0; + rotation_ = kVideoRotation_0; + + // Check if it's safe to reuse allocation. + if (video_frame_buffer_ && + video_frame_buffer_->HasOneRef() && + !video_frame_buffer_->native_handle() && + width == video_frame_buffer_->width() && + height == video_frame_buffer_->height() && + stride_y == stride(kYPlane) && + stride_u == stride(kUPlane) && + stride_v == stride(kVPlane)) { + return 0; + } + + // Need to allocate new buffer. + video_frame_buffer_ = new rtc::RefCountedObject<I420Buffer>( + width, height, stride_y, stride_u, stride_v); + return 0; +} + +int I420VideoFrame::CreateFrame(int size_y, const uint8_t* buffer_y, + int size_u, const uint8_t* buffer_u, + int size_v, const uint8_t* buffer_v, + int width, int height, + int stride_y, int stride_u, int stride_v) { + return CreateFrame(size_y, buffer_y, size_u, buffer_u, size_v, buffer_v, + width, height, stride_y, stride_u, stride_v, + kVideoRotation_0); +} + +int I420VideoFrame::CreateFrame(int size_y, + const uint8_t* buffer_y, + int size_u, + const uint8_t* buffer_u, + int size_v, + const uint8_t* buffer_v, + int width, + int height, + int stride_y, + int stride_u, + int stride_v, + VideoRotation rotation) { + const int half_height = (height + 1) / 2; + const int expected_size_y = height * stride_y; + const int expected_size_u = half_height * stride_u; + const int expected_size_v = half_height * stride_v; + CHECK_GE(size_y, expected_size_y); + CHECK_GE(size_u, expected_size_u); + CHECK_GE(size_v, expected_size_v); + if (CreateEmptyFrame(width, height, stride_y, stride_u, stride_v) < 0) + return -1; + memcpy(buffer(kYPlane), buffer_y, expected_size_y); + memcpy(buffer(kUPlane), buffer_u, expected_size_u); + memcpy(buffer(kVPlane), buffer_v, expected_size_v); + rotation_ = rotation; + return 0; +} + +int I420VideoFrame::CopyFrame(const I420VideoFrame& videoFrame) { + if (videoFrame.native_handle()) { + video_frame_buffer_ = videoFrame.video_frame_buffer(); + } else { + int ret = CreateFrame( + videoFrame.allocated_size(kYPlane), videoFrame.buffer(kYPlane), + videoFrame.allocated_size(kUPlane), videoFrame.buffer(kUPlane), + videoFrame.allocated_size(kVPlane), videoFrame.buffer(kVPlane), + videoFrame.width(), videoFrame.height(), videoFrame.stride(kYPlane), + videoFrame.stride(kUPlane), videoFrame.stride(kVPlane)); + if (ret < 0) + return ret; + } + timestamp_ = videoFrame.timestamp_; + ntp_time_ms_ = videoFrame.ntp_time_ms_; + render_time_ms_ = videoFrame.render_time_ms_; + rotation_ = videoFrame.rotation_; + return 0; +} + +I420VideoFrame* I420VideoFrame::CloneFrame() const { + rtc::scoped_ptr<I420VideoFrame> new_frame(new I420VideoFrame()); + if (new_frame->CopyFrame(*this) == -1) { + // CopyFrame failed. + return NULL; + } + return new_frame.release(); +} + +void I420VideoFrame::SwapFrame(I420VideoFrame* videoFrame) { + video_frame_buffer_.swap(videoFrame->video_frame_buffer_); + std::swap(timestamp_, videoFrame->timestamp_); + std::swap(ntp_time_ms_, videoFrame->ntp_time_ms_); + std::swap(render_time_ms_, videoFrame->render_time_ms_); + std::swap(rotation_, videoFrame->rotation_); +} + +uint8_t* I420VideoFrame::buffer(PlaneType type) { + return video_frame_buffer_ ? video_frame_buffer_->data(type) : nullptr; +} + +const uint8_t* I420VideoFrame::buffer(PlaneType type) const { + // Const cast to call the correct const-version of data. + const VideoFrameBuffer* const_buffer = video_frame_buffer_.get(); + return const_buffer ? const_buffer->data(type) : nullptr; +} + +int I420VideoFrame::allocated_size(PlaneType type) const { + const int plane_height = (type == kYPlane) ? height() : (height() + 1) / 2; + return plane_height * stride(type); +} + +int I420VideoFrame::stride(PlaneType type) const { + return video_frame_buffer_ ? video_frame_buffer_->stride(type) : 0; +} + +int I420VideoFrame::width() const { + return video_frame_buffer_ ? video_frame_buffer_->width() : 0; +} + +int I420VideoFrame::height() const { + return video_frame_buffer_ ? video_frame_buffer_->height() : 0; +} + +bool I420VideoFrame::IsZeroSize() const { + return !video_frame_buffer_; +} + +void* I420VideoFrame::native_handle() const { + return video_frame_buffer_ ? video_frame_buffer_->native_handle() : nullptr; +} + +rtc::scoped_refptr<VideoFrameBuffer> I420VideoFrame::video_frame_buffer() + const { + return video_frame_buffer_; +} + +} // namespace webrtc diff --git a/pool/shard007/C++/0094624_perforcesubmiteditor.cpp b/pool/shard007/C++/0094624_perforcesubmiteditor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..115be50ad6f1bcd71a5dfd0eda39ded4330673d2 --- /dev/null +++ b/pool/shard007/C++/0094624_perforcesubmiteditor.cpp @@ -0,0 +1,165 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of Qt Creator. +** +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +****************************************************************************/ + +#include "perforcesubmiteditor.h" +#include "perforcesubmiteditorwidget.h" +#include "perforceplugin.h" + +#include <coreplugin/idocument.h> +#include <vcsbase/submitfilemodel.h> +#include <utils/qtcassert.h> + +#include <QRegularExpression> + +namespace Perforce { +namespace Internal { + +enum { FileSpecRole = Qt::UserRole + 1 }; + +PerforceSubmitEditor::PerforceSubmitEditor() : + VcsBaseSubmitEditor(new PerforceSubmitEditorWidget), + m_fileModel(new VcsBase::SubmitFileModel(this)) +{ + document()->setPreferredDisplayName(tr("Perforce Submit")); + setFileModel(m_fileModel); +} + +PerforceSubmitEditorWidget *PerforceSubmitEditor::submitEditorWidget() +{ + return static_cast<PerforceSubmitEditorWidget *>(widget()); +} + +QByteArray PerforceSubmitEditor::fileContents() const +{ + const_cast<PerforceSubmitEditor*>(this)->updateEntries(); + QString text; + QTextStream out(&text); + for (auto it = m_entries.cbegin(), end = m_entries.cend(); it != end; ++it) + out << it.key() << ":" << it.value(); + return text.toLocal8Bit(); +} + +bool PerforceSubmitEditor::setFileContents(const QByteArray &contents) +{ + if (!parseText(QString::fromUtf8(contents))) + return false; + updateFields(); + return true; +} + +bool PerforceSubmitEditor::parseText(QString text) +{ + QRegularExpression formField(QLatin1String("^\\S+:")); + const QString newLine = QString(QLatin1Char('\n')); + + int matchLen; + QTextStream stream(&text, QIODevice::ReadOnly); + QString line; + QString key; + QString value; + line = stream.readLine(); + while (!stream.atEnd()) { + const QRegularExpressionMatch match = formField.match(line); + if (match.hasMatch()) { + matchLen = match.capturedLength(); + key = line.left(matchLen-1); + value = line.mid(matchLen) + newLine; + while (!stream.atEnd()) { + line = stream.readLine(); + if (line.indexOf(formField) != -1) + break; + value += line + newLine; + } + m_entries.insert(key, value); + } else { + line = stream.readLine(); + } + } + return true; +} + +void PerforceSubmitEditor::restrictToProjectFiles(const QStringList &knownProjectFiles) +{ + m_fileModel->filterFiles(knownProjectFiles); +} + +void PerforceSubmitEditor::updateFields() +{ + PerforceSubmitEditorWidget *widget = submitEditorWidget(); + widget->setData(m_entries.value(QLatin1String("Change")).trimmed(), + m_entries.value(QLatin1String("Client")).trimmed(), + m_entries.value(QLatin1String("User")).trimmed()); + + const QChar newLine = QLatin1Char('\n'); + QStringList lines = m_entries.value(QLatin1String("Description")).split(newLine); + lines.removeFirst(); // that is the line break after 'Description:' + lines.removeLast(); // that is the empty line at the end + + const QRegularExpression leadingTabPattern("^\\t"); + QTC_CHECK(leadingTabPattern.isValid()); + + lines.replaceInStrings(leadingTabPattern, QString()); + widget->setDescriptionText(lines.join(newLine)); + + lines = m_entries.value(QLatin1String("Files")).split(newLine); + // split up "file#add" and store complete spec line as user data + foreach (const QString &specLine, lines) { + const QStringList list = specLine.split(QLatin1Char('#')); + if (list.size() == 2) { + const QString file = list.at(0).trimmed(); + const QString state = list.at(1).trimmed(); + m_fileModel->addFile(file, state).at(0)->setData(specLine, FileSpecRole); + } + } +} + +void PerforceSubmitEditor::updateEntries() +{ + const QChar newLine = QLatin1Char('\n'); + const QChar tab = QLatin1Char('\t'); + + QStringList lines = submitEditorWidget()->descriptionText().split(newLine); + + while (!lines.empty() && lines.last().isEmpty()) + lines.removeLast(); + // Description + lines.replaceInStrings(QRegularExpression("^"), tab); + m_entries.insert(QLatin1String("Description"), newLine + lines.join(newLine) + QLatin1String("\n\n")); + QString files = newLine; + // Re-build the file spec '<tab>file#add' from the user data + const int count = m_fileModel->rowCount(); + for (int r = 0; r < count; r++) { + const QStandardItem *item = m_fileModel->item(r, 0); + if (item->checkState() == Qt::Checked) { + files += item->data(FileSpecRole).toString(); + files += newLine; + } + } + files += newLine; + m_entries.insert(QLatin1String("Files"), files); +} + +} // Internal +} // Perforce diff --git a/pool/shard007/C++/0094627_moc_editaddressdialog.cpp b/pool/shard007/C++/0094627_moc_editaddressdialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..837a2d73e785250490585489b87d0e7438637a8a --- /dev/null +++ b/pool/shard007/C++/0094627_moc_editaddressdialog.cpp @@ -0,0 +1,94 @@ +/**************************************************************************** +** Meta object code from reading C++ file 'editaddressdialog.h' +** +** Created: Sun Feb 16 07:28:11 2014 +** by: The Qt Meta Object Compiler version 63 (Qt 4.8.1) +** +** WARNING! All changes made in this file will be lost! +*****************************************************************************/ + +#include "../src/qt/editaddressdialog.h" +#if !defined(Q_MOC_OUTPUT_REVISION) +#error "The header file 'editaddressdialog.h' doesn't include <QObject>." +#elif Q_MOC_OUTPUT_REVISION != 63 +#error "This file was generated using the moc from 4.8.1. It" +#error "cannot be used with the include files from this version of Qt." +#error "(The moc has changed too much.)" +#endif + +QT_BEGIN_MOC_NAMESPACE +static const uint qt_meta_data_EditAddressDialog[] = { + + // content: + 6, // revision + 0, // classname + 0, 0, // classinfo + 1, 14, // methods + 0, 0, // properties + 0, 0, // enums/sets + 0, 0, // constructors + 0, // flags + 0, // signalCount + + // slots: signature, parameters, type, tag, flags + 19, 18, 18, 18, 0x0a, + + 0 // eod +}; + +static const char qt_meta_stringdata_EditAddressDialog[] = { + "EditAddressDialog\0\0accept()\0" +}; + +void EditAddressDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) +{ + if (_c == QMetaObject::InvokeMetaMethod) { + Q_ASSERT(staticMetaObject.cast(_o)); + EditAddressDialog *_t = static_cast<EditAddressDialog *>(_o); + switch (_id) { + case 0: _t->accept(); break; + default: ; + } + } + Q_UNUSED(_a); +} + +const QMetaObjectExtraData EditAddressDialog::staticMetaObjectExtraData = { + 0, qt_static_metacall +}; + +const QMetaObject EditAddressDialog::staticMetaObject = { + { &QDialog::staticMetaObject, qt_meta_stringdata_EditAddressDialog, + qt_meta_data_EditAddressDialog, &staticMetaObjectExtraData } +}; + +#ifdef Q_NO_DATA_RELOCATION +const QMetaObject &EditAddressDialog::getStaticMetaObject() { return staticMetaObject; } +#endif //Q_NO_DATA_RELOCATION + +const QMetaObject *EditAddressDialog::metaObject() const +{ + return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; +} + +void *EditAddressDialog::qt_metacast(const char *_clname) +{ + if (!_clname) return 0; + if (!strcmp(_clname, qt_meta_stringdata_EditAddressDialog)) + return static_cast<void*>(const_cast< EditAddressDialog*>(this)); + return QDialog::qt_metacast(_clname); +} + +int EditAddressDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) +{ + _id = QDialog::qt_metacall(_c, _id, _a); + if (_id < 0) + return _id; + if (_c == QMetaObject::InvokeMetaMethod) { + if (_id < 1) + qt_static_metacall(this, _c, _id, _a); + _id -= 1; + } + return _id; +} +QT_END_MOC_NAMESPACE diff --git a/pool/shard007/C++/0094628_receiverequestdialog.cpp b/pool/shard007/C++/0094628_receiverequestdialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c69c9c8ba89700f335642b43498561f7860cc66d --- /dev/null +++ b/pool/shard007/C++/0094628_receiverequestdialog.cpp @@ -0,0 +1,209 @@ +// Copyright (c) 2011-2015 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "receiverequestdialog.h" +#include "ui_receiverequestdialog.h" + +#include "infinitumunits.h" +#include "guiconstants.h" +#include "guiutil.h" +#include "optionsmodel.h" +#include "walletmodel.h" + +#include <QClipboard> +#include <QDrag> +#include <QMenu> +#include <QMimeData> +#include <QMouseEvent> +#include <QPixmap> +#if QT_VERSION < 0x050000 +#include <QUrl> +#endif + +#if defined(HAVE_CONFIG_H) +#include "config/infinitum-config.h" /* for USE_QRCODE */ +#endif + +#ifdef USE_QRCODE +#include <qrencode.h> +#endif + +QRImageWidget::QRImageWidget(QWidget *parent): + QLabel(parent), contextMenu(0) +{ + contextMenu = new QMenu(); + QAction *saveImageAction = new QAction(tr("&Save Image..."), this); + connect(saveImageAction, SIGNAL(triggered()), this, SLOT(saveImage())); + contextMenu->addAction(saveImageAction); + QAction *copyImageAction = new QAction(tr("&Copy Image"), this); + connect(copyImageAction, SIGNAL(triggered()), this, SLOT(copyImage())); + contextMenu->addAction(copyImageAction); +} + +QImage QRImageWidget::exportImage() +{ + if(!pixmap()) + return QImage(); + return pixmap()->toImage(); +} + +void QRImageWidget::mousePressEvent(QMouseEvent *event) +{ + if(event->button() == Qt::LeftButton && pixmap()) + { + event->accept(); + QMimeData *mimeData = new QMimeData; + mimeData->setImageData(exportImage()); + + QDrag *drag = new QDrag(this); + drag->setMimeData(mimeData); + drag->exec(); + } else { + QLabel::mousePressEvent(event); + } +} + +void QRImageWidget::saveImage() +{ + if(!pixmap()) + return; + QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Image (*.png)"), NULL); + if (!fn.isEmpty()) + { + exportImage().save(fn); + } +} + +void QRImageWidget::copyImage() +{ + if(!pixmap()) + return; + QApplication::clipboard()->setImage(exportImage()); +} + +void QRImageWidget::contextMenuEvent(QContextMenuEvent *event) +{ + if(!pixmap()) + return; + contextMenu->exec(event->globalPos()); +} + +ReceiveRequestDialog::ReceiveRequestDialog(QWidget *parent) : + QDialog(parent), + ui(new Ui::ReceiveRequestDialog), + model(0) +{ + ui->setupUi(this); + +#ifndef USE_QRCODE + ui->btnSaveAs->setVisible(false); + ui->lblQRCode->setVisible(false); +#endif + + connect(ui->btnSaveAs, SIGNAL(clicked()), ui->lblQRCode, SLOT(saveImage())); +} + +ReceiveRequestDialog::~ReceiveRequestDialog() +{ + delete ui; +} + +void ReceiveRequestDialog::setModel(OptionsModel *model) +{ + this->model = model; + + if (model) + connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(update())); + + // update the display unit if necessary + update(); +} + +void ReceiveRequestDialog::setInfo(const SendCoinsRecipient &info) +{ + this->info = info; + update(); +} + +void ReceiveRequestDialog::update() +{ + if(!model) + return; + QString target = info.label; + if(target.isEmpty()) + target = info.address; + setWindowTitle(tr("Request payment to %1").arg(target)); + + QString uri = GUIUtil::formatInfinitumURI(info); + ui->btnSaveAs->setEnabled(false); + QString html; + html += "<html><font face='verdana, arial, helvetica, sans-serif'>"; + html += "<b>"+tr("Payment information")+"</b><br>"; + html += "<b>"+tr("URI")+"</b>: "; + html += "<a href=\""+uri+"\">" + GUIUtil::HtmlEscape(uri) + "</a><br>"; + html += "<b>"+tr("Address")+"</b>: " + GUIUtil::HtmlEscape(info.address) + "<br>"; + if(info.amount) + html += "<b>"+tr("Amount")+"</b>: " + InfinitumUnits::formatHtmlWithUnit(model->getDisplayUnit(), info.amount) + "<br>"; + if(!info.label.isEmpty()) + html += "<b>"+tr("Label")+"</b>: " + GUIUtil::HtmlEscape(info.label) + "<br>"; + if(!info.message.isEmpty()) + html += "<b>"+tr("Message")+"</b>: " + GUIUtil::HtmlEscape(info.message) + "<br>"; + ui->outUri->setText(html); + +#ifdef USE_QRCODE + ui->lblQRCode->setText(""); + if(!uri.isEmpty()) + { + // limit URI length + if (uri.length() > MAX_URI_LENGTH) + { + ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); + } else { + QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); + if (!code) + { + ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); + return; + } + QImage qrImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); + qrImage.fill(0xffffff); + unsigned char *p = code->data; + for (int y = 0; y < code->width; y++) + { + for (int x = 0; x < code->width; x++) + { + qrImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); + p++; + } + } + QRcode_free(code); + + QImage qrAddrImage = QImage(QR_IMAGE_SIZE, QR_IMAGE_SIZE+20, QImage::Format_RGB32); + qrAddrImage.fill(0xffffff); + QPainter painter(&qrAddrImage); + painter.drawImage(0, 0, qrImage.scaled(QR_IMAGE_SIZE, QR_IMAGE_SIZE)); + QFont font = GUIUtil::fixedPitchFont(); + font.setPixelSize(12); + painter.setFont(font); + QRect paddedRect = qrAddrImage.rect(); + paddedRect.setHeight(QR_IMAGE_SIZE+12); + painter.drawText(paddedRect, Qt::AlignBottom|Qt::AlignCenter, info.address); + painter.end(); + + ui->lblQRCode->setPixmap(QPixmap::fromImage(qrAddrImage)); + ui->btnSaveAs->setEnabled(true); + } + } +#endif +} + +void ReceiveRequestDialog::on_btnCopyURI_clicked() +{ + GUIUtil::setClipboard(GUIUtil::formatInfinitumURI(info)); +} + +void ReceiveRequestDialog::on_btnCopyAddress_clicked() +{ + GUIUtil::setClipboard(info.address); +} diff --git a/pool/shard007/C++/0094630_drive_app_registry_unittest.cc b/pool/shard007/C++/0094630_drive_app_registry_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..d5dfd6c37d261636793777c98c2fdf184fee2661 --- /dev/null +++ b/pool/shard007/C++/0094630_drive_app_registry_unittest.cc @@ -0,0 +1,224 @@ +// 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 "components/drive/drive_app_registry.h" + +#include "base/files/file_path.h" +#include "base/macros.h" +#include "base/message_loop/message_loop.h" +#include "base/run_loop.h" +#include "base/values.h" +#include "components/drive/drive_app_registry_observer.h" +#include "components/drive/service/fake_drive_service.h" +#include "google_apis/drive/drive_api_parser.h" +#include "google_apis/drive/test_util.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace drive { + +class TestDriveAppRegistryObserver : public DriveAppRegistryObserver { + public: + explicit TestDriveAppRegistryObserver(DriveAppRegistry* registry) + : registry_(registry), + update_count_(0) { + registry_->AddObserver(this); + } + ~TestDriveAppRegistryObserver() override { registry_->RemoveObserver(this); } + + int update_count() const { return update_count_; } + + private: + // DriveAppRegistryObserver overrides: + void OnDriveAppRegistryUpdated() override { ++update_count_; } + + DriveAppRegistry* registry_; + int update_count_; + DISALLOW_COPY_AND_ASSIGN(TestDriveAppRegistryObserver); +}; + +class DriveAppRegistryTest : public testing::Test { + protected: + void SetUp() override { + fake_drive_service_.reset(new FakeDriveService); + fake_drive_service_->LoadAppListForDriveApi("drive/applist.json"); + + apps_registry_.reset(new DriveAppRegistry(fake_drive_service_.get())); + } + + bool VerifyApp(const std::vector<DriveAppInfo>& list, + const std::string& app_id, + const std::string& app_name) { + bool found = false; + for (size_t i = 0; i < list.size(); ++i) { + const DriveAppInfo& app = list[i]; + if (app_id == app.app_id) { + EXPECT_EQ(app_name, app.app_name); + found = true; + break; + } + } + EXPECT_TRUE(found) << "Unable to find app with app_id " << app_id; + return found; + } + + base::MessageLoop message_loop_; + scoped_ptr<FakeDriveService> fake_drive_service_; + scoped_ptr<DriveAppRegistry> apps_registry_; +}; + +TEST_F(DriveAppRegistryTest, BasicParse) { + TestDriveAppRegistryObserver observer(apps_registry_.get()); + + apps_registry_->Update(); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(1, observer.update_count()); + + std::vector<DriveAppInfo> apps; + apps_registry_->GetAppList(&apps); + + ASSERT_EQ(2u, apps.size()); + EXPECT_EQ("123456788192", apps[0].app_id); + EXPECT_EQ("Drive app 1", apps[0].app_name); + EXPECT_EQ("https://www.example.com/createForApp1", + apps[0].create_url.spec()); + EXPECT_EQ("abcdefghabcdefghabcdefghabcdefgh", apps[0].product_id); + EXPECT_TRUE(apps[0].is_removable); +} + +TEST_F(DriveAppRegistryTest, LoadAndFindDriveApps) { + TestDriveAppRegistryObserver observer(apps_registry_.get()); + + apps_registry_->Update(); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(1, observer.update_count()); + + // Find by primary extension 'exe'. + std::vector<DriveAppInfo> ext_results; + base::FilePath ext_file(FILE_PATH_LITERAL("drive/file.exe")); + apps_registry_->GetAppsForFile(ext_file.Extension(), "", &ext_results); + ASSERT_EQ(1U, ext_results.size()); + VerifyApp(ext_results, "123456788192", "Drive app 1"); + + // Find by primary MIME type. + std::vector<DriveAppInfo> primary_app; + apps_registry_->GetAppsForFile(base::FilePath::StringType(), + "application/vnd.google-apps.drive-sdk.123456788192", &primary_app); + ASSERT_EQ(1U, primary_app.size()); + VerifyApp(primary_app, "123456788192", "Drive app 1"); + + // Find by secondary MIME type. + std::vector<DriveAppInfo> secondary_app; + apps_registry_->GetAppsForFile( + base::FilePath::StringType(), "text/html", &secondary_app); + ASSERT_EQ(1U, secondary_app.size()); + VerifyApp(secondary_app, "123456788192", "Drive app 1"); +} + +TEST_F(DriveAppRegistryTest, UpdateFromAppList) { + scoped_ptr<base::Value> app_info_value = + google_apis::test_util::LoadJSONFile("drive/applist.json"); + scoped_ptr<google_apis::AppList> app_list( + google_apis::AppList::CreateFrom(*app_info_value)); + + TestDriveAppRegistryObserver observer(apps_registry_.get()); + apps_registry_->UpdateFromAppList(*app_list); + EXPECT_EQ(1, observer.update_count()); + + // Confirm that something was loaded from applist.json. + std::vector<DriveAppInfo> ext_results; + base::FilePath ext_file(FILE_PATH_LITERAL("drive/file.exe")); + apps_registry_->GetAppsForFile(ext_file.Extension(), "", &ext_results); + ASSERT_EQ(1U, ext_results.size()); +} + +TEST_F(DriveAppRegistryTest, MultipleUpdate) { + TestDriveAppRegistryObserver observer(apps_registry_.get()); + + // Call Update(). + apps_registry_->Update(); + EXPECT_EQ(0, observer.update_count()); + + // Call Update() again. + // This call should be ignored because there is already an ongoing update. + apps_registry_->Update(); + EXPECT_EQ(0, observer.update_count()); + + // The app list should be loaded only once. + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(1, fake_drive_service_->app_list_load_count()); + EXPECT_EQ(1, observer.update_count()); +} + +TEST(DriveAppRegistryUtilTest, FindPreferredIcon_Empty) { + DriveAppInfo::IconList icons; + EXPECT_EQ("", + util::FindPreferredIcon(icons, util::kPreferredIconSize).spec()); +} + +TEST(DriveAppRegistryUtilTest, FindPreferredIcon_) { + const char kSmallerIconUrl[] = "http://example.com/smaller.png"; + const char kMediumIconUrl[] = "http://example.com/medium.png"; + const char kBiggerIconUrl[] = "http://example.com/bigger.png"; + const int kMediumSize = 16; + + DriveAppInfo::IconList icons; + // The icons are not sorted by the size. + icons.push_back(std::make_pair(kMediumSize, + GURL(kMediumIconUrl))); + icons.push_back(std::make_pair(kMediumSize + 2, + GURL(kBiggerIconUrl))); + icons.push_back(std::make_pair(kMediumSize - 2, + GURL(kSmallerIconUrl))); + + // Exact match. + EXPECT_EQ(kMediumIconUrl, + util::FindPreferredIcon(icons, kMediumSize).spec()); + // The requested size is in-between of smaller.png and + // medium.png. medium.png should be returned. + EXPECT_EQ(kMediumIconUrl, + util::FindPreferredIcon(icons, kMediumSize - 1).spec()); + // The requested size is smaller than the smallest icon. The smallest icon + // should be returned. + EXPECT_EQ(kSmallerIconUrl, + util::FindPreferredIcon(icons, kMediumSize - 3).spec()); + // The requested size is larger than the largest icon. The largest icon + // should be returned. + EXPECT_EQ(kBiggerIconUrl, + util::FindPreferredIcon(icons, kMediumSize + 3).spec()); +} + +TEST_F(DriveAppRegistryTest, UninstallDriveApp) { + apps_registry_->Update(); + base::RunLoop().RunUntilIdle(); + + std::vector<DriveAppInfo> apps; + apps_registry_->GetAppList(&apps); + size_t original_count = apps.size(); + + // Uninstall an existing app. + google_apis::DriveApiErrorCode error = google_apis::DRIVE_OTHER_ERROR; + apps_registry_->UninstallApp( + "123456788192", + google_apis::test_util::CreateCopyResultCallback(&error)); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(error, google_apis::HTTP_NO_CONTENT); + + // Check that the number of apps is decreased by one. + apps_registry_->GetAppList(&apps); + EXPECT_EQ(original_count - 1, apps.size()); + + // Try to uninstall a non-existing app. + error = google_apis::DRIVE_OTHER_ERROR; + apps_registry_->UninstallApp( + "non-existing-app-id", + google_apis::test_util::CreateCopyResultCallback(&error)); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(error, google_apis::HTTP_NOT_FOUND); + + // Check that the number is not changed this time. + apps_registry_->GetAppList(&apps); + EXPECT_EQ(original_count - 1, apps.size()); +} + +} // namespace drive diff --git a/pool/shard007/C++/0094631_statistics.cpp b/pool/shard007/C++/0094631_statistics.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d4c9c294b3fd0319267f2d4d44e077653a0ffee1 --- /dev/null +++ b/pool/shard007/C++/0094631_statistics.cpp @@ -0,0 +1,122 @@ +/* TA3D, a remake of Total Annihilation + Copyright (C) 2005 Roland BROCHARD + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA*/ + +#include "statistics.h" +#include <ta3dbase.h> +#include <EngineClass.h> +#include <ingame/players.h> +#include <input/mouse.h> +#include <input/keyboard.h> + + + +namespace TA3D +{ +namespace Menus +{ + + + bool Statistics::Execute() + { + Statistics m; + return m.execute(); + } + + + + Statistics::Statistics() + :Abstract() + {} + + Statistics::~Statistics() + {} + + + void Statistics::doUpdateObject(const String& id, const short indx, const uint32 color, const String& value) + { + String nameID("statistics."); + nameID << id << indx; + pArea->caption(nameID, value); + Gui::GUIOBJ::Ptr o = pArea->get_object(nameID); + if (o) + o->Data = color; + } + + bool Statistics::doInitialize() + { + LOG_DEBUG(LOG_PREFIX_MENU_STATS << "Entering..."); + gfx->set_2D_mode(); + gfx->ReInitTexSys(); + loadAreaFromTDF("statistics", "gui/statistics.area"); + + // Statistics for All players + for (short i = 0; i < short(players.count()); ++i) + { + uint32 color = gfx->makeintcol(player_color[3 * player_color_map[i]], + player_color[3 * player_color_map[i] + 1], + player_color[3 * player_color_map[i] + 2]); + + doUpdateObject("player", i, color, players.nom[i]); + doUpdateObject("side", i, color, players.side[i]); + doUpdateObject("losses", i, color, String(players.losses[i])); + doUpdateObject("kills", i, color, String(players.kills[i])); + doUpdateObject("energy", i, color, String((int)players.energy_total[i])); + doUpdateObject("metal", i, color, String((int)players.metal_total[i])); + } + return true; + } + + + void Statistics::doFinalize() + { + // Do nothing + LOG_DEBUG(LOG_PREFIX_MENU_STATS << "Done."); + } + + + void Statistics::waitForEvent() + { + bool keyIsPressed(false); + do + { + // Grab user events + pArea->check(); + // Get if a key was pressed + keyIsPressed = pArea->key_pressed; + // Wait to reduce CPU consumption + wait(); + + } while (pMouseX == mouse_x && pMouseY == mouse_y && pMouseZ == mouse_z && pMouseB == mouse_b + && mouse_b == 0 + && !key[KEY_ENTER] && !key[KEY_ESC] && !key[KEY_SPACE] + && !keyIsPressed && !pArea->scrolling); + } + + + bool Statistics::maySwitchToAnotherMenu() + { + // Exit + return (key[KEY_SPACE] || key[KEY_ENTER] || key[KEY_ESC] || pArea->get_state("statistics.b_ok")); + } + + + + +} // namespace Menus +} // namespace TA3D + + diff --git a/pool/shard007/C++/0094635_lw1-01.cpp b/pool/shard007/C++/0094635_lw1-01.cpp new file mode 100644 index 0000000000000000000000000000000000000000..505e10d4dd727132b35037c4cf899f62b5ffb52f --- /dev/null +++ b/pool/shard007/C++/0094635_lw1-01.cpp @@ -0,0 +1,24 @@ +#include "stdafx.h" + +void printEvenInHandred() +{ + const int LOWER_BOUND = 1; + const int UPPER_BOUND = 100; + const int STEP = 2; + + for (int i = UPPER_BOUND / STEP * STEP; i > LOWER_BOUND; i -= STEP) + { + printf("%3d", i); + if (i - LOWER_BOUND >= STEP) + { + printf(", "); + } + } + printf("\n"); +} + +int main(int argc, char* argv[]) +{ + printEvenInHandred(); + return 0; +} \ No newline at end of file diff --git a/pool/shard007/C++/0094639_nckDemo_Quadtree.cpp b/pool/shard007/C++/0094639_nckDemo_Quadtree.cpp new file mode 100644 index 0000000000000000000000000000000000000000..358e271ee27c05d4e23e8c1e62a78d69f0d10667 --- /dev/null +++ b/pool/shard007/C++/0094639_nckDemo_Quadtree.cpp @@ -0,0 +1,76 @@ + +/** +* NCtoolKit © 2007-2017 Luís F.Loureiro, under zlib software license. +* https://github.com/nczeroshift/nctoolkit +*/ + +#include "nckDemo_Quadtree.h" + +Demo_Quadtree::Demo_Quadtree(Core::Window * wnd, Graph::Device * dev){ + this->dev = dev; + this->wnd = wnd; + time = 0; +} + +Demo_Quadtree::~Demo_Quadtree(){ + +} + +void Demo_Quadtree::Load(){ + // Enable z test + dev->Enable(Graph::STATE_DEPTH_TEST); + + // Set correct states for alpha blending. + dev->Enable(Graph::STATE_BLEND); + dev->BlendFunc(Graph::BLEND_SRC_ALPHA, Graph::BLEND_INV_SRC_ALPHA); +} + +void Demo_Quadtree::Render(float dt){ + // Clear graphics rendering buffer. + dev->Clear(); + + // Define the rendering area in window space. + dev->Viewport(0,0,wnd->GetWidth(),wnd->GetHeight()); + + // Set projection matrix. + dev->MatrixMode(Graph::MATRIX_PROJECTION); + dev->Identity(); + + dev->Ortho2D(wnd->GetWidth(),wnd->GetHeight()); + + // Set the view (camera) matrix. + dev->MatrixMode(Graph::MATRIX_VIEW); + dev->Identity(); + + + // Set the model matrix. + dev->MatrixMode(Graph::MATRIX_MODEL); + dev->Identity(); + + + + time += dt; + + // Finish rendering and present the graphics. + dev->PresentAll(); +} + +void Demo_Quadtree::UpdateWndEvents(){ + +} + +std::vector<std::string> Demo_Quadtree::GetKeywords() { + std::vector<std::string> ret; + ret.push_back("TODO"); + //ret.push_back("Basic"); + //ret.push_back("Quadtree"); + return ret; +} + +std::string Demo_Quadtree::GetDescription() { + return "Quadtree Structure Usage"; +} + +Demo * CreateDemo_Quadtree(Core::Window * wnd, Graph::Device * dev){ + return new Demo_Quadtree(wnd,dev); +} diff --git a/pool/shard007/C++/0094641_handzone.cpp b/pool/shard007/C++/0094641_handzone.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a5b97548d1a24275ca1700e936bee892919dee42 --- /dev/null +++ b/pool/shard007/C++/0094641_handzone.cpp @@ -0,0 +1,142 @@ +#include <QPainter> +#include "handzone.h" +#include "settingscache.h" +#include "thememanager.h" +#include "player.h" +#include "carddragitem.h" +#include "carditem.h" + +#include "pb/command_move_card.pb.h" + +HandZone::HandZone(Player *_p, bool _contentsKnown, int _zoneHeight, QGraphicsItem *parent) + : SelectZone(_p, "hand", false, false, _contentsKnown, parent), zoneHeight(_zoneHeight) +{ + connect(themeManager, SIGNAL(themeChanged()), this, SLOT(updateBg())); + updateBg(); + setCacheMode(DeviceCoordinateCache); +} + +void HandZone::updateBg() +{ + update(); +} + +void HandZone::addCardImpl(CardItem *card, int x, int /*y*/) +{ + if (x == -1) + x = cards.size(); + cards.insert(x, card); + + if (!cards.getContentsKnown()) { + card->setId(-1); + card->setName(); + } + card->setParentItem(this); + card->resetState(); + card->setVisible(true); + card->update(); +} + +void HandZone::handleDropEvent(const QList<CardDragItem *> &dragItems, CardZone *startZone, const QPoint & dropPoint) +{ + QPoint point = dropPoint + scenePos().toPoint(); + int x = -1; + if (settingsCache->getHorizontalHand()) { + for (x = 0; x < cards.size(); x++) + if (point.x() < static_cast<CardItem *>(cards.at(x))->scenePos().x()) + break; + } else { + for (x = 0; x < cards.size(); x++) + if (point.y() < static_cast<CardItem *>(cards.at(x))->scenePos().y()) + break; + } + + Command_MoveCard cmd; + cmd.set_start_player_id(startZone->getPlayer()->getId()); + cmd.set_start_zone(startZone->getName().toStdString()); + cmd.set_target_player_id(player->getId()); + cmd.set_target_zone(getName().toStdString()); + cmd.set_x(x); + cmd.set_y(-1); + + for (int i = 0; i < dragItems.size(); ++i) + cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId()); + + player->sendGameCommand(cmd); +} + +QRectF HandZone::boundingRect() const +{ + if (settingsCache->getHorizontalHand()) + return QRectF(0, 0, width, CARD_HEIGHT + 10); + else + return QRectF(0, 0, 100, zoneHeight); +} + +void HandZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) +{ + painter->fillRect(boundingRect(), themeManager->getHandBgBrush()); +} + +void HandZone::reorganizeCards() +{ + if (!cards.isEmpty()) { + const int cardCount = cards.size(); + if (settingsCache->getHorizontalHand()) { + bool leftJustified = settingsCache->getLeftJustified(); + qreal cardWidth = cards.at(0)->boundingRect().width(); + const int xPadding = leftJustified ? cardWidth * 1.4 : 5; + qreal totalWidth = leftJustified? boundingRect().width() - (1 * xPadding) - 5 : boundingRect().width() - 2 * xPadding; + + for (int i = 0; i < cardCount; i++) { + CardItem *c = cards.at(i); + // If the total width of the cards is smaller than the available width, + // the cards do not need to overlap and are displayed in the center of the area. + if (cardWidth * cardCount > totalWidth) + c->setPos(xPadding + ((qreal) i) * (totalWidth - cardWidth) / (cardCount - 1), 5); + else { + qreal xPosition = leftJustified ? xPadding + ((qreal) i) * cardWidth : + xPadding + ((qreal) i) * cardWidth + (totalWidth - cardCount * cardWidth) / 2; + c->setPos(xPosition, 5); + } + c->setRealZValue(i); + } + } else { + qreal totalWidth = boundingRect().width(); + qreal totalHeight = boundingRect().height(); + qreal cardWidth = cards.at(0)->boundingRect().width(); + qreal cardHeight = cards.at(0)->boundingRect().height(); + qreal xspace = 5; + qreal x1 = xspace; + qreal x2 = totalWidth - xspace - cardWidth; + + for (int i = 0; i < cardCount; i++) { + CardItem *c = cards.at(i); + qreal x = (i % 2) ? x2 : x1; + // If the total height of the cards is smaller than the available height, + // the cards do not need to overlap and are displayed in the center of the area. + if (cardHeight * cardCount > totalHeight) + c->setPos(x, ((qreal) i) * (totalHeight - cardHeight) / (cardCount - 1)); + else + c->setPos(x, ((qreal) i) * cardHeight + (totalHeight - cardCount * cardHeight) / 2); + c->setRealZValue(i); + } + } + } + update(); +} + +void HandZone::setWidth(qreal _width) +{ + if (settingsCache->getHorizontalHand()) { + prepareGeometryChange(); + width = _width; + reorganizeCards(); + } +} + +void HandZone::updateOrientation() +{ + prepareGeometryChange(); + reorganizeCards(); +} diff --git a/pool/shard007/C++/0094642_DeprecatedAlgorithm.cpp b/pool/shard007/C++/0094642_DeprecatedAlgorithm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..862cce4fb1b2d10242a8fecfb129f9161933db9f --- /dev/null +++ b/pool/shard007/C++/0094642_DeprecatedAlgorithm.cpp @@ -0,0 +1,87 @@ +#include "MantidAPI/DeprecatedAlgorithm.h" +#include "MantidAPI/AlgorithmFactory.h" +#include "MantidKernel/DateAndTime.h" +#include "MantidKernel/Logger.h" +#include <sstream> + +namespace Mantid { +namespace API { +namespace { +/// Static logger +Kernel::Logger g_log("DeprecatedAlgorithm"); +} + +/// Does nothing other than make the compiler happy. +DeprecatedAlgorithm::DeprecatedAlgorithm() + : m_replacementAlgorithm(), m_replacementVersion(-1), m_deprecatedDate() {} + +/// Does nothing other than make the compiler happy. +DeprecatedAlgorithm::~DeprecatedAlgorithm() = default; + +/// The algorithm to use instead of this one. +/// @param replacement Name of the algorithm that replaces the deprecated one +/// @param version An optional version number for the replacement (default=-1) +void DeprecatedAlgorithm::useAlgorithm(const std::string &replacement, + const int version) { + // Replacement is not checked here as we cannot guarantee all algorithms have + // been + // registered when we are called. It is checked when the message is about to + // be printed + if (!replacement.empty()) + this->m_replacementAlgorithm = replacement; + else + this->m_replacementAlgorithm = ""; + + m_replacementVersion = version; +} + +/// The date the algorithm was deprecated on +void DeprecatedAlgorithm::deprecatedDate(const std::string &date) { + this->m_deprecatedDate = ""; + if (date.empty()) { + // TODO warn people that it wasn't set + return; + } + if (!Kernel::DateAndTime::stringIsISO8601(date)) { + // TODO warn people that it wasn't set + return; + } + this->m_deprecatedDate = date; +} + +/// This merely prints the deprecation error for people to see. +const std::string DeprecatedAlgorithm::deprecationMsg(const IAlgorithm *algo) { + std::stringstream msg; + if (algo != nullptr) + msg << algo->name() << " is "; + + msg << "deprecated"; + + if (!this->m_deprecatedDate.empty()) + msg << " (on " << this->m_deprecatedDate << ")"; + + if (this->m_replacementAlgorithm.empty()) { + msg << " and has no replacement."; + } else { + // sanity check + if (!AlgorithmFactory::Instance().exists(this->m_replacementAlgorithm, + this->m_replacementVersion)) { + std::ostringstream msg; + msg << "Invalid replacement algorithm '" + this->m_replacementAlgorithm + + "'"; + if (this->m_replacementVersion > 0) + msg << " version " << this->m_replacementVersion << "\n"; + msg << "Replacement algorithm not registered."; + g_log.warning(msg.str()); + } + + msg << ". Use " << this->m_replacementAlgorithm; + if (this->m_replacementVersion > 0) + msg << " version " << this->m_replacementVersion; + msg << " instead."; + } + + return msg.str(); +} +} // namesapce API +} // namespace Mantid diff --git a/pool/shard007/C++/0094644_example7.cc b/pool/shard007/C++/0094644_example7.cc new file mode 100644 index 0000000000000000000000000000000000000000..5aa55025192c46010c07a35bc248f6de4b5e7ae5 --- /dev/null +++ b/pool/shard007/C++/0094644_example7.cc @@ -0,0 +1,88 @@ +/** + * \file + * \remark This file is part of VITA. + * \details Building blocks infrastructure test. + * + * \copyright Copyright (C) 2011-2018 EOS di Manlio Morini. + * + * \license + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/ + */ + +#include <iostream> +#include <fstream> + +#include "kernel/vita.h" + +int main(int argc, char *argv[]) +{ + using namespace vita; + + problem p; + + p.env.init(); + p.env.mep.code_length = static_cast<unsigned>(argc > 1 + ? std::atoi(argv[1]) : 100); + const auto n(static_cast<unsigned>(argc > 2 ? std::atoi(argv[2]) : 1)); + + symbol_factory factory; + p.sset.insert(factory.make(domain_t::d_double, -200, 200)); + p.sset.insert(factory.make("FADD")); + p.sset.insert(factory.make("FSUB")); + p.sset.insert(factory.make("FMUL")); + p.sset.insert(factory.make("FIFL")); + p.sset.insert(factory.make("FIFE")); + p.sset.insert(factory.make("FABS")); + p.sset.insert(factory.make("FLN")); + + distribution<double> individuals, blocks_len, blocks_n, arguments; + + for (unsigned k(0); k < n; ++k) + { + i_mep base(p); + auto base_es(base.active_symbols()); + while (base_es < 5) + { + base = i_mep(p); + base_es = base.active_symbols(); + } + + individuals.add(base_es); + + std::cout << std::string(40, '-') << '\n' << base << '\n'; + + auto bl(base.blocks()); + for (auto i(bl.begin()); i != bl.end(); ++i) + { + i_mep ib(base.get_block(*i)); + + auto generalized(ib.generalize(2, p.sset)); + + std::cout << '\n' << ib + << "GENERALIZED\n" << generalized.first + << "\nArguments: ["; + for (const auto &l : generalized.second) + std::cout << ' ' << l; + std::cout << " ]\n"; + + blocks_len.add(ib.active_symbols()); + arguments.add(static_cast<double>(generalized.second.size())); + } + } + + std::cout << std::string(40, '-') + << "\nIndividuals effective lengths.\nMin: " << individuals.min() + << " Mean: " << individuals.mean() + << " StdDev: " << individuals.standard_deviation() + << " Max: " << individuals.max() + << "\nBlocks effective lengths.\nMin: " << blocks_len.min() + << " Mean: " << blocks_len.mean() + << " StdDev: " << std::sqrt(blocks_len.variance()) + << " Max: " << blocks_len.max() + << "\nNumber of arguments.\nMin: " << arguments.min() + << " Mean: " << arguments.mean() + << " StdDev: " << arguments.standard_deviation() + << " Max: " << arguments.max() << std::endl; +} diff --git a/pool/shard007/C++/0094654_CompoundFile.cpp b/pool/shard007/C++/0094654_CompoundFile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e732c2787c0fb49f91d67de1b9ad007f1a5ae783 --- /dev/null +++ b/pool/shard007/C++/0094654_CompoundFile.cpp @@ -0,0 +1,268 @@ +/* + * (c) Copyright Ascensio System SIA 2010-2019 + * + * This program is a free software product. You can redistribute it and/or + * modify it under the terms of the GNU Affero General Public License (AGPL) + * version 3 as published by the Free Software Foundation. In accordance with + * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect + * that Ascensio System SIA expressly excludes the warranty of non-infringement + * of any third-party rights. + * + * This program is distributed WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For + * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html + * + * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha + * street, Riga, Latvia, EU, LV-1050. + * + * The interactive user interfaces in modified source and object code versions + * of the Program must display Appropriate Legal Notices, as required under + * Section 5 of the GNU AGPL version 3. + * + * Pursuant to Section 7(b) of the License you must retain the original Product + * logo when distributing the program. Pursuant to Section 7(e) we decline to + * grant you any rights under trademark law for use of our trademarks. + * + * All the Product's GUI elements, including illustrations and icon sets, as + * well as technical writing content are licensed under the terms of the + * Creative Commons Attribution-ShareAlike 4.0 International. See the License + * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode + * + */ + +#include "CompoundFile.h" +#include "CFStream.h" + +#include <sstream> + +namespace XLS +{ + + +CompoundFile::~CompoundFile() +{ + streams.clear(); + + if (storage_)delete storage_; + storage_ = NULL; +} + +bool CompoundFile::isError() +{ + if (storage_ != NULL) return false; + return true; +} + +bool CompoundFile::Open(const std::wstring & file_path, const ReadWriteMode mode) +{ + if (storage_) delete storage_; + storage_ = NULL; + + rwMode = mode; + + unsigned int grfMode = 0; + + storage_ = new POLE::Storage(file_path.c_str()); + if (storage_ == NULL) return false; + + switch(rwMode) + { + case cf_ReadMode: + { + if (storage_->open(false, false) == false) + { + delete storage_; + storage_ = NULL; + } + + }break; + case cf_WriteMode: + { + if (storage_->open(true, true) == false) + { + delete storage_; + storage_ = NULL; + } + }break; + } + + if (storage_ == NULL) return false; + return true; +} + + +CompoundFile::CompoundFile(const std::wstring & file_path, const ReadWriteMode mode) +{ + storage_ = NULL; + Open(file_path, mode); +} + +void CompoundFile::copy_stream(std::wstring streamNameOpen, std::wstring streamNameCreate, POLE::Storage * storageOut, bool bWithRoot) +{ + POLE::Stream *stream = new POLE::Stream(storage_, streamNameOpen); + if (!stream) return; + + stream->seek(0); + POLE::uint64 size_stream = stream->size(); + + if (bWithRoot == false) + { + int pos = streamNameCreate.find(L"/"); + if (pos >= 0) + streamNameCreate = streamNameCreate.substr(pos + 1); + } + + POLE::Stream *streamNew = new POLE::Stream(storageOut, streamNameCreate, true, size_stream); + if (!streamNew) return; + + unsigned char buffer[4096]; + int bytesRead = 0; + + while(true) + { + int bytesToRead = size_stream - bytesRead; + if (bytesToRead <= 0) + break; + if (bytesToRead > 4096) + bytesToRead = 4096; + + stream->read(buffer, bytesToRead); + streamNew->write(buffer, bytesToRead); + + bytesRead += bytesToRead; + } + //unsigned char* data_stream = new unsigned char[size_stream + 64]; + //memset(data_stream, 0, size_stream + 64); + //if (data_stream) + //{ + // stream->read(data_stream, size_stream); + + // streamNew->write(data_stream, size_stream); + + // delete []data_stream; + // data_stream = NULL; + //} + + streamNew->flush(); + + delete streamNew; + delete stream; +} + +void CompoundFile::copy( int indent, std::wstring path, POLE::Storage * storageOut, bool bWithRoot, bool bSortFiles) +{ + std::list<std::wstring> entries, entries_files, entries_dir; + + entries = storage_->entries_with_prefix( path ); + + for( std::list<std::wstring>::iterator it = entries.begin(); it != entries.end(); ++it ) + { + std::wstring fullname = path + *it; + + if ((it->at(0) >= 32) && (storage_->isDirectory( fullname ) )) + { + entries_dir.push_back(*it); + } + else + { + entries_files.push_front(*it); + } + } + + for( std::list<std::wstring>::iterator it = entries_dir.begin(); it != entries_dir.end(); ++it ) + { + std::wstring fullname = path + *it; + + copy( indent + 1, fullname + L"/", storageOut, bWithRoot, bSortFiles ); + } + + //entries_files.sort(); + + for( std::list<std::wstring>::iterator it = entries_files.begin(); it != entries_files.end(); ++it ) + { + std::wstring createName = path + *it; + std::wstring openName; + + if (it->at(0) < 32) openName = path + it->substr(1); + else openName = path + *it; + + copy_stream(openName, createName, storageOut, bWithRoot); + } +} +CFStreamPtr CompoundFile::getWorkbookStream() +{ + CFStreamPtr stream = getNamedStream(L"Workbook"); + + if (stream == NULL) + stream = getNamedStream(L"WORKBOOK"); //6447323.xls + if (stream == NULL) + stream = getNamedStream(L"Book"); + if (stream == NULL) + stream = getNamedStream(L"BOOK");//file(6).xls + if (stream == NULL) + stream = getNamedStream(L"book"); + return stream; +} + +CFStreamPtr CompoundFile::getNamedStream(const std::wstring& name) +{ + if(!streams[name]) + { + POLE::Stream * pStream = openStream(name.c_str()); + if (pStream) + streams[name].reset(new CFStream(pStream)); + } + return streams[name]; +} + +CFStreamPtr CompoundFile::createNamedStream(const std::wstring& name) +{ + if(!streams[name]) + { + POLE::Stream * pStream = createStream(name.c_str()); + if (pStream) + streams[name].reset(new CFStream(pStream)); + } + return streams[name]; +} + + +void CompoundFile::closeNamedStream(const std::wstring& name) +{ + streams[name].reset(); +} + + +// Opens a stream in the storage (shall be called not more than once per stream) +POLE::Stream* CompoundFile::openStream(const std::wstring & stream_name) +{ + if (storage_ == NULL) return NULL; + + POLE::Stream* pStream = new POLE::Stream(storage_, stream_name); + if(pStream == NULL) + { + return NULL; + } + if ((pStream) && (pStream->size() > 0)) + return pStream; + else return NULL; +} + + +// Creates a new stream in the storage +POLE::Stream* CompoundFile::createStream(const std::wstring & stream_name) +{ + if (storage_ == NULL) return NULL; + + POLE::Stream* pStream = new POLE::Stream(storage_, stream_name, true); + if(pStream == NULL) + { + return NULL; + } + return pStream; +} + + +} // namespace XLS + + diff --git a/pool/shard007/C++/0094657_raytracer.cpp b/pool/shard007/C++/0094657_raytracer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..76bb102e4bb2976aa022421199a210961a275985 --- /dev/null +++ b/pool/shard007/C++/0094657_raytracer.cpp @@ -0,0 +1,37 @@ +#include <thread> +#include <renderer.hpp> +#include <fensterchen.hpp> + + +int main(int argc, char* argv[]) +{ + if (argc != 2) { + std::cout << "usage: raytracer file.sdf\n"; + return 1; + } + Scene scene = loadSDF(argv[1]); + unsigned const width = scene.width; + unsigned const height = scene.height; + std::string const filename = "./checkerboard.ppm"; + + Renderer app(scene, width, height, filename); + + std::thread thr([&app]() { app.render(); }); + + Window win(glm::ivec2(width,height)); + + while (!win.shouldClose()) { + if (win.isKeyPressed(GLFW_KEY_ESCAPE)) { + win.stop(); + } + + glDrawPixels( width, height, GL_RGB, GL_FLOAT + , app.colorbuffer().data()); + + win.update(); + } + + thr.join(); + + return 0; +} diff --git a/pool/shard007/C++/0094659_main.cpp b/pool/shard007/C++/0094659_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a40dd28d8f4880c06608f61740031983e88452cf --- /dev/null +++ b/pool/shard007/C++/0094659_main.cpp @@ -0,0 +1,34 @@ +#include "mainwindow.h" +#include <QApplication> +#include <QSplitter> +#include <QFileSystemModel> +#include <QTreeView> +#include <QListView> +//#include <duilib2.h> + +int main(int argc, char *argv[]) +{ +// QApplication a(argc, argv); +// MainWindow w; +// w.show(); + + QApplication app(argc, argv); + QSplitter *splitter = new QSplitter; + + QFileSystemModel *model = new QFileSystemModel; + model->setRootPath(QDir::currentPath()); + + QTreeView *tree = new QTreeView(splitter); + tree->setModel(model); + tree->setRootIndex(model->index(QDir::currentPath())); + + QListView *list = new QListView(splitter); + list->setModel(model); + list->setRootIndex(model->index(QDir::currentPath())); + + splitter->setWindowTitle("Two views onto the same file system model"); + splitter->show(); + return app.exec(); + + //return a.exec(); +} diff --git a/pool/shard007/C++/0094661_re_posix.cc b/pool/shard007/C++/0094661_re_posix.cc new file mode 100644 index 0000000000000000000000000000000000000000..e8fe1fc9e0107a8277fe904da988023efb5cbfa0 --- /dev/null +++ b/pool/shard007/C++/0094661_re_posix.cc @@ -0,0 +1,59 @@ +// Copyright 2015 Google Inc. 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 "check.h" +#include "re.h" + +namespace benchmark { + +Regex::Regex() : init_(false) { } + +bool Regex::Init(const std::string& spec, std::string* error) { + int ec = regcomp(&re_, spec.c_str(), REG_EXTENDED | REG_NOSUB); + if (ec != 0) { + if (error) { + size_t needed = regerror(ec, &re_, NULL, 0); + char* errbuf = new char[needed]; + regerror(ec, &re_, errbuf, needed); + + // regerror returns the number of bytes necessary to null terminate + // the string, so we move that when assigning to error. + CHECK_NE(needed, 0); + error->assign(errbuf, needed - 1); + + delete[] errbuf; + } + + return false; + } + + init_ = true; + return true; +} + +Regex::~Regex() { + if (init_) { + regfree(&re_); + } +} + +bool Regex::Match(const std::string& str) { + if (!init_) { + return false; + } + + return regexec(&re_, str.c_str(), 0, NULL, 0) == 0; +} + +} // end namespace benchmark diff --git a/pool/shard007/C++/0094665_hdsensorslist.cpp b/pool/shard007/C++/0094665_hdsensorslist.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8cbfa135830618de1b3cff7476f1eb05c5fc39f6 --- /dev/null +++ b/pool/shard007/C++/0094665_hdsensorslist.cpp @@ -0,0 +1,171 @@ +/*************************************************************************** + hdsensorslist.cpp - description + ------------------- + begin : vie abr 26 2002 + copyright : (C) 2002 by Miguel Novas + email : michaell@teleline.es + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include <stdio.h> +#include <string.h> +#include <unistd.h> +#include <dirent.h> +#include <sys/types.h> +#include <stdlib.h> +#include <qstringlist.h> +#include <klocale.h> +#include <qregexp.h> + +#include "sensor.h" +#include "hdsensorslist.h" + + +HDSensorsList::HDSensorsList(QObject *parent, const char * name): SensorsList(parent,name) +{ + process= 0; + + setDescription( QString(i18n("Hard Disks")) ); + + setClass(Sensor::hdSensor); + + readConfig(); + + if(!isHddTempInstalled()) return; + + QStringList disks; + if(!getDisks(disks)) return; + + for(QStringList::Iterator it = disks.begin(); it != disks.end(); ++it ) { + ProcessExec proc; + proc << "hddtemp" << "-q"; + proc << *it; + if(proc.runAndWait()) { + double value; + QString str; + if(getDiskInfo(proc.getStdoutData(),str,value)) { + Sensor *sensor= new Sensor(this); + sensor->setType(Sensor::lmTemp); + sensor->setName(*it); + sensor->setDescription(str); + sensor->setValueMax (40 , Sensor::dgCelsius); + sensor->setValueMin ( 0 , Sensor::dgCelsius); + sensor->setValueIdeal(value, Sensor::dgCelsius); + sensor->setValue (value, Sensor::dgCelsius); + sensor->readConfig(); + } + } + } +} + +HDSensorsList::~HDSensorsList() +{ + delete process; +} + +//************* + +void HDSensorsList::updateSensors() +{ + if(process) return; + + QObjectList *list= (QObjectList *)children(); + if(!list) return; + + QStringList params; + for(Sensor *obj= (Sensor *)list->first(); obj!=0; obj= (Sensor *)list->next()) + if(obj->monitorized()) + params << obj->name(); + + if(params.count()>0) { + process= new ProcessExec; + *process << "hddtemp" << "-q" << params; + connect( process, SIGNAL(processExited(KProcess *)), this, SLOT(slotProcessExited(KProcess *)) ); + process->run(); + } +} + +void HDSensorsList::slotProcessExited(KProcess *) +{ + QObjectList *list= (QObjectList *)children(); + + if (!list) return; + + if (process->outputErrors()) + qWarning("HddTemp Error:\n%s", process->getStdoutData().ascii()); + + QStringList buf = QStringList::split(QChar('\n'), process->getStdoutData()); + for(QStringList::Iterator it = buf.begin(); it != buf.end(); ++it ) { + for(Sensor *obj= (Sensor *)list->first(); obj!=0; obj= (Sensor *)list->next()) { + QRegExp rx(QString(obj->name()) + QString(":\\s+.+:\\s+(\\d+).*C")); + if (rx.search((*it)) > -1) + obj->setValue(rx.cap(1).toDouble(), Sensor::dgCelsius); + } + } + delete process; + process= 0; +} + +// *************** Static methods + + +bool HDSensorsList::getDiskInfo(const QString buf, QString &name, double &value) +{ + QRegExp rx(":\\s+(.+):\\s+(\\d+).*C"); + + if (rx.search(buf) > -1) { + bool ok; + name = rx.cap(1); + value = rx.cap(2).toDouble(&ok); + if (ok) + return true; + else + return false; + } + else + return false; +} + + +bool HDSensorsList::isHddTempInstalled() +{ + ProcessExec proc; + + proc << "hddtemp" << "-v" ; + if(proc.runAndWait()) { + if(proc.getStdoutData().contains("ERROR")==0) return true; + qWarning("HddTemp Error:\n%s", proc.getStdoutData().ascii()); + } + return false; +} + +bool HDSensorsList::getDisks(QStringList &disks ) +{ + DIR *dir; + + /* Get a listing of the hard drives looking under sysfs first then falling back to /proc/ide */ + if((dir = opendir ("/sys/block")) == NULL) + if ((dir = opendir ("/proc/ide")) == NULL) + return false; + QString str; + struct dirent *ptr; + while((ptr= readdir(dir))) { + if((ptr->d_name[0]=='h' || ptr->d_name[0]=='s') && ptr->d_name[1]=='d') { + str.sprintf("/dev/%s",ptr->d_name); + disks << str; + } + } + closedir(dir); + return true; +} + +// *************** + diff --git a/pool/shard007/C++/0094668_D3.cpp b/pool/shard007/C++/0094668_D3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..844b772f04077e4e5adcd123f0c35aab4299d03d --- /dev/null +++ b/pool/shard007/C++/0094668_D3.cpp @@ -0,0 +1,36 @@ +#include <iostream> +#include <string> +using namespace std; + +long long power(long long x, long long n) { + if (n == 0) { + return 1; + } else if (n%2 == 1) { + return (x * power(x, n-1)); + } else { + long long half = power(x, n/2); + return (half * half); + } +} + +long long under_count(long long N, long long x) { + // N未満の自然数に、xが何個あるか。ただしxは1から9。 + // Nは10^16くらいまで + long long ans = 0; + for (auto i=0; i<16; i++) { + ans += N/power(10, i+1) * power(10, i); + long long y = N%power(10, i+1); + if (power(10, i) * x < y && y <= power(10, i) * (x+1)) { + ans += y - power(10, i) * x; + } else if (power(10, i) * (x+1) < y) { + ans += power(10, i); + } + } + return ans; +} + +int main() { + long long N; + cin >> N; + cout << under_count(N+1, 1) << endl; +} diff --git a/pool/shard007/C++/0094669_clustering_nonparametric_bayes.cc b/pool/shard007/C++/0094669_clustering_nonparametric_bayes.cc new file mode 100644 index 0000000000000000000000000000000000000000..64074b7b03390730918a3a1d942fce62cfb15eb7 --- /dev/null +++ b/pool/shard007/C++/0094669_clustering_nonparametric_bayes.cc @@ -0,0 +1,137 @@ +#include <Eigen/Core> +#include <Eigen/LU> +#include <iostream> +#include <iomanip> +#include <vector> +#include <cmath> +#include <string> +#include <sstream> +#include <random> +#include "ProbDistributions.h" +#include "DataSet.h" +#include "Cluster.h" +using namespace std; + +int dim = 0; + +int pickCandidateCluster(vector<int> *bincount,double d = 0.0) +{ + vector<double> prob_list; + const double alpha = 0.8; + int n = accumulate(bincount->begin(),bincount->end(),0.0); + int n_k = 0; + int i = 0; + for(auto bin : *bincount){ + n_k += bin; + prob_list.push_back(((double)n_k - d*(i+1))/(n + alpha)); + } + + double r = pd.uniformRand(0.0,1.0); + int candidate_cluster = 0; + for(auto p : prob_list){ + if(r < p) + break; + candidate_cluster++; + } + + return candidate_cluster; +} + +double densityMultiNormal(Data &d, Cluster &c) +{ + Eigen::MatrixXd info = c.cov.inverse(); + Eigen::VectorXd mu = c.mean;//[0],c.mean[1]); + Eigen::VectorXd diff = d.normalized_data - mu; + + double det = c.cov.determinant(); + double a = 1.0/ (pow(2 * 3.151592,c.dimension*0.5) * sqrt(det)); + double exp_part = -0.5 * diff.transpose() * info * diff; + + return a*exp(exp_part); +} + +bool resampling(DataSet *ds, Clusters *cs, Data *d, vector<int> &bin) +{ + int org_c_num = (int)cs->c.size(); + bin[d->cluster_id]--; + int candidate_cluster = pickCandidateCluster(&bin); + bin[d->cluster_id]++; + + if(candidate_cluster == d->cluster_id){ + return false; + } + + Cluster *old_cluster = &(cs->c[d->cluster_id]); + double eval_new = 0.0; + double eval_old = densityMultiNormal(*d,*old_cluster); + Cluster c(dim); + if(candidate_cluster == org_c_num){//新しいクラスタ + eval_new = densityMultiNormal(*d,c); + }else{//既存のクラスタ + eval_new = densityMultiNormal(*d,cs->c[candidate_cluster]); + } + + double acceptance = eval_new/eval_old; + if(pd.uniformRand(0.0,1.0) >= acceptance) + return false; + + bin[d->cluster_id]--; + d->cluster_id = candidate_cluster; + if(candidate_cluster == org_c_num){ + cs->c.push_back(c); + bin.push_back(1); + }else + bin[candidate_cluster]++; + return true; +} + +void sweep(DataSet *ds,Clusters *cs) +{ + vector<int> bincount(cs->c.size(),0); + for(auto x : ds->x){ + bincount[x.cluster_id]++; + } + + int chance = 3; + for(auto &target : ds->x){ + for(int i=0;i<chance;i++){ + resampling(ds,cs,&target,bincount); + } + } + //どのクラスタに標本が幾つかる数える + for(auto &c : cs->c){ + c.clear(); + } + for(auto &d : ds->x){ + cs->c[d.cluster_id].regData(&d); + } + cs->calcParams(); + cerr << "----" << endl; +} + +int main(int argc, char const* argv[]) +{ + Clusters cs; + DataSet ds; + dim = ds.read(); + if(dim <= 0) + exit(1); + + int sweep_num = 50; + + //最初のクラスタを作る。平均値は1軸ごとにガウス分布からサンプリング + cs.c.push_back(Cluster(dim)); + for(auto &d : ds.x){ + cs.c[d.cluster_id].regData(&d); + } + cs.calcParams(); + cerr << "----" << endl; + + for(int k=0;k<sweep_num;k++){ + cerr << "sweep " << k << endl; + sweep(&ds,&cs); + } + ds.print(); + + exit(0); +} diff --git a/pool/shard007/C++/0094679_DistanceConstraint.cpp b/pool/shard007/C++/0094679_DistanceConstraint.cpp new file mode 100644 index 0000000000000000000000000000000000000000..44ea7194a5a350aea246d04cd61eb6caaa314bdb --- /dev/null +++ b/pool/shard007/C++/0094679_DistanceConstraint.cpp @@ -0,0 +1,103 @@ +// $Id$ +// +// Copyright (C) 2013 Paolo Tosco +// +// Copyright (C) 2004-2006 Rational Discovery LLC +// +// @@ All Rights Reserved @@ +// This file is part of the RDKit. +// The contents are covered by the terms of the BSD license +// which is included in the file license.txt, found at the root +// of the RDKit source tree. +// +#include "DistanceConstraint.h" +#include <cmath> +#include <ForceField/ForceField.h> +#include <RDGeneral/Invariant.h> + +namespace ForceFields { +namespace UFF { +DistanceConstraintContrib::DistanceConstraintContrib( + ForceField *owner, unsigned int idx1, unsigned int idx2, double minLen, + double maxLen, double forceConst) { + PRECONDITION(owner, "bad owner"); + URANGE_CHECK(idx1, owner->positions().size() - 1); + URANGE_CHECK(idx2, owner->positions().size() - 1); + PRECONDITION(maxLen >= minLen, "bad bounds"); + + dp_forceField = owner; + d_end1Idx = idx1; + d_end2Idx = idx2; + d_minLen = minLen; + d_maxLen = maxLen; + d_forceConstant = forceConst; +} + +DistanceConstraintContrib::DistanceConstraintContrib( + ForceField *owner, unsigned int idx1, unsigned int idx2, bool relative, + double minLen, double maxLen, double forceConst) { + PRECONDITION(owner, "bad owner"); + const RDGeom::PointPtrVect &pos = owner->positions(); + URANGE_CHECK(idx1, pos.size() - 1); + URANGE_CHECK(idx2, pos.size() - 1); + PRECONDITION(maxLen >= minLen, "bad bounds"); + + double dist = 0.0; + if (relative) { + RDGeom::Point3D p1 = *((RDGeom::Point3D *)pos[idx1]); + RDGeom::Point3D p2 = *((RDGeom::Point3D *)pos[idx2]); + dist = (p1 - p2).length(); + } + dp_forceField = owner; + d_end1Idx = idx1; + d_end2Idx = idx2; + d_minLen = std::max(dist + minLen, 0.0); + d_maxLen = std::max(dist + maxLen, 0.0); + d_forceConstant = forceConst; +} + +double DistanceConstraintContrib::getEnergy(double *pos) const { + PRECONDITION(dp_forceField, "no owner"); + PRECONDITION(pos, "bad vector"); + + double dist = dp_forceField->distance(d_end1Idx, d_end2Idx, pos); + double distTerm = 0.0; + if (dist < d_minLen) { + distTerm = d_minLen - dist; + } else if (dist > d_maxLen) { + distTerm = dist - d_maxLen; + } + double res = 0.5 * d_forceConstant * distTerm * distTerm; + + return res; +} + +void DistanceConstraintContrib::getGrad(double *pos, double *grad) const { + PRECONDITION(dp_forceField, "no owner"); + PRECONDITION(pos, "bad vector"); + PRECONDITION(grad, "bad vector"); + + double dist = dp_forceField->distance(d_end1Idx, d_end2Idx, pos); + + double preFactor = 0.0; + if (dist < d_minLen) { + preFactor = dist - d_minLen; + } else if (dist > d_maxLen) { + preFactor = dist - d_maxLen; + } else { + return; + } + preFactor *= d_forceConstant; + + double *end1Coords = &(pos[3 * d_end1Idx]); + double *end2Coords = &(pos[3 * d_end2Idx]); + for (unsigned int i = 0; i < 3; ++i) { + double dGrad; + dGrad = + preFactor * (end1Coords[i] - end2Coords[i]) / std::max(dist, 1.0e-8); + grad[3 * d_end1Idx + i] += dGrad; + grad[3 * d_end2Idx + i] -= dGrad; + } +} +} +} diff --git a/pool/shard007/C++/0094683_par.cpp b/pool/shard007/C++/0094683_par.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cfa1ce8241a94832d3a292d008c1e1c47e7aae77 --- /dev/null +++ b/pool/shard007/C++/0094683_par.cpp @@ -0,0 +1,150 @@ +/* + * Website: + * https://github.com/wo3kie/dojo + * + * Author: + * Lukasz Czerwinski + * + * Compilation: + * g++ --std=c++11 par.cpp -o par -pthread + * + * Usage: + * $ echo {1..10} > 1-10-file + * $ sed -i 's/ /\n/g' 1-10-file + * $ + * $ cat 1-10-file | ./par echo + * 140556950165248: 1 + * 140556941772544: 2 + * 140556950165248: 3 + * 140556941772544: 4 + * 140556950165248: 5 + * 140556941772544: 6 + * 140556950165248: 7 + * 140556941772544: 8 + * 140556941772544: 10 + * 140556950165248: 9 + * + * GNU parallel: + * http://www.gnu.org/software/parallel/ + */ + +#include <chrono> +#include <iostream> +#include <mutex> +#include <queue> +#include <thread> + +template< typename T > +class Buffer +{ +public: + + void push( T const & t ) + { + std::unique_lock< std::mutex > lock( m_mutex ); + m_queue.push( t ); + } + + bool get( T & result ) + { + std::unique_lock< std::mutex > lock( m_mutex ); + + if( m_queue.empty() ){ + return false; + } + + result = m_queue.front(); + m_queue.pop(); + + return true; + } + +private: + + std::mutex m_mutex; + std::queue< T > m_queue; +}; + +bool exec( + char const * const command, + std::function< void ( char const * ) > const onRead +) +{ + FILE * const pipe = popen( command, "r" ); + + if( ! pipe ){ + return false; + } + + char buffer[ 4 * 1024 ]; + + while( ! feof( pipe ) ) + { + if( fgets( buffer, sizeof( buffer ), pipe ) ){ + onRead( buffer ); + } + } + + pclose( pipe ); + + return true; +} + +void producer( Buffer< std::string > & buffer ) +{ + std::string line; + + while( std::getline( std::cin, line ) ){ + buffer.push( line ); + } +} + +void consumer( std::string const & command, Buffer< std::string > & buffer ) +{ + auto const print = []( std::string const & text ){ + std::cout << std::this_thread::get_id() << ": " << text; + }; + + std::string args; + + while( true ) + { + if( buffer.get( args ) == false ) + { + std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) ); + + if( buffer.get( args ) == false ){ + return; + } + } + + exec( (command + args).c_str(), print ); + } +} + +int main( int argc, char* argv[] ) +{ + std::string command; + + for( unsigned i = 1 ; i < argc ; ++ i ){ + command += std::string( argv[ i ] ) + " "; + } + + Buffer< std::string > buffer; + std::vector< std::thread > threads; + + threads.push_back( std::thread( & producer, std::ref( buffer ) ) ); + + unsigned const cores = std::thread::hardware_concurrency(); + + for( unsigned i = 0 ; i < 2 * cores ; ++ i ){ + threads.push_back( std::thread( & consumer, command, std::ref( buffer ) ) ); + } + + for( std::thread & t : threads ){ + t.join(); + } + + return 0; +} + diff --git a/pool/shard007/C++/0094684_sql_rename.cc b/pool/shard007/C++/0094684_sql_rename.cc new file mode 100644 index 0000000000000000000000000000000000000000..6a7b0b0b3adf988baaa7471140965e8053e63556 --- /dev/null +++ b/pool/shard007/C++/0094684_sql_rename.cc @@ -0,0 +1,365 @@ +/* Copyright (C) 2000-2006 MySQL AB, 2008-2009 Sun Microsystems, Inc + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* + Atomic rename of table; RENAME TABLE t1 to t2, tmp to t1 [,...] +*/ + +#include "sql_priv.h" +#include "unireg.h" +#include "sql_rename.h" +#include "sql_cache.h" // query_cache_* +#include "sql_table.h" // build_table_filename +#include "sql_view.h" // mysql_frm_type, mysql_rename_view +#include "sql_trigger.h" +#include "lock.h" // MYSQL_OPEN_SKIP_TEMPORARY +#include "sql_base.h" // tdc_remove_table, lock_table_names, +#include "sql_handler.h" // mysql_ha_rm_tables +#include "datadict.h" + +static TABLE_LIST *rename_tables(THD *thd, TABLE_LIST *table_list, + bool skip_error); + +static TABLE_LIST *reverse_table_list(TABLE_LIST *table_list); + +/* + Every second entry in the table_list is the original name and every + second entry is the new name. +*/ + +bool mysql_rename_tables(THD *thd, TABLE_LIST *table_list, bool silent) +{ + bool error= 1; + bool binlog_error= 0; + TABLE_LIST *ren_table= 0; + int to_table; + char *rename_log_table[2]= {NULL, NULL}; + DBUG_ENTER("mysql_rename_tables"); + + /* + Avoid problems with a rename on a table that we have locked or + if the user is trying to to do this in a transcation context + */ + + if (thd->locked_tables_mode || thd->in_active_multi_stmt_transaction()) + { + my_message(ER_LOCK_OR_ACTIVE_TRANSACTION, + ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0)); + DBUG_RETURN(1); + } + + mysql_ha_rm_tables(thd, table_list); + + if (logger.is_log_table_enabled(QUERY_LOG_GENERAL) || + logger.is_log_table_enabled(QUERY_LOG_SLOW)) + { + + /* + Rules for rename of a log table: + + IF 1. Log tables are enabled + AND 2. Rename operates on the log table and nothing is being + renamed to the log table. + DO 3. Throw an error message. + ELSE 4. Perform rename. + */ + + for (to_table= 0, ren_table= table_list; ren_table; + to_table= 1 - to_table, ren_table= ren_table->next_local) + { + int log_table_rename= 0; + + if ((log_table_rename= + check_if_log_table(ren_table->db_length, ren_table->db, + ren_table->table_name_length, + ren_table->table_name, 1))) + { + /* + as we use log_table_rename as an array index, we need it to start + with 0, while QUERY_LOG_SLOW == 1 and QUERY_LOG_GENERAL == 2. + So, we shift the value to start with 0; + */ + log_table_rename--; + if (rename_log_table[log_table_rename]) + { + if (to_table) + rename_log_table[log_table_rename]= NULL; + else + { + /* + Two renames of "log_table TO" w/o rename "TO log_table" in + between. + */ + my_error(ER_CANT_RENAME_LOG_TABLE, MYF(0), ren_table->table_name, + ren_table->table_name); + goto err; + } + } + else + { + if (to_table) + { + /* + Attempt to rename a table TO log_table w/o renaming + log_table TO some table. + */ + my_error(ER_CANT_RENAME_LOG_TABLE, MYF(0), ren_table->table_name, + ren_table->table_name); + goto err; + } + else + { + /* save the name of the log table to report an error */ + rename_log_table[log_table_rename]= ren_table->table_name; + } + } + } + } + if (rename_log_table[0] || rename_log_table[1]) + { + if (rename_log_table[0]) + my_error(ER_CANT_RENAME_LOG_TABLE, MYF(0), rename_log_table[0], + rename_log_table[0]); + else + my_error(ER_CANT_RENAME_LOG_TABLE, MYF(0), rename_log_table[1], + rename_log_table[1]); + goto err; + } + } + + if (lock_table_names(thd, table_list, 0, thd->variables.lock_wait_timeout, + MYSQL_OPEN_SKIP_TEMPORARY)) + goto err; + + for (ren_table= table_list; ren_table; ren_table= ren_table->next_local) + tdc_remove_table(thd, TDC_RT_REMOVE_ALL, ren_table->db, + ren_table->table_name, FALSE); + + error=0; + /* + An exclusive lock on table names is satisfactory to ensure + no other thread accesses this table. + */ + if ((ren_table=rename_tables(thd,table_list,0))) + { + /* Rename didn't succeed; rename back the tables in reverse order */ + TABLE_LIST *table; + + /* Reverse the table list */ + table_list= reverse_table_list(table_list); + + /* Find the last renamed table */ + for (table= table_list; + table->next_local != ren_table ; + table= table->next_local->next_local) ; + table= table->next_local->next_local; // Skip error table + /* Revert to old names */ + rename_tables(thd, table, 1); + + /* Revert the table list (for prepared statements) */ + table_list= reverse_table_list(table_list); + + error= 1; + } + + if (!silent && !error) + { + binlog_error= write_bin_log(thd, TRUE, thd->query(), thd->query_length()); + if (!binlog_error) + my_ok(thd); + } + + if (!error) + query_cache_invalidate3(thd, table_list, 0); + +err: + DBUG_RETURN(error || binlog_error); +} + + +/* + reverse table list + + SYNOPSIS + reverse_table_list() + table_list pointer to table _list + + RETURN + pointer to new (reversed) list +*/ +static TABLE_LIST *reverse_table_list(TABLE_LIST *table_list) +{ + TABLE_LIST *prev= 0; + + while (table_list) + { + TABLE_LIST *next= table_list->next_local; + table_list->next_local= prev; + prev= table_list; + table_list= next; + } + return (prev); +} + + +/* + Rename a single table or a view + + SYNPOSIS + do_rename() + thd Thread handle + ren_table A table/view to be renamed + new_db The database to which the table to be moved to + new_table_name The new table/view name + new_table_alias The new table/view alias + skip_error Whether to skip error + + DESCRIPTION + Rename a single table or a view. + + RETURN + false Ok + true rename failed +*/ + +bool +do_rename(THD *thd, TABLE_LIST *ren_table, char *new_db, char *new_table_name, + char *new_table_alias, bool skip_error) +{ + int rc= 1; + char name[FN_REFLEN + 1]; + const char *new_alias, *old_alias; + frm_type_enum frm_type; + enum legacy_db_type table_type; + + DBUG_ENTER("do_rename"); + + if (lower_case_table_names == 2) + { + old_alias= ren_table->alias; + new_alias= new_table_alias; + } + else + { + old_alias= ren_table->table_name; + new_alias= new_table_name; + } + DBUG_ASSERT(new_alias); + + build_table_filename(name, sizeof(name) - 1, + new_db, new_alias, reg_ext, 0); + if (!access(name,F_OK)) + { + my_error(ER_TABLE_EXISTS_ERROR, MYF(0), new_alias); + DBUG_RETURN(1); // This can't be skipped + } + build_table_filename(name, sizeof(name) - 1, + ren_table->db, old_alias, reg_ext, 0); + + frm_type= dd_frm_type(thd, name, &table_type); + switch (frm_type) + { + case FRMTYPE_TABLE: + { + if (!(rc= mysql_rename_table(ha_resolve_by_legacy_type(thd, + table_type), + ren_table->db, old_alias, + new_db, new_alias, 0))) + { + if ((rc= Table_triggers_list::change_table_name(thd, ren_table->db, + old_alias, + ren_table->table_name, + new_db, + new_alias))) + { + /* + We've succeeded in renaming table's .frm and in updating + corresponding handler data, but have failed to update table's + triggers appropriately. So let us revert operations on .frm + and handler's data and report about failure to rename table. + */ + (void) mysql_rename_table(ha_resolve_by_legacy_type(thd, + table_type), + new_db, new_alias, + ren_table->db, old_alias, 0); + } + } + } + break; + case FRMTYPE_VIEW: + /* + change of schema is not allowed + except of ALTER ...UPGRADE DATA DIRECTORY NAME command + because a view has valid internal db&table names in this case. + */ + if (thd->lex->sql_command != SQLCOM_ALTER_DB_UPGRADE && + strcmp(ren_table->db, new_db)) + my_error(ER_FORBID_SCHEMA_CHANGE, MYF(0), ren_table->db, + new_db); + else + rc= mysql_rename_view(thd, new_db, new_alias, ren_table); + break; + default: + DBUG_ASSERT(0); // should never happen + case FRMTYPE_ERROR: + my_error(ER_FILE_NOT_FOUND, MYF(0), name, my_errno); + break; + } + if (rc && !skip_error) + DBUG_RETURN(1); + + DBUG_RETURN(0); + +} +/* + Rename all tables in list; Return pointer to wrong entry if something goes + wrong. Note that the table_list may be empty! +*/ + +/* + Rename tables/views in the list + + SYNPOSIS + rename_tables() + thd Thread handle + table_list List of tables to rename + skip_error Whether to skip errors + + DESCRIPTION + Take a table/view name from and odd list element and rename it to a + the name taken from list element+1. Note that the table_list may be + empty. + + RETURN + false Ok + true rename failed +*/ + +static TABLE_LIST * +rename_tables(THD *thd, TABLE_LIST *table_list, bool skip_error) +{ + TABLE_LIST *ren_table, *new_table; + + DBUG_ENTER("rename_tables"); + + for (ren_table= table_list; ren_table; ren_table= new_table->next_local) + { + new_table= ren_table->next_local; + if (do_rename(thd, ren_table, new_table->db, new_table->table_name, + new_table->alias, skip_error)) + DBUG_RETURN(ren_table); + } + DBUG_RETURN(0); +} diff --git a/pool/shard007/C++/0094686_c_point_camera.cpp b/pool/shard007/C++/0094686_c_point_camera.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6bf5eda4732d4e262ce0220cb7707eccf5ac7f6f --- /dev/null +++ b/pool/shard007/C++/0094686_c_point_camera.cpp @@ -0,0 +1,86 @@ +//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// +// +// Purpose: +// +// $NoKeywords: $ +//=============================================================================// +#include "cbase.h" +#include "C_Point_Camera.h" + +// memdbgon must be the last include file in a .cpp file!!! +#include "tier0/memdbgon.h" + +IMPLEMENT_CLIENTCLASS_DT( C_PointCamera, DT_PointCamera, CPointCamera ) + RecvPropFloat( RECVINFO( m_FOV ) ), + RecvPropFloat( RECVINFO( m_Resolution ) ), + RecvPropInt( RECVINFO( m_bFogEnable ) ), + RecvPropInt( RECVINFO( m_FogColor ) ), + RecvPropFloat( RECVINFO( m_flFogStart ) ), + RecvPropFloat( RECVINFO( m_flFogEnd ) ), + RecvPropInt( RECVINFO( m_bActive ) ), + RecvPropInt( RECVINFO( m_bUseScreenAspectRatio ) ), +END_RECV_TABLE() + +C_EntityClassList<C_PointCamera> g_PointCameraList; +C_PointCamera *C_EntityClassList<C_PointCamera>::m_pClassList = NULL; + +C_PointCamera* GetPointCameraList() +{ + return g_PointCameraList.m_pClassList; +} + +C_PointCamera::C_PointCamera() +{ + m_bActive = false; + m_bFogEnable = false; + + g_PointCameraList.Insert( this ); +} + +C_PointCamera::~C_PointCamera() +{ + g_PointCameraList.Remove( this ); +} + +bool C_PointCamera::ShouldDraw() +{ + return false; +} + +float C_PointCamera::GetFOV() +{ + return m_FOV; +} + +float C_PointCamera::GetResolution() +{ + return m_Resolution; +} + +bool C_PointCamera::IsFogEnabled() +{ + return m_bFogEnable; +} + +void C_PointCamera::GetFogColor( unsigned char &r, unsigned char &g, unsigned char &b ) +{ + r = m_FogColor.r; + g = m_FogColor.g; + b = m_FogColor.b; +} + +float C_PointCamera::GetFogStart() +{ + return m_flFogStart; +} + +float C_PointCamera::GetFogEnd() +{ + return m_flFogEnd; +} + +bool C_PointCamera::IsActive() +{ + return m_bActive; +} + diff --git a/pool/shard007/C++/0094690_gdbserverprovidermanager.cpp b/pool/shard007/C++/0094690_gdbserverprovidermanager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..84207afdae07cfe70db901e93a2afda355e041a2 --- /dev/null +++ b/pool/shard007/C++/0094690_gdbserverprovidermanager.cpp @@ -0,0 +1,215 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Denis Shienkov <denis.shienkov@gmail.com> +** Contact: http://www.qt-project.org/legal +** +** This file is part of Qt Creator. +** +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://www.qt.io/licensing. For further information +** use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 or version 3 as published by the Free +** Software Foundation and appearing in the file LICENSE.LGPLv21 and +** LICENSE.LGPLv3 included in the packaging of this file. Please review the +** following information to ensure the GNU Lesser General Public License +** requirements will be met: https://www.gnu.org/licenses/lgpl.html and +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +****************************************************************************/ + +#include "gdbserverprovidermanager.h" +#include "gdbserverprovider.h" + +#include "openocdgdbserverprovider.h" +#include "defaultgdbserverprovider.h" +#include "stlinkutilgdbserverprovider.h" + +#include <coreplugin/icore.h> + +#include <extensionsystem/pluginmanager.h> + +#include <utils/persistentsettings.h> +#include <utils/qtcassert.h> +#include <utils/algorithm.h> + +#include <QDir> + +namespace BareMetal { +namespace Internal { + +const char dataKeyC[] = "GdbServerProvider."; +const char countKeyC[] = "GdbServerProvider.Count"; +const char fileVersionKeyC[] = "Version"; +const char fileNameKeyC[] = "/qtcreator/gdbserverproviders.xml"; + +static Utils::FileName settingsFileName(const QString &path) +{ + const QFileInfo settingsLocation(Core::ICore::settings()->fileName()); + return Utils::FileName::fromString(settingsLocation.absolutePath() + path); +} + +static GdbServerProviderManager *m_instance = 0; + +GdbServerProviderManager::GdbServerProviderManager(QObject *parent) + : QObject(parent) + , m_configFile(settingsFileName(QLatin1String(fileNameKeyC))) + , m_factories({ new DefaultGdbServerProviderFactory, + new OpenOcdGdbServerProviderFactory, + new StLinkUtilGdbServerProviderFactory }) +{ + m_writer = new Utils::PersistentSettingsWriter( + m_configFile, QLatin1String("QtCreatorGdbServerProviders")); + + connect(Core::ICore::instance(), &Core::ICore::saveSettingsRequested, + this, &GdbServerProviderManager::saveProviders); + + connect(this, &GdbServerProviderManager::providerAdded, + this, &GdbServerProviderManager::providersChanged); + connect(this, &GdbServerProviderManager::providerRemoved, + this, &GdbServerProviderManager::providersChanged); + connect(this, &GdbServerProviderManager::providerUpdated, + this, &GdbServerProviderManager::providersChanged); +} + +GdbServerProviderManager::~GdbServerProviderManager() +{ + qDeleteAll(m_providers); + m_providers.clear(); + delete m_writer; + m_instance = 0; +} + +GdbServerProviderManager *GdbServerProviderManager::instance() +{ + if (!m_instance) + m_instance = new GdbServerProviderManager; + return m_instance; +} + +void GdbServerProviderManager::restoreProviders() +{ + Utils::PersistentSettingsReader reader; + if (!reader.load(m_configFile)) + return; + + const QVariantMap data = reader.restoreValues(); + const int version = data.value(QLatin1String(fileVersionKeyC), 0).toInt(); + if (version < 1) + return; + + const int count = data.value(QLatin1String(countKeyC), 0).toInt(); + for (int i = 0; i < count; ++i) { + const QString key = QString::fromLatin1(dataKeyC) + QString::number(i); + if (!data.contains(key)) + break; + + const QVariantMap map = data.value(key).toMap(); + bool restored = false; + foreach (GdbServerProviderFactory *f, m_factories) { + if (f->canRestore(map)) { + if (GdbServerProvider *p = f->restore(map)) { + registerProvider(p); + restored = true; + break; + } + } + } + if (!restored) + qWarning("Warning: Unable to restore provider '%s' stored in %s.", + qPrintable(GdbServerProviderFactory::idFromMap(map)), + qPrintable(m_configFile.toUserOutput())); + } + + emit providersLoaded(); +} + +void GdbServerProviderManager::saveProviders() +{ + QVariantMap data; + data.insert(QLatin1String(fileVersionKeyC), 1); + + int count = 0; + foreach (const GdbServerProvider *p, m_providers) { + if (p->isValid()) { + const QVariantMap tmp = p->toMap(); + if (tmp.isEmpty()) + continue; + const QString key = QString::fromLatin1(dataKeyC) + QString::number(count); + data.insert(key, tmp); + ++count; + } + } + data.insert(QLatin1String(countKeyC), count); + m_writer->save(data, Core::ICore::mainWindow()); +} + +QList<GdbServerProvider *> GdbServerProviderManager::providers() const +{ + return m_providers; +} + +QList<GdbServerProviderFactory *> GdbServerProviderManager::factories() const +{ + return m_factories; +} + +GdbServerProvider *GdbServerProviderManager::findProvider(const QString &id) const +{ + if (id.isEmpty()) + return 0; + + return Utils::findOrDefault(m_providers, Utils::equal(&GdbServerProvider::id, id)); +} + +GdbServerProvider *GdbServerProviderManager::findByDisplayName(const QString &displayName) const +{ + if (displayName.isEmpty()) + return 0; + + return Utils::findOrDefault(m_providers, Utils::equal(&GdbServerProvider::displayName, displayName)); +} + +void GdbServerProviderManager::notifyAboutUpdate(GdbServerProvider *provider) +{ + if (!provider || !m_providers.contains(provider)) + return; + emit providerUpdated(provider); +} + +bool GdbServerProviderManager::registerProvider(GdbServerProvider *provider) +{ + if (!provider || m_providers.contains(provider)) + return true; + foreach (const GdbServerProvider *current, m_providers) { + if (*provider == *current) + return false; + QTC_ASSERT(current->id() != provider->id(), return false); + } + + m_providers.append(provider); + emit providerAdded(provider); + return true; +} + +void GdbServerProviderManager::deregisterProvider(GdbServerProvider *provider) +{ + if (!provider || !m_providers.contains(provider)) + return; + m_providers.removeOne(provider); + emit providerRemoved(provider); + delete provider; +} + +} // namespace Internal +} // namespace BareMetal diff --git a/pool/shard007/C++/0094691_CWE401_Memory_Leak__int64_t_realloc_43.cpp b/pool/shard007/C++/0094691_CWE401_Memory_Leak__int64_t_realloc_43.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2b556a7eb5cacb86b9931f175f9a222dddef7c94 --- /dev/null +++ b/pool/shard007/C++/0094691_CWE401_Memory_Leak__int64_t_realloc_43.cpp @@ -0,0 +1,125 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE401_Memory_Leak__int64_t_realloc_43.cpp +Label Definition File: CWE401_Memory_Leak.c.label.xml +Template File: sources-sinks-43.tmpl.cpp +*/ +/* + * @description + * CWE: 401 Memory Leak + * BadSource: realloc Allocate data using realloc() + * GoodSource: Allocate data on the stack + * Sinks: + * GoodSink: call free() on data + * BadSink : no deallocation of data + * Flow Variant: 43 Data flow: data flows using a C++ reference from one function to another in the same source file + * + * */ + +#include "std_testcase.h" + +#include <wchar.h> + +namespace CWE401_Memory_Leak__int64_t_realloc_43 +{ + +#ifndef OMITBAD + +static void badSource(int64_t * &data) +{ + /* POTENTIAL FLAW: Allocate memory on the heap */ + data = (int64_t *)realloc(data, 100*sizeof(int64_t)); + if (data == NULL) {exit(-1);} + /* Initialize and make use of data */ + data[0] = 5LL; + printLongLongLine(data[0]); +} + +void bad() +{ + int64_t * data; + data = NULL; + badSource(data); + /* POTENTIAL FLAW: No deallocation */ + ; /* empty statement needed for some flow variants */ +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() uses the GoodSource with the BadSink */ +static void goodG2BSource(int64_t * &data) +{ + /* FIX: Use memory allocated on the stack with ALLOCA */ + data = (int64_t *)ALLOCA(100*sizeof(int64_t)); + /* Initialize and make use of data */ + data[0] = 5LL; + printLongLongLine(data[0]); +} + +static void goodG2B() +{ + int64_t * data; + data = NULL; + goodG2BSource(data); + /* POTENTIAL FLAW: No deallocation */ + ; /* empty statement needed for some flow variants */ +} + +/* goodB2G() uses the BadSource with the GoodSink */ +static void goodB2GSource(int64_t * &data) +{ + /* POTENTIAL FLAW: Allocate memory on the heap */ + data = (int64_t *)realloc(data, 100*sizeof(int64_t)); + if (data == NULL) {exit(-1);} + /* Initialize and make use of data */ + data[0] = 5LL; + printLongLongLine(data[0]); +} + +static void goodB2G() +{ + int64_t * data; + data = NULL; + goodB2GSource(data); + /* FIX: Deallocate memory */ + free(data); +} + +void good() +{ + goodG2B(); + goodB2G(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +using namespace CWE401_Memory_Leak__int64_t_realloc_43; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard007/C++/0094693_adapterStat.cpp b/pool/shard007/C++/0094693_adapterStat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d8177ef1ee30c6625124434b22d5e5d5195b02ad --- /dev/null +++ b/pool/shard007/C++/0094693_adapterStat.cpp @@ -0,0 +1,263 @@ +// ========================================================================== +// adapterStat +// ========================================================================== +// Copyright (c) 2006-2013, Knut Reinert, FU Berlin +// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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. +// +// ========================================================================== +// Author: Benjamin Strauch +// ========================================================================== + +#include <seqan/basic.h> +#include <seqan/sequence.h> +#include <seqan/seq_io.h> +#include <seqan/arg_parse.h> + +#include <unordered_map> + +#include <unordered_map> // enable C++11 mode for this structure. + +// ========================================================================== +// Classes +// ========================================================================== + +// -------------------------------------------------------------------------- +// Class AppOptions +// -------------------------------------------------------------------------- + +// This struct stores the options from the command line. +// +// You might want to rename this to reflect the name of your app. + +struct AppOptions +{ + // Verbosity level. 0 -- quiet, 1 -- normal, 2 -- verbose, 3 -- very verbose. + int verbosity; + + // The first (and only) argument of the program is stored here. + seqan::CharString file1, file2; + + AppOptions() : + verbosity(1) + {} +}; + +// ========================================================================== +// Functions +// ========================================================================== + +// -------------------------------------------------------------------------- +// Function parseCommandLine() +// -------------------------------------------------------------------------- + +seqan::ArgumentParser::ParseResult +parseCommandLine(AppOptions & options, int argc, char const ** argv) +{ + // Setup ArgumentParser. + seqan::ArgumentParser parser("adapterStat"); + // Set short description, version, and date. + setShortDescription(parser, "Adapter trimming statistics"); + setVersion(parser, "0.1"); + setDate(parser, "July 2012"); + + // Define usage line and long description. + addUsageLine(parser, "[\\fIOPTIONS\\fP] \\fIREFERENCE\\fP \\fITRIMMED\\fP"); + addDescription(parser, "This program analyses fastq files generated by SimSeq and generates " + "statistics about the accuracy of the adapter trimming."); + + // We require one argument. + addArgument(parser, seqan::ArgParseArgument(seqan::ArgParseArgument::INPUTFILE, "FILE", true)); + + addOption(parser, seqan::ArgParseOption("q", "quiet", "Set verbosity to a minimum.")); + addOption(parser, seqan::ArgParseOption("v", "verbose", "Enable verbose output.")); + addOption(parser, seqan::ArgParseOption("vv", "very-verbose", "Enable very verbose output.")); + + // Add Examples Section. + addTextSection(parser, "Examples"); + addListItem(parser, "\\fBadapterStat\\fP \\fB-v\\fP \\fItext\\fP", + "Call with \\fITEXT\\fP set to \"text\" with verbose output."); + + // Parse command line. + seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); + + // Only extract options if the program will continue after parseCommandLine() + if (res != seqan::ArgumentParser::PARSE_OK) + return res; + + // Extract option values. + if (isSet(parser, "quiet")) + options.verbosity = 0; + if (isSet(parser, "verbose")) + options.verbosity = 2; + if (isSet(parser, "very-verbose")) + options.verbosity = 3; + seqan::getArgumentValue(options.file1, parser, 0, 0); + seqan::getArgumentValue(options.file2, parser, 0, 1); + + return seqan::ArgumentParser::PARSE_OK; +} + +// -------------------------------------------------------------------------- +// Function insertSize(char* s) +// -------------------------------------------------------------------------- + +// Returns (num2 - num1 + 1) in a string "xxxx_num1_num2_xxx...". +int insertSize(char* s) +{ + int insert = 0; + strtok(s, "_"); + insert -= atoi(strtok(NULL, "_")); + insert += atoi(strtok(NULL, "_")) + 1; + return insert; +} + +// Since CharStrings can't be hashed so easily, we +// hash their CString representation and store the hash. +unsigned long hash2(const char *str) +{ + unsigned long n = 5381UL; + int i; + for (i = 0; str[i] != '\0'; i++) + { + n = n * 33UL + str[i]; + } + return n; +} + +template <typename key, typename map> +bool exists(key k, map m) +{ + return m.find(k) != m.end(); +} + +// -------------------------------------------------------------------------- +// Function main() +// -------------------------------------------------------------------------- + +// Program entry point. + +int main(int argc, char const ** argv) +{ + // Parse the command line. + seqan::ArgumentParser parser; + AppOptions options; + seqan::ArgumentParser::ParseResult res = parseCommandLine(options, argc, argv); + + // If there was an error parsing or built-in argument parser functionality + // was triggered then we exit the program. The return code is 1 if there + // were errors and 0 if there were none. + if (res != seqan::ArgumentParser::PARSE_OK) + return res == seqan::ArgumentParser::PARSE_ERROR; + + // Print the command line arguments back to the user. + if (options.verbosity > 0) + { + std::cout << "__OPTIONS____________________________________________________________________\n" + << '\n' + << "VERBOSITY\t" << options.verbosity << '\n' + << "REF \t" << options.file1 << '\n' + << "TRIM \t" << options.file2 << "\n\n"; + } + + seqan::SequenceStream refStream(seqan::toCString(options.file1)); + seqan::SequenceStream trimStream(seqan::toCString(options.file2)); + + if (!isGood(refStream) || !isGood(trimStream)) + { + std::cerr << "Could not open file.\n"; + return 1; + } + seqan::CharString idRef, idTrim; + seqan::String<seqan::Dna5Q> seqRef, seqTrim; + + std::unordered_map<unsigned long, unsigned> lengthMap; + + unsigned c =0; + while (!atEnd(trimStream)) + { + if ( readRecord(idTrim, seqTrim, trimStream) == 0) + { + unsigned long h = hash2(seqan::toCString(idTrim)); + lengthMap[h] = length(seqTrim); + c++; + } + else + { + std::cerr << "Error while reading reference file.\n"; + } + } + + std::cout << "Inserted " << c << " " << lengthMap.size() << " elements.\n"; + + int count = 0; + int false_pos = 0, true_pos = 0, false_neg = 0, true_neg = 0; + + while (!atEnd(refStream)) + { + if ( readRecord(idRef, seqRef, refStream) == 0) + { + ++count; + unsigned long h = hash2(seqan::toCString(idRef)); + unsigned insert = insertSize(seqan::toCString(idRef)); + + unsigned len_trim = 0; + if (lengthMap.count(h) != 0) + len_trim = lengthMap[h]; + + // We know how much adapter sequence we have read. + int overlap = length(seqRef) > insert ? length(seqRef) - insert : 0; + int trimmed = length(seqRef) - len_trim; + + if (trimmed > overlap) // Trimmed more than necessary. + ++false_pos; + else if (trimmed == overlap && overlap > 0) // Trimmed the adapter exactly. + ++true_pos; + else if (trimmed < overlap) // Trimmed less than necessary (or nothing at all). + ++false_neg; + else if(trimmed == 0 && overlap == 0) // Correctly trimmed nothing. + ++true_neg; + } + else + { + std::cerr << "Error reading file reference file." << std::endl; + return 1; + } + } + + double sensitivity = (double) true_pos / ((double) true_pos + (double) false_neg); + double specifivity = (double) true_neg / ((double) true_neg + (double) false_pos); + + double exact = (double) (true_pos + true_neg) / (double) count; + double wrong = (double) (false_pos + false_neg) / (double) count; + + std::cout << "Adapter trimming statistics\n"; + std::cout << "===========================\n" << std::setprecision(3); + std::cout << "Sens: " << std::setw(5) << sensitivity << " | Spec: " << std::setw(5) << specifivity << std::endl; + std::cout << "Exact: " << std::setw(5) << exact << " | Wrong: " << std::setw(5) << wrong << "\n" << std::endl; + + return 0; +} diff --git a/pool/shard007/C++/0094694_EffectorNode.cpp b/pool/shard007/C++/0094694_EffectorNode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e7838c32f630c1b9fc7a2918d3fb8f7d57a53e92 --- /dev/null +++ b/pool/shard007/C++/0094694_EffectorNode.cpp @@ -0,0 +1,59 @@ +// +// EffectorNode.cpp +// Cinder-Pipeline +// +// Created by Jean-Pierre Mouilleseaux on 19 May 2014. +// Copyright 2014-2015 Chorded Constructions. All rights reserved. +// + +#include "EffectorNode.h" + +namespace Cinder { namespace Pipeline { + +using namespace ci; + +const std::string EffectorNode::sVertexShaderPassThrough = R"( + #version 150 + uniform mat4 ciModelViewProjection; + + in vec4 ciPosition; + in vec2 ciTexCoord0; + + out vec2 vTexCoord0; + + void main() { + vTexCoord0 = ciTexCoord0; + gl_Position = ciModelViewProjection * ciPosition; + } +)"; + +const std::string EffectorNode::sFragmentShaderPassThrough = R"( + #version 150 + uniform sampler2D image; + + in vec2 vTexCoord0; + + out vec4 oFragColor; + + void main() { + oFragColor = texture(image, vTexCoord0); + } +)"; + +void EffectorNode::setupShader(const DataSourceRef& vertexShader, const DataSourceRef& fragmentShader) { + std::string vert = vertexShader ? loadString(vertexShader) : sVertexShaderPassThrough; + std::string frag = loadString(fragmentShader); + setupShader(vert, frag); +} + +void EffectorNode::setupShader(const std::string& vertexShader, const std::string& fragmentShader) { + std::string vert = !vertexShader.empty() ? vertexShader : sVertexShaderPassThrough; + auto format = gl::GlslProg::Format().vertex(vert).fragment(fragmentShader); + try { + mShader = gl::GlslProg::create(format); + } catch (gl::GlslProgExc e) { + throw e; + } +} + +}} diff --git a/pool/shard007/C++/0094696_Cookie.cpp b/pool/shard007/C++/0094696_Cookie.cpp new file mode 100644 index 0000000000000000000000000000000000000000..716e675759a68adbeb2ae4abee10a23a245c57d3 --- /dev/null +++ b/pool/shard007/C++/0094696_Cookie.cpp @@ -0,0 +1,107 @@ +/* + * Cookie.cpp + * + * Copyright (C) 2009-12 by RStudio, Inc. + * + * Unless you have received this program directly from RStudio pursuant + * to the terms of a commercial license agreement with RStudio, then + * this program is licensed to you under the terms of version 3 of the + * GNU Affero General Public License. This program is distributed WITHOUT + * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, + * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the + * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. + * + */ + +#include <core/http/Cookie.hpp> + +#include <core/http/URL.hpp> +#include <core/Error.hpp> +#include <core/Log.hpp> + +using namespace boost::gregorian ; + +namespace rstudio { +namespace core { +namespace http { + +Cookie::Cookie(const Request& request, + const std::string& name, + const std::string& value, + const std::string& path, + bool httpOnly) + : name_(name), + value_(value), + path_(path), + expires_(not_a_date_time), + httpOnly_(httpOnly) +{ + if (path.empty() && URL::complete(request.uri(), "") != "/") + { + // If we're here, it means we're using an implicit path that + // isn't the root. In other words, we're setting a cookie + // that will only apply under the current "path". Since this + // is not something we're likely to want, we warn--if this + // is actually the desired behavior then use an explicit path + // value. + LOG_WARNING_MESSAGE("Implicit path used with non-root URL (" + + request.uri() + ")"); + } +} + +Cookie::~Cookie() +{ +} + +void Cookie::setExpires(const days& expiresDays) +{ + expires_ = date(day_clock::universal_day() + expiresDays) ; +} + +void Cookie::setExpiresDelete() +{ + expires_ = date(day_clock::universal_day() - days(2)) ; +} + +void Cookie::setHttpOnly() +{ + httpOnly_ = true; +} + +std::string Cookie::cookieHeaderValue() const +{ + // basic name/value + std::ostringstream headerValue ; + headerValue << name() << "=" << value() ; + + // expiries if specified + if ( !expires().is_not_a_date() ) + { + date::ymd_type ymd = expires_.year_month_day() ; + greg_weekday wd = expires_.day_of_week() ; + + headerValue << "; expires=" ; + headerValue << wd.as_short_string() << ", " + << ymd.day << "-" << ymd.month.as_short_string() << "-" + << ymd.year << " 23:59:59 GMT" ; + } + + // path if specified + if ( !path().empty() ) + headerValue << "; path=" << path(); + + // domain if specified + if ( !domain().empty() ) + headerValue << "; domain=" << domain() ; + + // http only if specified + if (httpOnly_) + headerValue << "; HttpOnly"; + + // return the header value + return headerValue.str() ; +} + +} // namespace http +} // namespace core +} // namespace rstudio diff --git a/pool/shard007/C++/0094697_numeric_value_chooser_delegate.cpp b/pool/shard007/C++/0094697_numeric_value_chooser_delegate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..975239ea74dfa109956bbc02f73f10ca3952bbb7 --- /dev/null +++ b/pool/shard007/C++/0094697_numeric_value_chooser_delegate.cpp @@ -0,0 +1,106 @@ +/* numeric_value_chooser_delegate.cpp + * Delegate to select a numeric value for a treeview entry + * + * Wireshark - Network traffic analyzer + * By Gerald Combs <gerald@wireshark.org> + * Copyright 1998 Gerald Combs + * + * SPDX-License-Identifier: GPL-2.0-or-later + */ + +#include "config.h" + +#include <ui/qt/models/numeric_value_chooser_delegate.h> + +#include <QStyledItemDelegate> +#include <QSpinBox> + +NumericValueChooserDelegate::NumericValueChooserDelegate(int min, int max, QObject *parent) + : QStyledItemDelegate(parent) +{ + _min = min; + _max = max; + _default = min; +} + +NumericValueChooserDelegate::~NumericValueChooserDelegate() +{ +} + +void NumericValueChooserDelegate::setMinMaxRange(int min, int max) +{ + _min = qMin(min, max); + _max = qMax(min, max); + /* ensure, that the default value is within the new min<->max */ + _default = qMin(_max, qMax(_min, _default)); + _defReturn = QVariant::fromValue(_default); +} + +void NumericValueChooserDelegate::setDefaultValue(int defValue, QVariant defaultReturn) +{ + /* ensure, that the new default value is within min<->max */ + _default = qMin(_max, qMax(_min, defValue)); + _defReturn = defaultReturn; +} + +QWidget* NumericValueChooserDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const +{ + if (!index.isValid()) { + return QStyledItemDelegate::createEditor(parent, option, index); + } + + QSpinBox * editor = new QSpinBox(parent); + editor->setMinimum(_min); + editor->setMaximum(_max); + editor->setWrapping(true); + + connect(editor, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, + &NumericValueChooserDelegate::onValueChanged); + + return editor; +} + +void NumericValueChooserDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const +{ + if (index.isValid()) + { + bool canConvert = false; + int val = index.data().toInt(&canConvert); + if (! canConvert) + val = _default; + + QSpinBox * spinBox = qobject_cast<QSpinBox *>(editor); + spinBox->setValue(val); + } + else + QStyledItemDelegate::setEditorData(editor, index); +} + +void NumericValueChooserDelegate::setModelData(QWidget *editor, QAbstractItemModel * model, const QModelIndex &index) const +{ + if (index.isValid()) { + QSpinBox * spinBox = qobject_cast<QSpinBox *>(editor); + model->setData(index, _default == spinBox->value() ? _defReturn : QVariant::fromValue(spinBox->value())); + } else { + QStyledItemDelegate::setModelData(editor, model, index); + } +} + +void NumericValueChooserDelegate::onValueChanged(int) +{ + QSpinBox * spinBox = qobject_cast<QSpinBox *>(sender()); + emit commitData(spinBox); +} + +/* + * Editor modelines + * + * Local Variables: + * c-basic-offset: 4 + * tab-width: 8 + * indent-tabs-mode: nil + * End: + * + * ex: set shiftwidth=4 tabstop=8 expandtab: + * :indentSize=4:tabSize=8:noTabs=true: + */ diff --git a/pool/shard007/C++/0094700_LDLTriangleLine.cpp b/pool/shard007/C++/0094700_LDLTriangleLine.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8266700303fb6ea75ef4f448f1dd42ea06ef39f1 --- /dev/null +++ b/pool/shard007/C++/0094700_LDLTriangleLine.cpp @@ -0,0 +1,218 @@ +#include "LDLTriangleLine.h" +#include "LDLLineLine.h" +#include "LDLMainModel.h" +#include <TCFoundation/TCLocalStrings.h> +#include <sstream> + +#ifdef WIN32 +#if defined(_MSC_VER) && _MSC_VER >= 1400 && defined(_DEBUG) +#define new DEBUG_CLIENTBLOCK +#endif // _DEBUG +#endif // WIN32 + +LDLTriangleLine::LDLTriangleLine(LDLModel *parentModel, const char *line, + int lineNumber, const char *originalLine) + :LDLShapeLine(parentModel, line, lineNumber, originalLine), + m_colinearIndex(-1), + m_matchingIndex(-1) +{ +} + +LDLTriangleLine::LDLTriangleLine(const LDLTriangleLine &other) + :LDLShapeLine(other), + m_colinearIndex(other.m_colinearIndex), + m_matchingIndex(other.m_matchingIndex) +{ +} + +bool LDLTriangleLine::parse(void) +{ + float x1, y1, z1; + float x2, y2, z2; + float x3, y3, z3; + int lineType; + + if (sscanf(m_line, "%d %i %f %f %f %f %f %f %f %f %f", &lineType, + &m_colorNumber, &x1, &y1, &z1, &x2, &y2, &z2, &x3, &y3, &z3) == 11) + { + std::string prefix = getTypeAndColorPrefix(); + std::stringstream ss; + if (!prefix.empty()) + { + ss << prefix << " "; + } + else + { + ss << "3 " << m_colorNumber << " "; + } + ss << x1 << " " << y1 << " " << z1 << " "; + ss << x2 << " " << y2 << " " << z2 << " "; + ss << x3 << " " << y3 << " " << z3 << " "; + m_formattedLine = copyString(ss.str().c_str()); + m_points = new TCVector[3]; + m_points[0] = TCVector(x1, y1, z1); + m_points[1] = TCVector(x2, y2, z2); + m_points[2] = TCVector(x3, y3, z3); + if (!getMainModel()->getSkipValidation()) + { + // Note that we don't care what the second matching index is, + // because we only need to throw out one of the two points, so don't + // bother to even read it. + if (getMatchingPoints(&m_matchingIndex)) + { + m_valid = false; + } + else + { + checkForColinearPoints(); + } + } + return true; + } + else + { + m_valid = false; + setError(LDLEParse, TCLocalStrings::get(_UC("LDLTriLineParse"))); + return false; + } +} + +TCObject *LDLTriangleLine::copy(void) const +{ + return new LDLTriangleLine(*this); +} + +void LDLTriangleLine::checkForColinearPoints(void) +{ + m_colinearIndex = getColinearIndex(); + if (m_colinearIndex >= 0) + { + m_valid = false; + } +} + +int LDLTriangleLine::getColinearIndex(void) +{ + TCVector &p1 = m_points[0]; + TCVector &p2 = m_points[1]; + TCVector &p3 = m_points[2]; + TCVector normal = (p1 - p3) * (p1 - p2); + + if (normal.lengthSquared() == 0.0f) + { + return middleIndex(p1, p2, p3); + } + return -1; +} + +LDLFileLineArray *LDLTriangleLine::getReplacementLines(void) +{ + if (m_valid) + { + return NULL; + } + else + { + if (m_matchingIndex >= 0) + { + return removeMatchingPoint(); + } + if (m_colinearIndex >= 0) + { + return removeColinearPoint(); + } + else + { + return NULL; + } + } +} + +LDLFileLineArray *LDLTriangleLine::removePoint(int index) +{ + LDLFileLineArray *fileLineArray = NULL; + LDLLineLine *lineLine = NULL; +/* + TCVector &p1 = m_points[0]; + TCVector &p2 = m_points[1]; + TCVector &p3 = m_points[2]; +*/ + + switch (index) + { + case 0: + lineLine = newLineLine(1, 2); + break; + case 1: + lineLine = newLineLine(0, 2); + break; + case 2: + lineLine = newLineLine(0, 1); + break; + default: + break; + } + if (lineLine) + { + fileLineArray = new LDLFileLineArray(1); + fileLineArray->addObject(lineLine); + lineLine->release(); + } + return fileLineArray; +} + +LDLFileLineArray *LDLTriangleLine::removeMatchingPoint(void) +{ + LDLFileLineArray *fileLineArray = removePoint(m_matchingIndex); + + if (fileLineArray) + { + UCSTRING pointStr; + + pointStr = printPoint(m_matchingIndex); + setWarning(LDLEMatchingPoints, + TCLocalStrings::get(_UC("LDLTriLineIdentical")), + m_matchingIndex + 1, pointStr.c_str()); + } + else + { + setError(LDLEGeneral, + TCLocalStrings::get(_UC("LDLTriLineIdenticalError"))); + } + return fileLineArray; +} + +LDLFileLineArray *LDLTriangleLine::removeColinearPoint(void) +{ + LDLFileLineArray *fileLineArray = removePoint(m_colinearIndex); + + if (fileLineArray) + { + UCSTRING pointStr; + + pointStr = printPoint(m_colinearIndex); + setWarning(LDLEColinear, TCLocalStrings::get(_UC("LDLTriLineCoLinear")), + m_colinearIndex + 1, pointStr.c_str()); + } + else + { + setError(LDLEGeneral, TCLocalStrings::get(_UC("LDLTriLineCoLinearError"))); + } + return fileLineArray; +} + +LDLLineLine *LDLTriangleLine::newLineLine(int p1, int p2) +{ + UCSTRING point1Str, point2Str; + char *newLine; + LDLLineLine *retValue; + std::basic_stringstream<UCSTRING::value_type> ss; + + point1Str = printPoint(p1); + point2Str = printPoint(p2); + ss << "2 " << m_colorNumber << " " << point1Str << " " << point2Str; + newLine = ucstringtombs(ss.str().c_str()); + retValue = new LDLLineLine(m_parentModel, newLine, m_lineNumber, m_line); + delete[] newLine; + return retValue; +} diff --git a/pool/shard007/C++/0094703_ndarray_tensor_bridge.cc b/pool/shard007/C++/0094703_ndarray_tensor_bridge.cc new file mode 100644 index 0000000000000000000000000000000000000000..b9a43bd8203cc5b6c3d8f850230cc2fffe4fa69c --- /dev/null +++ b/pool/shard007/C++/0094703_ndarray_tensor_bridge.cc @@ -0,0 +1,213 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Must be included first. +#include "tensorflow/python/lib/core/numpy.h" + +#include <vector> + +#include "tensorflow/c/c_api.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/python/lib/core/ndarray_tensor_bridge.h" + +namespace tensorflow { + +// Mutex used to serialize accesses to cached vector of pointers to python +// arrays to be dereferenced. +static mutex* DelayedDecrefLock() { + static mutex* decref_lock = new mutex; + return decref_lock; +} + +// Caches pointers to numpy arrays which need to be dereferenced. +static std::vector<void*>* DecrefCache() { + static std::vector<void*>* decref_cache = new std::vector<void*>; + return decref_cache; +} + +// Destructor passed to TF_NewTensor when it reuses a numpy buffer. Stores a +// pointer to the pyobj in a buffer to be dereferenced later when we're actually +// holding the GIL. +void DelayedNumpyDecref(void* data, size_t len, void* obj) { + mutex_lock ml(*DelayedDecrefLock()); + DecrefCache()->push_back(obj); +} + +// Actually dereferences cached numpy arrays. REQUIRES being called while +// holding the GIL. +void ClearDecrefCache() { + mutex_lock ml(*DelayedDecrefLock()); + for (void* obj : *DecrefCache()) { + Py_DECREF(reinterpret_cast<PyObject*>(obj)); + } + DecrefCache()->clear(); +} + +// Structure which keeps a reference to a Tensor alive while numpy has a pointer +// to it. +struct TensorReleaser { + // Python macro to include standard members. + PyObject_HEAD + + // Destructor responsible for releasing the memory. + std::function<void()>* destructor; +}; + +extern PyTypeObject TensorReleaserType; + +static void TensorReleaser_dealloc(TensorReleaser* self) { + (*self->destructor)(); + delete self->destructor; + TensorReleaserType.tp_free(self); +} + +PyTypeObject TensorReleaserType = { + PyVarObject_HEAD_INIT(nullptr, 0) /* head init */ + "tensorflow_wrapper", /* tp_name */ + sizeof(TensorReleaser), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)TensorReleaser_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + "Wrapped TensorFlow Tensor", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ +}; + +Status TF_DataType_to_PyArray_TYPE(TF_DataType tf_datatype, + int* out_pyarray_type) { + switch (tf_datatype) { + case TF_HALF: + *out_pyarray_type = NPY_FLOAT16; + break; + case TF_FLOAT: + *out_pyarray_type = NPY_FLOAT32; + break; + case TF_DOUBLE: + *out_pyarray_type = NPY_FLOAT64; + break; + case TF_INT32: + *out_pyarray_type = NPY_INT32; + break; + case TF_UINT8: + *out_pyarray_type = NPY_UINT8; + break; + case TF_UINT16: + *out_pyarray_type = NPY_UINT16; + break; + case TF_INT8: + *out_pyarray_type = NPY_INT8; + break; + case TF_INT16: + *out_pyarray_type = NPY_INT16; + break; + case TF_INT64: + *out_pyarray_type = NPY_INT64; + break; + case TF_BOOL: + *out_pyarray_type = NPY_BOOL; + break; + case TF_COMPLEX64: + *out_pyarray_type = NPY_COMPLEX64; + break; + case TF_COMPLEX128: + *out_pyarray_type = NPY_COMPLEX128; + break; + case TF_STRING: + *out_pyarray_type = NPY_OBJECT; + break; + case TF_RESOURCE: + *out_pyarray_type = NPY_VOID; + break; + // TODO(keveman): These should be changed to NPY_VOID, and the type used for + // the resulting numpy array should be the custom struct types that we + // expect for quantized types. + case TF_QINT8: + *out_pyarray_type = NPY_INT8; + break; + case TF_QUINT8: + *out_pyarray_type = NPY_UINT8; + break; + case TF_QINT16: + *out_pyarray_type = NPY_INT16; + break; + case TF_QUINT16: + *out_pyarray_type = NPY_UINT16; + break; + case TF_QINT32: + *out_pyarray_type = NPY_INT32; + break; + case TF_BFLOAT16: + *out_pyarray_type = NPY_UINT16; + break; + default: + return errors::Internal("Tensorflow type ", tf_datatype, + " not convertible to numpy dtype."); + } + return Status::OK(); +} + +Status ArrayFromMemory(int dim_size, npy_intp* dims, void* data, DataType dtype, + std::function<void()> destructor, PyObject** result) { + int size = 1; + for (int i = 0; i < dim_size; ++i) { + size *= dims[i]; + } + if (dtype == DT_STRING || dtype == DT_RESOURCE || size == 0) { + return errors::FailedPrecondition( + "Cannot convert strings, resources, or empty Tensors."); + } + + int type_num = -1; + Status s = + TF_DataType_to_PyArray_TYPE(static_cast<TF_DataType>(dtype), &type_num); + if (!s.ok()) { + return s; + } + + PyObject* np_array = + PyArray_SimpleNewFromData(dim_size, dims, type_num, data); + if (PyType_Ready(&TensorReleaserType) == -1) { + return errors::Unknown("Python type initialization failed."); + } + TensorReleaser* releaser = reinterpret_cast<TensorReleaser*>( + TensorReleaserType.tp_alloc(&TensorReleaserType, 0)); + releaser->destructor = new std::function<void()>(std::move(destructor)); + if (PyArray_SetBaseObject(reinterpret_cast<PyArrayObject*>(np_array), + reinterpret_cast<PyObject*>(releaser)) == -1) { + Py_DECREF(releaser); + return errors::Unknown("Python array refused to use memory."); + } + *result = PyArray_Return(reinterpret_cast<PyArrayObject*>(np_array)); + return Status::OK(); +} + +} // namespace tensorflow diff --git a/pool/shard007/C++/0094704_ulinks.cpp b/pool/shard007/C++/0094704_ulinks.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c8b9f1bd6bfa707604c8b9580f01e4c5736434f --- /dev/null +++ b/pool/shard007/C++/0094704_ulinks.cpp @@ -0,0 +1,93 @@ + + +static bool UnixSymlink(const char *Target,const wchar *LinkName,RarTime *ftm,RarTime *fta) +{ + CreatePath(LinkName,true); + DelFile(LinkName); + char LinkNameA[NM]; + WideToChar(LinkName,LinkNameA,ASIZE(LinkNameA)); + if (symlink(Target,LinkNameA)==-1) // Error. + { + if (errno==EEXIST) + uiMsg(UIERROR_ULINKEXIST,LinkName); + else + { + uiMsg(UIERROR_SLINKCREATE,UINULL,LinkName); + ErrHandler.SetErrorCode(RARX_WARNING); + } + return false; + } +#ifdef USE_LUTIMES +#ifdef UNIX_TIME_NS + timespec times[2]; + times[0].tv_sec=fta->GetUnix(); + times[0].tv_nsec=fta->IsSet() ? long(fta->GetUnixNS()%1000000000) : UTIME_NOW; + times[1].tv_sec=ftm->GetUnix(); + times[1].tv_nsec=ftm->IsSet() ? long(ftm->GetUnixNS()%1000000000) : UTIME_NOW; + utimensat(AT_FDCWD,LinkNameA,times,AT_SYMLINK_NOFOLLOW); +#else + struct timeval tv[2]; + tv[0].tv_sec=fta->GetUnix(); + tv[0].tv_usec=long(fta->GetUnixNS()%1000000000/1000); + tv[1].tv_sec=ftm->GetUnix(); + tv[1].tv_usec=long(ftm->GetUnixNS()%1000000000/1000); + lutimes(LinkNameA,tv); +#endif +#endif + + return true; +} + + +static bool IsFullPath(const char *PathA) // Unix ASCII version. +{ + return *PathA==CPATHDIVIDER; +} + + +bool ExtractUnixLink30(CommandData *Cmd,ComprDataIO &DataIO,Archive &Arc,const wchar *LinkName) +{ + char Target[NM]; + if (IsLink(Arc.FileHead.FileAttr)) + { + size_t DataSize=Min(Arc.FileHead.PackSize,ASIZE(Target)-1); + DataIO.UnpRead((byte *)Target,DataSize); + Target[DataSize]=0; + + DataIO.UnpHash.Init(Arc.FileHead.FileHash.Type,1); + DataIO.UnpHash.Update(Target,strlen(Target)); + DataIO.UnpHash.Result(&Arc.FileHead.FileHash); + + // Return true in case of bad checksum, so link will be processed further + // and extraction routine will report the checksum error. + if (!DataIO.UnpHash.Cmp(&Arc.FileHead.FileHash,Arc.FileHead.UseHashKey ? Arc.FileHead.HashKey:NULL)) + return true; + + if (!Cmd->AbsoluteLinks && (IsFullPath(Target) || + !IsRelativeSymlinkSafe(Arc.FileHead.FileName,Arc.FileHead.RedirName))) + return false; + return UnixSymlink(Target,LinkName,&Arc.FileHead.mtime,&Arc.FileHead.atime); + } + return false; +} + + +bool ExtractUnixLink50(CommandData *Cmd,const wchar *Name,FileHeader *hd) +{ + char Target[NM]; + WideToChar(hd->RedirName,Target,ASIZE(Target)); + if (hd->RedirType==FSREDIR_WINSYMLINK || hd->RedirType==FSREDIR_JUNCTION) + { + // Cannot create Windows absolute path symlinks in Unix. Only relative path + // Windows symlinks can be created here. RAR 5.0 used \??\ prefix + // for Windows absolute symlinks, since RAR 5.1 /??/ is used. + // We escape ? as \? to avoid "trigraph" warning + if (strncmp(Target,"\\??\\",4)==0 || strncmp(Target,"/\?\?/",4)==0) + return false; + DosSlashToUnix(Target,Target,ASIZE(Target)); + } + if (!Cmd->AbsoluteLinks && (IsFullPath(Target) || + !IsRelativeSymlinkSafe(hd->FileName,hd->RedirName))) + return false; + return UnixSymlink(Target,Name,&hd->mtime,&hd->atime); +} diff --git a/pool/shard007/C++/0094709_CollisionSphere.cpp b/pool/shard007/C++/0094709_CollisionSphere.cpp new file mode 100644 index 0000000000000000000000000000000000000000..181ed347ed77f4cd9a9d49c9ee3600bac606fa63 --- /dev/null +++ b/pool/shard007/C++/0094709_CollisionSphere.cpp @@ -0,0 +1,53 @@ +# include "include/CollisionSphere.hpp" + +# include "include/PhysicalScene.hpp" + +CollisionSphere::CollisionSphere(gloost::Vector3 const& position, float radius, bool isStatic, bool countCollision): + position_(position), + collisionPositions_(), + radius_(radius), + isStatic_(isStatic), + countCollision_(countCollision), + collisionCount_(0) { + PhysicalScene::pointer()->addSphere(this, isStatic); +} + +CollisionSphere::~CollisionSphere() { + PhysicalScene::pointer()->removeSphere(this, isStatic_); +} + +gloost::Vector3 const& CollisionSphere::getPosition() const { + return position_; +} + +float CollisionSphere::getRadius() const { + return radius_; +} + +int CollisionSphere::getCollisionCount() const { + return collisionCount_; +} + +bool CollisionSphere::isCollisionCounted() const { + return countCollision_; +} + +void CollisionSphere::setPosition(gloost::Vector3 const& position) { + position_=position; +} + +void CollisionSphere::addCollisionPosition(gloost::Vector3 const& position) { + collisionPositions_.push_back(position); +} + +std::list<gloost::Vector3> const& CollisionSphere::getCollisionPositions() const { + return collisionPositions_; +} + +void CollisionSphere::clearCollisionPositions() { + collisionPositions_.clear(); +} + +void CollisionSphere::countCollision() { + ++collisionCount_; +} diff --git a/pool/shard007/C++/0094724_stateMachine.cpp b/pool/shard007/C++/0094724_stateMachine.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4e28725ee09cb929211ea02c796bdea427586206 --- /dev/null +++ b/pool/shard007/C++/0094724_stateMachine.cpp @@ -0,0 +1,241 @@ +#include "stateMachine.hpp" +#include "state.hpp" +#include "../game/globals.hpp" + +#include <SFML/Graphics.hpp> + +void stateMachine::popStateFromStack() + { + if (!_currentStates.empty()) + { + int amount = _amountToPop; + for (int i = 0; i < amount; i++) + { + // if the state isnt nullptr + if (_currentStates.back() && !_currentStates.empty()) + { + _currentStates.back()->cleanup(); + delete _currentStates.back(); + _currentStates.back() = nullptr; + _currentStates.pop_back(); + } + else if (!_currentStates.back()) + { + _currentStates.pop_back(); + } + else + { + break; + } + + _amountToPop--; + } + } + + _popState = false; + } + +stateMachine::stateMachine(sf::RenderWindow *window) + { + _amountToPop = 0; + + _popState = false; + _closeWindow = false; + _window = window; + } + +void stateMachine::queueState(state *newState) + { + _queuedState.push(newState); + } + +void stateMachine::pushState(state *newState) + { + newState->initialize(); + _currentStates.push_back(newState); + } + +void stateMachine::popState() + { + _popState = true; + _amountToPop++; + } + +void stateMachine::popAllStates() + { + _popState = true; + _amountToPop = _currentStates.size(); + } + +void stateMachine::reinitState() + { + _currentStates.back()->initialize(); + } + +state *stateMachine::getCurrentState() const + { + if (!_currentStates.empty()) + { + return _currentStates.back(); + } + + return nullptr; + } + +std::vector<state*> *stateMachine::getAllStates() + { + return &_currentStates; + } + +state *stateMachine::getStateUnderneath() + { + if (!_currentStates.empty() && _currentStates.size() > 1) + { + return _currentStates[_currentStates.size() - 2]; + } + + return nullptr; + } + +void stateMachine::tick(sf::Time deltaTime) + { + // check if someone wants to close the window + // do this at the start of the loop so it doesnt happen inbetween rendering and updating + if (_closeWindow) + { + _window->close(); + } + + // check if a state is popped + // We need this flag so a state isnt popped/cleaned up mid render/update. If it does happen, program crashes + if (_popState) + { + // if so, pop it off the stack + popStateFromStack(); + } + + // this makes sure that a state isnt changed mid render / update + if (!_queuedState.empty()) + { + for (int i = (_queuedState.size() - 1); i >= 0; i--) + { + pushState(_queuedState.front()); + _queuedState.pop(); + } + } + + handleInput(); + update(deltaTime); + } + +void stateMachine::handleInput() + { + sf::Event event; + while (_window->pollEvent(event)) + { + // make sure a state is actually in the stack + if (!_currentStates.empty() && _currentStates.back()) + { + globals::_keyboardManager.handleInput(event, _currentStates.back()->getState()); + } + + switch (event.type) + { + case sf::Event::Closed: + _window->close(); + break; + case sf::Event::KeyPressed: + break; + default: + break; + } + } + } + +void stateMachine::update(sf::Time deltaTime) + { + if (!_currentStates.empty()) + { + for (int i = (_currentStates.size() - 1); i >= 0; i--) + { + // update the state and check if they want to have underneath states update + // if they dont want to update overtop, break out of the loop + // if so, continue down the stack + _currentStates[i]->update(deltaTime); + if (!_currentStates[i]->updateUnderneath()) + { + break; + } + } + } + } + +void stateMachine::render() + { + _window->clear(sf::Color::Black); + if (!_currentStates.empty()) + { + for (int i = (_currentStates.size() - 1); i >= 0; i--) + { + // render the state and check if they want to render overtop + // if they dont want to render overtop, break out of the loop + // if so, continue down the stack + + if (!_currentStates[i]->renderOvertop()) + { + _currentStates[i]->render(); + break; + } + else + { + // if the state wants to be rendered overtop the current state + // check if there is any state underneath + if (i >= 1) + { + // if so, render that state + _currentStates[i - 1]->render(); + // and increment the count down so the state underneath doesnt render over the current state + _currentStates[i--]->render(); + } + else// otherwise render like normal + { + _currentStates[i]->render(); + } + } + } + } + _window->display(); + } + +void stateMachine::closeWindow() + { + _closeWindow = true; + } + +sf::RenderWindow *stateMachine::getWindow() const + { + return _window; + } + +void stateMachine::setWindow(sf::RenderWindow *window) + { + _window = window; + } + +void stateMachine::cleanup() + { + for (auto &topState : _currentStates) + { + if (topState) + { + topState->cleanup(); + delete topState; + topState = nullptr; + } + } + } + +stateMachine::~stateMachine() + { + cleanup(); + } diff --git a/pool/shard007/C++/0094726_accountscombobox.cpp b/pool/shard007/C++/0094726_accountscombobox.cpp new file mode 100644 index 0000000000000000000000000000000000000000..12bb37376189aaed89a618f061bf22ddd17e887f --- /dev/null +++ b/pool/shard007/C++/0094726_accountscombobox.cpp @@ -0,0 +1,106 @@ +/* + * accountscombobox.cpp + * Copyright (C) 2001, 2002 Justin Karneges + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +#include "psicon.h" +#include "accountscombobox.h" +#include "psiaccount.h" +#include "psicontactlist.h" + +AccountsComboBox::AccountsComboBox(PsiCon *_psi, QWidget *parent, bool online_only) +:QComboBox(parent), onlineOnly(online_only) +{ + psi = _psi; + // TODO: Status changes of accounts should be notified when onlineOnly is true + connect(psi, SIGNAL(accountCountChanged()), this, SLOT(updateAccounts())); + connect(psi, SIGNAL(destroyed()), SLOT(deleteMe())); + connect(this, SIGNAL(activated(int)), this, SLOT(changeAccount())); + if (online_only) + connect(psi, SIGNAL(accountActivityChanged()), this, SLOT(updateAccounts())); + + pa = 0; + setSizePolicy(QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::Fixed )); + + if(psi->contactList()->haveEnabledAccounts()) + setAccount(psi->contactList()->enabledAccounts().first()); +} + +AccountsComboBox::~AccountsComboBox() +{ +} + +void AccountsComboBox::setAccount(PsiAccount *_pa) +{ + pa = _pa; + updateAccounts(); +} + +void AccountsComboBox::changeAccount() +{ + int i = currentItem(); + + int n = 0; + bool found = false; + foreach(PsiAccount* p, psi->contactList()->enabledAccounts()) { + if (!onlineOnly || p->loggedIn()) { + if(i == n) { + pa = p; + found = true; + break; + } + ++n; + } + } + if(!found) + pa = 0; + + activated(pa); +} + +void AccountsComboBox::updateAccounts() +{ + clear(); + int n = 0; + bool found = false; + PsiAccount *firstAccount = 0; + foreach(PsiAccount* p, psi->contactList()->enabledAccounts()) { + if (!onlineOnly || p->loggedIn()) { + insertItem(p->nameWithJid()); + if(p == pa) { + setCurrentItem(n); + found = true; + } + if (!firstAccount) + firstAccount = p; + ++n; + } + } + if(!found) { + // choose a different account + pa = firstAccount; + activated(pa); + } +} + +void AccountsComboBox::deleteMe() +{ + delete this; +} + + diff --git a/pool/shard007/C++/0094727_html_track_element.cc b/pool/shard007/C++/0094727_html_track_element.cc new file mode 100644 index 0000000000000000000000000000000000000000..67d538e51865f795bc9ceac3344a413a5a698a12 --- /dev/null +++ b/pool/shard007/C++/0094727_html_track_element.cc @@ -0,0 +1,347 @@ +/* + * Copyright (C) 2011 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: + * 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. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "third_party/blink/renderer/core/html/track/html_track_element.h" + +#include "third_party/blink/public/platform/task_type.h" +#include "third_party/blink/renderer/core/css/css_style_sheet.h" +#include "third_party/blink/renderer/core/dom/document.h" +#include "third_party/blink/renderer/core/dom/events/event.h" +#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h" +#include "third_party/blink/renderer/core/html/cross_origin_attribute.h" +#include "third_party/blink/renderer/core/html/media/html_media_element.h" +#include "third_party/blink/renderer/core/html/track/loadable_text_track.h" +#include "third_party/blink/renderer/core/html_names.h" +#include "third_party/blink/renderer/platform/heap/heap.h" + +#define TRACK_LOG_LEVEL 3 + +namespace blink { + +static String UrlForLoggingTrack(const KURL& url) { + static const unsigned kMaximumURLLengthForLogging = 128; + + if (url.GetString().length() < kMaximumURLLengthForLogging) + return url.GetString(); + return url.GetString().Substring(0, kMaximumURLLengthForLogging) + "..."; +} + +HTMLTrackElement::HTMLTrackElement(Document& document) + : HTMLElement(html_names::kTrackTag, document), + load_timer_(document.GetTaskRunner(TaskType::kNetworking), + this, + &HTMLTrackElement::LoadTimerFired) { + DVLOG(TRACK_LOG_LEVEL) << "HTMLTrackElement - " << (void*)this; +} + +HTMLTrackElement::~HTMLTrackElement() = default; + +Node::InsertionNotificationRequest HTMLTrackElement::InsertedInto( + ContainerNode& insertion_point) { + DVLOG(TRACK_LOG_LEVEL) << "insertedInto"; + + // Since we've moved to a new parent, we may now be able to load. + ScheduleLoad(); + + HTMLElement::InsertedInto(insertion_point); + HTMLMediaElement* parent = MediaElement(); + if (&insertion_point == parent) + parent->DidAddTrackElement(this); + return kInsertionDone; +} + +void HTMLTrackElement::RemovedFrom(ContainerNode& insertion_point) { + auto* html_media_element = DynamicTo<HTMLMediaElement>(insertion_point); + if (html_media_element && !parentNode()) + html_media_element->DidRemoveTrackElement(this); + HTMLElement::RemovedFrom(insertion_point); +} + +void HTMLTrackElement::ParseAttribute( + const AttributeModificationParams& params) { + const QualifiedName& name = params.name; + if (name == html_names::kSrcAttr) { + ScheduleLoad(); + + // 4.8.10.12.3 Sourcing out-of-band text tracks + // As the kind, label, and srclang attributes are set, changed, or removed, + // the text track must update accordingly... + } else if (name == html_names::kKindAttr) { + AtomicString lower_case_value = params.new_value.LowerASCII(); + // 'missing value default' ("subtitles") + if (lower_case_value.IsNull()) + lower_case_value = TextTrack::SubtitlesKeyword(); + // 'invalid value default' ("metadata") + else if (!TextTrack::IsValidKindKeyword(lower_case_value)) + lower_case_value = TextTrack::MetadataKeyword(); + + track()->SetKind(lower_case_value); + } else if (name == html_names::kLabelAttr) { + track()->SetLabel(params.new_value); + } else if (name == html_names::kSrclangAttr) { + track()->SetLanguage(params.new_value); + } else if (name == html_names::kIdAttr) { + track()->SetId(params.new_value); + } + + HTMLElement::ParseAttribute(params); +} + +const AtomicString& HTMLTrackElement::kind() { + return track()->kind(); +} + +void HTMLTrackElement::setKind(const AtomicString& kind) { + setAttribute(html_names::kKindAttr, kind); +} + +LoadableTextTrack* HTMLTrackElement::EnsureTrack() { + if (!track_) { + // kind, label and language are updated by parseAttribute + track_ = MakeGarbageCollected<LoadableTextTrack>(this); + } + return track_.Get(); +} + +TextTrack* HTMLTrackElement::track() { + return EnsureTrack(); +} + +bool HTMLTrackElement::IsURLAttribute(const Attribute& attribute) const { + return attribute.GetName() == html_names::kSrcAttr || + HTMLElement::IsURLAttribute(attribute); +} + +void HTMLTrackElement::ScheduleLoad() { + DVLOG(TRACK_LOG_LEVEL) << "scheduleLoad"; + + // 1. If another occurrence of this algorithm is already running for this text + // track and its track element, abort these steps, letting that other + // algorithm take care of this element. + if (load_timer_.IsActive()) + return; + + // 2. If the text track's text track mode is not set to one of hidden or + // showing, abort these steps. + if (EnsureTrack()->mode() != TextTrack::HiddenKeyword() && + EnsureTrack()->mode() != TextTrack::ShowingKeyword()) + return; + + // 3. If the text track's track element does not have a media element as a + // parent, abort these steps. + if (!MediaElement()) + return; + + // 4. Run the remainder of these steps in parallel, allowing whatever caused + // these steps to run to continue. + load_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); + + // 5. Top: Await a stable state. The synchronous section consists of the + // following steps. (The steps in the synchronous section are marked with [X]) + // FIXME: We use a timer to approximate a "stable state" - i.e. this is not + // 100% per spec. +} + +void HTMLTrackElement::LoadTimerFired(TimerBase*) { + DVLOG(TRACK_LOG_LEVEL) << "loadTimerFired"; + + // 7. [X] Let URL be the track URL of the track element. + KURL url = GetNonEmptyURLAttribute(html_names::kSrcAttr); + + // Whenever a track element has its src attribute set, changed, + // or removed, the user agent must immediately empty the + // element's text track's text track list of cues. + // Currently there are no other implementations clearing cues + // list _immediately_, so we are trying to align with what they are + // doing and remove cues as part of the synchronous section. + // Also we will first check if the new URL is not equal with + // the previous URL (there is an unclarified issue in spec + // about it, see: https://github.com/whatwg/html/issues/2916) + if (url == url_ && getReadyState() != kNone) + return; + + if (track_) + track_->Reset(); + + url_ = url; + + // 6. [X] Set the text track readiness state to loading. + // Step 7 does not depend on step 6, so they were reordered to grant + // setting kLoading state after the equality check + SetReadyState(kLoading); + + // 8. [X] If the track element's parent is a media element then let CORS mode + // be the state of the parent media element's crossorigin content attribute. + // Otherwise, let CORS mode be No CORS. + const AtomicString& cors_mode = MediaElementCrossOriginAttribute(); + + // 9. End the synchronous section, continuing the remaining steps in parallel. + + // 10. If URL is not the empty string, perform a potentially CORS-enabled + // fetch of URL, with the mode being CORS mode, the origin being the origin of + // the track element's node document, and the default origin behaviour set to + // fail. + if (!CanLoadUrl(url)) { + DidCompleteLoad(kFailure); + return; + } + + if (loader_) + loader_->CancelLoad(); + + loader_ = + MakeGarbageCollected<TextTrackLoader, TextTrackLoaderClient&, Document&>( + *this, GetDocument()); + if (!loader_->Load(url_, GetCrossOriginAttributeValue(cors_mode))) + DidCompleteLoad(kFailure); +} + +bool HTMLTrackElement::CanLoadUrl(const KURL& url) { + HTMLMediaElement* parent = MediaElement(); + if (!parent) + return false; + + if (url.IsEmpty()) + return false; + + if (!GetDocument().GetContentSecurityPolicy()->AllowMediaFromSource(url)) { + DVLOG(TRACK_LOG_LEVEL) << "canLoadUrl(" << UrlForLoggingTrack(url) + << ") -> rejected by Content Security Policy"; + return false; + } + + return true; +} + +void HTMLTrackElement::DidCompleteLoad(LoadStatus status) { + // 10. ... (continued) + + // If the fetching algorithm fails for any reason (network error, the server + // returns an error code, a cross-origin check fails, etc), or if URL is the + // empty string, then queue a task to first change the text track readiness + // state to failed to load and then fire a simple event named error at the + // track element. This task must use the DOM manipulation task source. + // + // (Note: We don't "queue a task" here because this method will only be called + // from a timer - load_timer_ or TextTrackLoader::cue_load_timer_ - which + // should be a reasonable, and hopefully non-observable, approximation of the + // spec text. I.e we could consider this to be run from the "networking task + // source".) + // + // If the fetching algorithm does not fail, but the type of the resource is + // not a supported text track format, or the file was not successfully + // processed (e.g. the format in question is an XML format and the file + // contained a well-formedness error that the XML specification requires be + // detected and reported to the application), then the task that is queued by + // the networking task source in which the aforementioned problem is found + // must change the text track readiness state to failed to load and fire a + // simple event named error at the track element. + if (status == kFailure) { + SetReadyState(kError); + DispatchEvent(*Event::Create(event_type_names::kError)); + return; + } + + // If the fetching algorithm does not fail, and the file was successfully + // processed, then the final task that is queued by the networking task + // source, after it has finished parsing the data, must change the text track + // readiness state to loaded, and fire a simple event named load at the track + // element. + SetReadyState(kLoaded); + DispatchEvent(*Event::Create(event_type_names::kLoad)); +} + +void HTMLTrackElement::NewCuesAvailable(TextTrackLoader* loader) { + DCHECK_EQ(loader_, loader); + DCHECK(track_); + + HeapVector<Member<TextTrackCue>> new_cues; + loader_->GetNewCues(new_cues); + + HeapVector<Member<CSSStyleSheet>> new_sheets; + loader_->GetNewStyleSheets(new_sheets); + + if (!new_sheets.IsEmpty()) { + track_->SetCSSStyleSheets(std::move(new_sheets)); + } + + track_->AddListOfCues(new_cues); +} + +void HTMLTrackElement::CueLoadingCompleted(TextTrackLoader* loader, + bool loading_failed) { + DCHECK_EQ(loader_, loader); + + DidCompleteLoad(loading_failed ? kFailure : kSuccess); +} + +// NOTE: The values in the TextTrack::ReadinessState enum must stay in sync with +// those in HTMLTrackElement::ReadyState. +static_assert( + HTMLTrackElement::kNone == + static_cast<HTMLTrackElement::ReadyState>(TextTrack::kNotLoaded), + "HTMLTrackElement::kNone should be in sync with TextTrack::NotLoaded"); +static_assert( + HTMLTrackElement::kLoading == + static_cast<HTMLTrackElement::ReadyState>(TextTrack::kLoading), + "HTMLTrackElement::kLoading should be in sync with TextTrack::Loading"); +static_assert( + HTMLTrackElement::kLoaded == + static_cast<HTMLTrackElement::ReadyState>(TextTrack::kLoaded), + "HTMLTrackElement::kLoaded should be in sync with TextTrack::Loaded"); +static_assert( + HTMLTrackElement::kError == + static_cast<HTMLTrackElement::ReadyState>(TextTrack::kFailedToLoad), + "HTMLTrackElement::kError should be in sync with TextTrack::FailedToLoad"); + +void HTMLTrackElement::SetReadyState(ReadyState state) { + EnsureTrack()->SetReadinessState( + static_cast<TextTrack::ReadinessState>(state)); + if (HTMLMediaElement* parent = MediaElement()) + return parent->TextTrackReadyStateChanged(track_.Get()); +} + +HTMLTrackElement::ReadyState HTMLTrackElement::getReadyState() { + return track_ ? static_cast<ReadyState>(track_->GetReadinessState()) : kNone; +} + +const AtomicString& HTMLTrackElement::MediaElementCrossOriginAttribute() const { + if (HTMLMediaElement* parent = MediaElement()) + return parent->FastGetAttribute(html_names::kCrossoriginAttr); + + return g_null_atom; +} + +HTMLMediaElement* HTMLTrackElement::MediaElement() const { + return DynamicTo<HTMLMediaElement>(parentElement()); +} + +void HTMLTrackElement::Trace(Visitor* visitor) { + visitor->Trace(track_); + visitor->Trace(loader_); + HTMLElement::Trace(visitor); +} + +} // namespace blink diff --git a/pool/shard007/C++/0094729_DeferringCondition.cc b/pool/shard007/C++/0094729_DeferringCondition.cc new file mode 100644 index 0000000000000000000000000000000000000000..04f26f5fb10a6d47f2a50afe8ce52990d1868be8 --- /dev/null +++ b/pool/shard007/C++/0094729_DeferringCondition.cc @@ -0,0 +1,35 @@ +/* +* Artery V2X Simulation Framework +* Copyright 2020 Raphael Riebl +* Licensed under GPLv2, see COPYING file for detailed license and warranty terms. +*/ + +#include "artery/storyboard/DeferringCondition.h" +#include "artery/utility/PointerCheck.h" + +namespace artery +{ + +DeferringCondition::DeferringCondition(omnetpp::cRNG* rng, omnetpp::SimTime min, omnetpp::SimTime max) : + mRNG(notNullPtr(rng)), mMinDeferral(min), mMaxDeferral(max) +{ +} + +ConditionResult DeferringCondition::testCondition(const Vehicle& v) +{ + const omnetpp::SimTime now = omnetpp::simTime(); + bool result = false; + + auto found = mDeferrals.find(&v); + if (found != mDeferrals.end()) { + result = found->second <= now; + } else { + omnetpp::SimTime deferral = now + omnetpp::uniform(mRNG, mMinDeferral, mMaxDeferral); + result = (deferral <= now); + mDeferrals[&v] = deferral; + } + + return result; +} + +} // namespace artery diff --git a/pool/shard007/C++/0094732_UnixWindow.cpp b/pool/shard007/C++/0094732_UnixWindow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..005eeb3382bbea405fe8bba244b9a8eeb28426c0 --- /dev/null +++ b/pool/shard007/C++/0094732_UnixWindow.cpp @@ -0,0 +1,94 @@ +#include "UnixWindow.h" + +#include <QApplication> +#include <QDesktopWidget> +#include <QVBoxLayout> +#include <QMouseEvent> + +#include <iostream> + +UnixWindow::UnixWindow() +{ + setObjectName("unixWindow"); + + mainPanel = new UnixPanel(this); + + QVBoxLayout* layout = new QVBoxLayout(); + layout->setMargin(0); + setLayout(layout); + layout->addWidget(mainPanel); + + this->setWindowFlags(Qt::FramelessWindowHint); + mainPanel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + + // Center window at runtime + QRect rec = QApplication::desktop()->screenGeometry(); + int width = 1152, height = 648, screenWidth = rec.width(), screenHeight = rec.height(); + int offsetX = (screenWidth - width) / 2; + int offsetY = (screenHeight - height) / 2; + + this->resize(width, height); + this->move(offsetX, offsetY); + this->show(); +} + +void UnixWindow::minimize() +{ + showMinimized(); +} + +void UnixWindow::maximize() +{ + if (isMaximized()) + { + showNormal(); + } + else + { + showMaximized(); + } +} + +void UnixWindow::closeWindow() +{ + this->close(); +} + +void UnixWindow::mousePressEvent(QMouseEvent* evt) +{ + oldWindowPos = evt->globalPos(); + if (evt->pos().y() < 32) + { + if (evt->button() == Qt::LeftButton) + { + dragging = true; + } + } +} + +void UnixWindow::mouseDoubleClickEvent(QMouseEvent* evt) +{ + if (evt->pos().y() < 32) + { + if (evt->button() == Qt::LeftButton) + { + maximize(); + } + } +} + +void UnixWindow::mouseReleaseEvent(QMouseEvent* evt) +{ + dragging = false; +} + +void UnixWindow::mouseMoveEvent(QMouseEvent* evt) +{ + const QPoint c_delta = evt->globalPos() - oldWindowPos; + if (dragging) + { + dragging = true; + move(x() + c_delta.x(), y() + c_delta.y()); + oldWindowPos = evt->globalPos(); + } +} diff --git a/pool/shard007/C++/0094733_psp_origin.cpp b/pool/shard007/C++/0094733_psp_origin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c10d4c0fc0f26dbe56234c42ac543ebf06d36bc7 --- /dev/null +++ b/pool/shard007/C++/0094733_psp_origin.cpp @@ -0,0 +1,146 @@ +/* +UserinfoEx plugin for Miranda IM + +Copyright: +© 2006-2010 DeathAxe, Yasnovidyashii, Merlin, K. Romanov, Kreol + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ + +#include "stdafx.h" + +/** + * This is the dialog procedure for the advanced contact information propertysheetpage. + * + * @param hDlg - handle to the dialog window + * @param uMsg - the message to handle + * @param wParam - parameter + * @param lParam - parameter + * + * @return different values + **/ +INT_PTR CALLBACK PSPProcOrigin(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + switch (uMsg) { + case WM_INITDIALOG: + { + CCtrlList *pCtrlList = CCtrlList::CreateObj(hDlg); + if (pCtrlList) { + LPIDSTRLIST pList; + UINT nList; + + HFONT hBoldFont; + PSGetBoldFont(hDlg, hBoldFont); + SendDlgItemMessage(hDlg, IDC_PAGETITLE, WM_SETFONT, (WPARAM)hBoldFont, 0); + + TranslateDialogDefault(hDlg); + SetTimer(hDlg, 1, 5000, nullptr); + + pCtrlList->insert(CEditCtrl::CreateObj(hDlg, EDIT_STREET, SET_CONTACT_ORIGIN_STREET, DBVT_WCHAR)); + pCtrlList->insert(CEditCtrl::CreateObj(hDlg, EDIT_ZIP, SET_CONTACT_ORIGIN_ZIP, DBVT_WCHAR)); + pCtrlList->insert(CEditCtrl::CreateObj(hDlg, EDIT_CITY, SET_CONTACT_ORIGIN_CITY, DBVT_WCHAR)); + pCtrlList->insert(CEditCtrl::CreateObj(hDlg, EDIT_STATE, SET_CONTACT_ORIGIN_STATE, DBVT_WCHAR)); + + GetCountryList(&nList, &pList); + pCtrlList->insert(CCombo::CreateObj(hDlg, EDIT_COUNTRY, SET_CONTACT_ORIGIN_COUNTRY, DBVT_WORD, pList, nList)); + + pCtrlList->insert(CTzCombo::CreateObj(hDlg, EDIT_TIMEZONE, nullptr)); + } + } + break; + + case WM_NOTIFY: + { + switch (((LPNMHDR) lParam)->idFrom) { + case 0: + { + MCONTACT hContact = (MCONTACT)((LPPSHNOTIFY)lParam)->lParam; + LPCSTR pszProto; + + switch (((LPNMHDR) lParam)->code) { + case PSN_INFOCHANGED: + { + if (!PSGetBaseProto(hDlg, pszProto) || *pszProto == 0) + break; + + if (hContact) { + MTime mt; + + if (mt.DBGetStamp(hContact, USERINFO, SET_CONTACT_ADDEDTIME) && strstr(pszProto, "ICQ")) { + uint32_t dwStamp; + + dwStamp = DB::Contact::WhenAdded(db_get_dw(hContact, pszProto, "UIN", 0), pszProto); + if (dwStamp > 0) + mt.FromStampAsUTC(dwStamp); + } + if (mt.IsValid()) { + wchar_t szTime[MAX_PATH]; + LPTSTR ptr; + + mt.UTCToLocal(); + mt.DateFormatLong(szTime, _countof(szTime)); + + mir_wstrcat(szTime, L" - "); + ptr = szTime + mir_wstrlen(szTime); + mt.TimeFormat(ptr, _countof(szTime) - (ptr - szTime)); + SetDlgItemText(hDlg, TXT_DATEADDED, szTime); + } + } + + SetWindowLongPtr(hDlg, DWLP_MSGRESULT, 0); + } + break; + + case PSN_ICONCHANGED: + { + const ICONCTRL idIcon[] = { + { IDI_TREE_ADDRESS, STM_SETIMAGE, ICO_ADDRESS }, + { IDI_CLOCK, STM_SETIMAGE, ICO_CLOCK }, + }; + + IcoLib_SetCtrlIcons(hDlg, idIcon, _countof(idIcon)); + } + } + } + } /* switch (((LPNMHDR)lParam)->idFrom) */ + } + break; + + case WM_COMMAND: + { + switch (LOWORD(wParam)) { + case EDIT_COUNTRY: + if (HIWORD(wParam) == CBN_SELCHANGE) { + LPIDSTRLIST pd = (LPIDSTRLIST)ComboBox_GetItemData((HWND)lParam, ComboBox_GetCurSel((HWND)lParam)); + UpDate_CountryIcon(GetDlgItem(hDlg, ICO_COUNTRY), pd->nID); + } + break; + } + } + break; + + case WM_TIMER: + { + wchar_t szTime[32]; + CTzCombo::GetObj(hDlg, EDIT_TIMEZONE)->GetTime(szTime, _countof(szTime)); + SetDlgItemText(hDlg, TXT_TIME, szTime); + break; + } + + case WM_DESTROY: + KillTimer(hDlg, 1); + } + return PSPBaseProc(hDlg, uMsg, wParam, lParam); +} diff --git a/pool/shard007/C++/0094735_module_test_registry.cpp b/pool/shard007/C++/0094735_module_test_registry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..22d01292e6460083f5791ba02673e70cbe265ce9 --- /dev/null +++ b/pool/shard007/C++/0094735_module_test_registry.cpp @@ -0,0 +1,31 @@ +/** + * See boost trac ticket: https://svn.boost.org/trac/boost/ticket/7548 + */ + +#include <boost/python.hpp> +#include <vector> +#include <iostream> + + +std::vector<double> list_of_doubles() { + std::vector<double> retval; + retval.push_back(3); + retval.push_back(2); + return retval; +} + + +// Instantiate the core module. +BOOST_PYTHON_MODULE(test_registry) +{ + using namespace boost::python; + + //We check if a converter for std::vector has been registered + type_info info = boost::python::type_id<std::vector<double> >(); + const converter::registration* reg = boost::python::converter::registry::query(info); + //We output to screen the result (should be NULL) + std::cout << reg << " "; + + //We also expose a function that needs such a conversion (to_python) + def("list_of_doubles",list_of_doubles); +} diff --git a/pool/shard007/C++/0094736_mb_validrun.cpp b/pool/shard007/C++/0094736_mb_validrun.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9bf7230b16da3f6dc22f142f1bf0b220815dbb7c --- /dev/null +++ b/pool/shard007/C++/0094736_mb_validrun.cpp @@ -0,0 +1,147 @@ +/* + * validrun.c + * + * Functions for determining if a section of the tape buffer can be + * turned into a valid work unit + * + * $Id: mb_validrun.cpp,v 1.1.2.1 2006/12/14 22:24:45 korpela Exp $ + * + */ + +#include "sah_config.h" +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <assert.h> +#include "setilib.h" +#include "splitparms.h" +#include "splittypes.h" +#include "splitter.h" +#include "message.h" + + +bool valid_run(std::vector<dr2_compact_block_t> &tapebuffer, int min_vgc) { + unsigned long start_dataseq=tapebuffer[0].header.dataseq; + unsigned long end_dataseq=tapebuffer[tapebuffer.size()-1].header.dataseq; + bool valid=true; + int i; + + // check for missing frames + if(!(end_dataseq-start_dataseq)==(tapebuffer.size()-1)) { + valid = false; + log_messages.printf(SCHED_MSG_LOG::MSG_NORMAL,"Missing frames between %lu and %lu\n", + tapebuffer[0].header.dataseq,tapebuffer[tapebuffer.size()-1].header.dataseq); + for (i=tapebuffer.size()-1;i>0;i--) { // find the last "in sequence" frame + if (tapebuffer[i-1].header.dataseq != (tapebuffer[i].header.dataseq-1)) { + tapebuffer.erase(tapebuffer.begin(),tapebuffer.begin()+i); // delete all frames prior to the miss + } + } + } + + // if still valid, check for failed blanking signal acquisition + if (valid) { + for (i=0;valid && (i<tapebuffer.size());i++) { + if (tapebuffer[i].header.blanking_failed) { + valid = false; + log_messages.printf(SCHED_MSG_LOG::MSG_NORMAL,"Failed blanking at dataseq %lu (between %lu and %lu)\n", + tapebuffer[i].header.dataseq, tapebuffer[0].header.dataseq,tapebuffer[tapebuffer.size()-1].header.dataseq); + tapebuffer.erase(tapebuffer.begin(),tapebuffer.begin()+i+1); // delete all frames through the fail + } + } + } + + // if still valid, check for changed frequency + if (valid) { + for (i=0;valid && (i<tapebuffer.size());i++) { + if (tapebuffer[i].header.sky_freq != tapebuffer[0].header.sky_freq) { + valid = false; + log_messages.printf(SCHED_MSG_LOG::MSG_NORMAL,"Frequency changed from %f to %f at dataseq %lu (between %lu and %lu)\n", + tapebuffer[i].header.sky_freq,tapebuffer[0].header.sky_freq, + tapebuffer[i].header.dataseq, tapebuffer[0].header.dataseq,tapebuffer[tapebuffer.size()-1].header.dataseq); + tapebuffer.erase(tapebuffer.begin(),tapebuffer.begin()+i+1); // delete all frames through the change + } + } + } + + // if still valid, check we are above minimum vgc values + if (valid && min_vgc > 0) { + for (i=0;valid && (i<tapebuffer.size());i++) { + if (get_vgc_for_channel(tapebuffer[i].header.channel,tapebuffer[i].header) < min_vgc) { + valid = false; + log_messages.printf(SCHED_MSG_LOG::MSG_NORMAL,"VGC value %d is below minimum (%d) at dataseq %lu\n", + get_vgc_for_channel(tapebuffer[i].header.channel,tapebuffer[i].header), min_vgc, tapebuffer[i].header.dataseq); + // tapebuffer.erase(tapebuffer.begin(),tapebuffer.begin()+i+1); // delete all frames through the change + tapebuffer.erase(tapebuffer.begin(),tapebuffer.end()-1); // delete all frames in entire tapebuffer (except last)! + } + } + } + + return(valid); +} + + +/* + * $Log: mb_validrun.cpp,v $ + * Revision 1.1.2.1 2006/12/14 22:24:45 korpela + * *** empty log message *** + * + * Revision 1.2.4.1 2006/01/13 00:37:58 korpela + * Moved splitter to using standard BOINC logging mechanisms. All stderr now + * goes to "error.log" + * + * Added command line parameters "-iterations=" (number of workunit groups to + * create before exiting), "-trigger_file_path=" (path to the splitter_stop trigger + * file. Default is /disks/setifiler1/wutape/tapedir/splitter_stop). + * + * Reduced deadlines by a factor of three. We now need a 30 MFLOP machine to meet + * the deadline. + * + * Revision 1.2 2003/09/11 18:53:38 korpela + * *** empty log message *** + * + * Revision 1.1 2003/07/29 20:35:57 korpela + * + * renames .C files to .cpp + * + * Revision 1.1 2003/06/03 00:23:43 korpela + * + * Again + * + * Revision 3.0 2001/08/01 19:04:57 korpela + * Check this in before Paul screws it up. + * + * Revision 2.7 2000/12/01 01:13:29 korpela + * *** empty log message *** + * + * Revision 2.6 1999/06/07 21:00:52 korpela + * *** empty log message *** + * + * Revision 2.5 1999/03/27 16:19:35 korpela + * *** empty log message *** + * + * Revision 2.4 1999/02/22 22:21:09 korpela + * added -nodb option + * + * Revision 2.3 1999/02/11 16:46:28 korpela + * Added checkpointing. + * + * Revision 2.2 1998/11/04 23:08:25 korpela + * Byte and bit order change. + * + * Revision 2.1 1998/11/02 16:41:21 korpela + * Minor Change. + * + * Revision 2.0 1998/10/30 22:00:04 korpela + * Conversion to C++ and merger with client source tree. + * + * Revision 1.3 1998/10/30 20:26:03 korpela + * Bug Fixes. Now mostly working. + * + * Revision 1.2 1998/10/27 00:59:22 korpela + * Bug fixes. + * + * Revision 1.1 1998/10/22 17:48:20 korpela + * Initial revision + * + * + */ diff --git a/pool/shard007/C++/0094742_DescribeLoadBalancerPoliciesResult.cpp b/pool/shard007/C++/0094742_DescribeLoadBalancerPoliciesResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a30ca9c7fa5d0d823e81cc1817898480911d85a5 --- /dev/null +++ b/pool/shard007/C++/0094742_DescribeLoadBalancerPoliciesResult.cpp @@ -0,0 +1,69 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include <aws/elasticloadbalancing/model/DescribeLoadBalancerPoliciesResult.h> +#include <aws/core/utils/xml/XmlSerializer.h> +#include <aws/core/AmazonWebServiceResult.h> +#include <aws/core/utils/StringUtils.h> +#include <aws/core/utils/logging/LogMacros.h> + +#include <utility> + +using namespace Aws::ElasticLoadBalancing::Model; +using namespace Aws::Utils::Xml; +using namespace Aws::Utils::Logging; +using namespace Aws::Utils; +using namespace Aws; + +DescribeLoadBalancerPoliciesResult::DescribeLoadBalancerPoliciesResult() +{ +} + +DescribeLoadBalancerPoliciesResult::DescribeLoadBalancerPoliciesResult(const AmazonWebServiceResult<XmlDocument>& result) +{ + *this = result; +} + +DescribeLoadBalancerPoliciesResult& DescribeLoadBalancerPoliciesResult::operator =(const AmazonWebServiceResult<XmlDocument>& result) +{ + const XmlDocument& xmlDocument = result.GetPayload(); + XmlNode rootNode = xmlDocument.GetRootElement(); + XmlNode resultNode = rootNode; + if (rootNode.GetName() != "DescribeLoadBalancerPoliciesResult") + { + resultNode = rootNode.FirstChild("DescribeLoadBalancerPoliciesResult"); + } + + if(!resultNode.IsNull()) + { + XmlNode policyDescriptionsNode = resultNode.FirstChild("PolicyDescriptions"); + if(!policyDescriptionsNode.IsNull()) + { + XmlNode policyDescriptionsMember = policyDescriptionsNode.FirstChild("member"); + while(!policyDescriptionsMember.IsNull()) + { + m_policyDescriptions.push_back(policyDescriptionsMember); + policyDescriptionsMember = policyDescriptionsMember.NextNode("member"); + } + + } + } + + XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); + m_responseMetadata = responseMetadataNode; + AWS_LOGSTREAM_DEBUG("Aws::ElasticLoadBalancing::Model::DescribeLoadBalancerPoliciesResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() ); + + return *this; +} diff --git a/pool/shard007/C++/0094750_NamedFileSystem.cpp b/pool/shard007/C++/0094750_NamedFileSystem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..25b482279c94b5892e9d596f681158e00a644f2a --- /dev/null +++ b/pool/shard007/C++/0094750_NamedFileSystem.cpp @@ -0,0 +1,312 @@ +/* Author: Stephen Austin Shiner + * Account #28 + * Author: Sarah Nolasco + * Account #23 + * Created: 10/31/2014 + * Completed: 11/05/2014 (Alpha) + * Purpose: CSC 331 File System Term Project + * Utilizes primary and secondary keys along with an index file to create and + * maintain a database-like information management system + * + * + */ + +// Preprocessor Directives +#include "FileSystem.h" +using namespace std; + +//name this file system +int main(int argc, char * argv[]) +{ + bool cont = true; + while(cont) + { + cout<<"Please enter a command or Q to quit"<<endl; + + string userInput; + getline(cin, userInput); + istringstream iss(userInput); + string command; + iss>>command; + + //switch statement + switch( command.at(0) ) + { + case 'q' : + { + cout<<"Closing..."<<endl; + cont = false; + + } + break; + + case'm' : + { + string modKey; + iss>>modKey; + string datalabel; + iss>>datalabel; + string newdata; + iss>>newdata; + + mod(atoi(modKey.c_str()), datalabel, newdata); + } + break; + + case 'd' : + { + string deleteKey; + iss>>deleteKey; + + deleteItem(atoi(deleteKey.c_str())); + } + break; + + case 's' : + { + string searchKey; + iss>>searchKey; + + searchItem(atoi(searchKey.c_str())); + } + break; + + case 'a' : + { + string addkey; + iss>>addkey; + string addname; + iss>>addname; + string code; + iss>>code; + string cost; + iss>>cost; + addItem(atoi(addkey.c_str()), addname, atoi(code.c_str()), atof(cost.c_str()) ); + } + break; + } + } + return(0); +} + +int deleteItem(int key) +{ + + fstream ioFile("file.bin", ios::binary | ios::in | ios::out); // Open data binary file + if (ioFile.fail()) // If output file was not successfully opened + { // Inform user of file opening failure and exit program run + cout << "Data file failed to open. Program is ending. Goodbye." << endl; + exit(1); // End program run with error value + } + + int tempRRN = search(key); + + if(tempRRN != -1) // Delete record from index file + { + Record delRecord; // Record to be "deleted" by setting its keys to -1 + + ioFile.seekp(sizeof(Record) * tempRRN); // Move file cursor to beginning of deleted record + ioFile.read((char *) &delRecord, sizeof(Record)); // Read in record to be deleted + ioFile.seekp(sizeof(Record) * tempRRN); // Reset pointer to start of record + + deleteFromPrimaryIndexFile(delRecord.getKey()); + + delRecord.setKey(-1); + delRecord.setCode(-1); + ioFile.write((char *) &delRecord, sizeof(Record)); // Write record back to file + + cout << "Record with key " << key << " was successfully deleted." << endl; // Output success message + } + else // record not found, output failure message to user + cout << "Sorry, a record with key " << key << " was not found, and could not be deleted." << endl; + + ioFile.close(); // Terminate program/file connection with data file + + return 0; // Return successful program run + + +} + + +int searchItem(int key) +{ + + // TODO: ADD COMMAND-LINE ERROR CHECKING + + int targetRRN = search(key); // Call search function and assign its return value to local variable + + if (targetRRN == -1) // Target not found, inform the user + cout << "Sorry, record with primary key " << key << " was not found." << endl; + else // Target was found in the index file, open the data file and seek to the appropriate position + { // Open output binary file in append mode, cursor at the end (ate) + ifstream dataFile("file.bin", ios::binary | ios::in); + if (dataFile.fail()) // If output file was not successfully opened + { // Inform user of file opening failure and exit program run + cout << "Output file failed to open. Program is ending. Goodbye." << endl; + exit(1); // End program run with error value + } + + dataFile.seekg(sizeof(Record) * targetRRN, ios::beg); // Seek to proper position in file + Record targetRecord; // Will hold target Record read in from data file + + // Read in target record as a Record object + dataFile.read((char *) &targetRecord, sizeof(Record)); + + dataFile.close(); // Terminate file/program connection with data file + + // Send target Record information to the console output stream + cout << "Target record successfully located: " << endl + << targetRecord.getKey() << " " << targetRecord.getName() << " " + << targetRecord.getCode() << " " << targetRecord.getCost() << endl; + } +} + + +int mod( int key, string datalabel, string newdata) +{ + + fstream ioFile("file.bin", ios::binary | ios::in | ios::out | ios::ate); // Open data binary file + if (ioFile.fail()) // If output file was not successfully opened + { // Inform user of file opening failure and exit program run + cout << "Data file failed to open. Program is ending. Goodbye." << endl; + exit(1); // End program run with error value + } + + Record headerRecord; // Create empty, dummy header Record, may hold actual header Record if file isn't empty + + if (ioFile.tellg() < 7) // Check if data file is empty, ie it has no header Record + { // empty file, cannot modify, inform user + cout << "Sorry, but the data file is empty and therefore cannot be modified." << endl; + } + else // File is NOT empty + { + int tempRRN = search(key); + + Record modRecord; // Will hold record and its modified version + + ioFile.seekp(sizeof(Record) * tempRRN, ios::beg); // Move file cursor to beginning of record + ioFile.read((char *) &modRecord, sizeof(Record)); // Read in record to be modified + ioFile.seekp(sizeof(Record) * tempRRN, ios::beg); // Reset cursor to start of record + + if(strcmp(datalabel, "code") == 0) + { + // change code in record + modRecord.setCode(atoi(newdata.c_str())); + // TODO: add new value in secondary index + } + else if(strcmp(datalabel, "key") == 0) + { + // Change key for data Record + modRecord.setKey(atoi(newdata.c_str())); + + // Update primary index file with new key value for the data item + fstream primaryIndexFile("primaryindex.idx", ios::binary | ios::in | ios::out); + if (primaryIndexFile.fail()) // If index file was not successfully opened + { // Inform user of file opening failure and exit program run + cout << "Primary Index file failed to open. Program is ending. Goodbye." << endl; + exit(1); // End program run with error value + } + + PrimaryIndex modIndex; // To write out to the index file + + // Move cursor to index position to update + primaryIndexFile.seekp(sizeof(PrimaryIndex) * (tempRRN - 1), ios::beg); + + primaryIndexFile.read((char *) &modIndex, sizeof(PrimaryIndex)); + + modIndex.setKey(atoi(newdata.c_str())); // Set new key value + + // Move cursor to index position to update + primaryIndexFile.seekp(sizeof(PrimaryIndex) * (tempRRN - 1), ios::beg); + + primaryIndexFile.write((char *) &modIndex, sizeof(PrimaryIndex)); + + primaryIndexFile.close(); // Terminate program/file connection + } + else if (strcmp(datalabel, "cost") == 0) // edit cost in file + modRecord.setCost(atof(newdata.c_str())); + else if (strcmp(datalabel, "name") == 0) + { + // edit name in file + modRecord.setName(newdata); + } + else // Invalid type, print failure message and exit program run after closing file + { + cout << "Sorry, " << datalabel << " is not a valid command parameter." << endl; + ioFile.close(); // Terminate program/file connection + exit(1); // End program run with error value + } + + ioFile.write((char *) &modRecord, sizeof(Record)); // Write modified record to file + ioFile.close(); // Terminate program/file connection + + // Output success message to user + cout << "Record with key " << key << " was successfully modified by changing its " + << datalabel << " to " << newdata << endl; + } + + return 0; // Return successful program run +} + + +int addItem(int key, string name, int code, float cost) +{ + ifstream fileExists("file.bin", ios::in | ios::binary); + + if (fileExists.fail()) // If failed to open, then file doesnt exist yet + { + fileExists.close(); + fstream newOutputFile("file.bin", ios::out | ios::binary); // Creates empty binary file + newOutputFile.close(); // Terminate program/file connection with empty bianry file + } + else + fileExists.close(); + + // Open output binary file, with cursor at the end (ate) + fstream outputFile("file.bin", ios::in | ios::out | ios::binary); + + if (outputFile.fail()) // If output file was not successfully opened + { // Inform user of file opening failure and exit program run + cout << "Output file failed to open. Program is ending. Goodbye." << endl; + exit(1); // End program run with error value + } + + //fstream inputFile("file.bin", ios::in | ios::binary); + + outputFile.seekp(0, ios::end); // Move file cursor to the end + + Record headerRecord; // Create empty, dummy header Record, may hold actual header Record if file isn't empty + + if (outputFile.tellg() < 7) // Check if data file is empty, ie it has no header Record + { + headerRecord.setKey(headerRecord.getKey() + 1); // Increment header Record count by one + outputFile.write((char *) &headerRecord, sizeof(Record)); // Write header record to file + } + else // File is NOT empty + { + outputFile.seekg(0, ios::beg); // Move extraction file cursor to beginning of the file + outputFile.read((char *) &headerRecord, sizeof(Record)); // Read in header Record + headerRecord.setKey(headerRecord.getKey() + 1); // Increment header Record count by one + outputFile.seekp(0, ios::beg); // Move file cursor to beginning of the file + outputFile.write((char *) &headerRecord, sizeof(Record)); // Write header record to file + } + + // TODO: ADD COMMAND-LINE ERROR CHECKING + + // Create new Record object using the user's command-line input + Record newRecord(key, name, code, cost); + + // Call function to write primary index entry out to primary index file + updatePrimaryIndexFile(newRecord.getKey(), headerRecord.getKey()); + + outputFile.seekp(0, ios::end); // Move insertion pointer to the end of the binary output file + + outputFile.write((char *) &newRecord, sizeof(Record)); // Write serialized Record object out to the data file + + outputFile.close(); // Terminate program connection with output data file + + cout << "Record with key " << key << " has been successfully added." << endl; + + return 0; // Return successful program run +} + diff --git a/pool/shard007/C++/0094751_TestCasePlayerModule.cpp b/pool/shard007/C++/0094751_TestCasePlayerModule.cpp new file mode 100644 index 0000000000000000000000000000000000000000..397bd521b660a8f48246918eba50080f72f858db --- /dev/null +++ b/pool/shard007/C++/0094751_TestCasePlayerModule.cpp @@ -0,0 +1,167 @@ +// +// Copyright (c) 2009-2014 Shawn Singh, Glen Berseth, Mubbasir Kapadia, Petros Faloutsos, Glenn Reinman +// See license.txt for complete license. +// + +/// @file TestCasePlayerModule.cpp +/// @brief Implements the TestCasePlayerModule built-in module. + +#include "modules/TestCasePlayerModule.h" +#include "testcaseio/TestCaseIO.h" +#include "util/Misc.h" + +using namespace SteerLib; + +// #define _DEBUG 1 + +void TestCasePlayerModule::init( const SteerLib::OptionDictionary & options, SteerLib::EngineInterface * engineInfo ) { + _engine = engineInfo; + _testCaseFilename = ""; + _aiModuleName = ""; + _aiModuleSearchPath = ""; + _aiModule = NULL; + _obstacles.clear(); + + // parse command line options + SteerLib::OptionDictionary::const_iterator optionIter; + for (optionIter = options.begin(); optionIter != options.end(); ++optionIter) { + if ((*optionIter).first == "testcase") { + _testCaseFilename = (*optionIter).second; + } + else if ((*optionIter).first == "ai") { + _aiModuleName = (*optionIter).second; + } + else { + throw Util::GenericException("unrecognized option \"" + Util::toString((*optionIter).first) + "\" given to testCasePlayer module."); + } + } + + // load the module if it is not already + if ( !_engine->isModuleLoaded(_aiModuleName) ) { + _engine->loadModule(_aiModuleName,_aiModuleSearchPath,""); + /// @todo add a boolean that flags this module was loaded here, so that we can unload the module after the simulation is done. + } + + // get a pointer to the loaded module + _aiModule = _engine->getModule(_aiModuleName); + + +#ifdef ENABLE_GUI +#ifdef ENABLE_QT + + QMainWindow * mainWindow = (QMainWindow*)(_engine->getEngineController()->getQtMainWindow()); + + if(mainWindow != NULL) { + + /// @todo why is this tooltip attribute here, and not in the engine driver? + mainWindow->QWidget::setAttribute(Qt::WA_AlwaysShowToolTips); + + _testCasePlayerDockWidget = new QDockWidget("Test Case Player"); + _testCasePlayerWidget = new SteerSimQt::TestCasePlayerWidget(this, _engine); + _testCasePlayerDockWidget->setWidget(_testCasePlayerWidget); + mainWindow->addDockWidget(Qt::RightDockWidgetArea, _testCasePlayerDockWidget); + } + else { + _testCasePlayerDockWidget = NULL; + _testCasePlayerWidget = NULL; + } +#endif +#endif +} + +void TestCasePlayerModule::initializeSimulation() { + + SteerLib::TestCaseReader * testCaseReader; + + std::string testCasePath; + + // try to find the test case in several ways: + if (Util::fileCanBeOpened(_testCaseFilename)) { + testCasePath = _testCaseFilename; + } + else if (Util::fileCanBeOpened( _engine->getTestCaseSearchPath() + _testCaseFilename )) { + testCasePath = _engine->getTestCaseSearchPath() + _testCaseFilename; + } + else if (Util::fileCanBeOpened(_testCaseFilename + ".xml")) { + testCasePath = _testCaseFilename + ".xml"; + } + else if (Util::fileCanBeOpened( _engine->getTestCaseSearchPath() + _testCaseFilename + ".xml" )) { + testCasePath = _engine->getTestCaseSearchPath() + _testCaseFilename + ".xml"; + } + else { + throw Util::GenericException("Could not find test case " + _testCaseFilename + "."); + } + + // open the test case + testCaseReader = new SteerLib::TestCaseReader(); + testCaseReader->readTestCaseFromFile(testCasePath); + + //Create the obstacles + for (unsigned int i=0; i < testCaseReader->getNumObstacles(); i++) { + const SteerLib::ObstacleInitialConditions * ic = testCaseReader->getObstacleInitialConditions(i); + /*SteerLib::BoxObstacle * b; + b = new SteerLib::BoxObstacle(ic.xmin, ic.xmax, ic.ymin, ic.ymax, ic.zmin, ic.zmax);*/ + SteerLib::ObstacleInterface *b = const_cast<SteerLib::ObstacleInitialConditions*>(ic)->createObstacle(); // TODO: FIX THIS. + _obstacles.push_back(b); + _engine->addObstacle(b); + _engine->getSpatialDatabase()->addObject( b, b->getBounds()); + // std::cout << "adding obstacle"; + } + + //Create the agents + for (unsigned int i=0; i < testCaseReader->getNumAgents(); i++) { + const SteerLib::AgentInitialConditions & ic = testCaseReader->getAgentInitialConditions(i); + _engine->createAgent( ic, _aiModule ); + } + + delete testCaseReader; + + +#ifdef ENABLE_GUI +#ifdef ENABLE_QT + if (_testCasePlayerWidget != NULL) _testCasePlayerWidget->setFrameNumber(_engine->getClock().getCurrentFrameNumber()); +#endif +#endif + +} + +void TestCasePlayerModule::postprocessFrame(float timeStamp, float dt, unsigned int frameNumber) { +#ifdef ENABLE_GUI +#ifdef ENABLE_QT + if (_testCasePlayerWidget != NULL) _testCasePlayerWidget->setFrameNumber(frameNumber); +#endif +#endif +} + + +void TestCasePlayerModule::cleanupSimulation() { +#ifdef _DEBUG + std::cout << "about to TestCasePlayerModule::cleanupSimulation();\n"; +#endif + for (unsigned int i=0; i<_obstacles.size(); i++) { + _engine->getSpatialDatabase()->removeObject( _obstacles[i], _obstacles[i]->getBounds()); + _engine->removeObstacle(_obstacles[i]); + delete _obstacles[i]; + } + _obstacles.clear(); + + _engine->destroyAllAgentsFromModule(_aiModule); +} + + +void TestCasePlayerModule::finish() { + +#ifdef ENABLE_GUI +#ifdef ENABLE_QT + + QMainWindow * mainWindow = (QMainWindow*)(_engine->getEngineController()->getQtMainWindow()); + if(mainWindow != NULL) { + mainWindow->removeDockWidget(_testCasePlayerDockWidget); + delete _testCasePlayerDockWidget; + delete _testCasePlayerWidget; // may not be necessary, do Qt automatically take control and de-allocate children widgets? + } + +#endif +#endif + +} diff --git a/pool/shard007/C++/0094752_CWE194_Unexpected_Sign_Extension__connect_socket_malloc_81_bad.cpp b/pool/shard007/C++/0094752_CWE194_Unexpected_Sign_Extension__connect_socket_malloc_81_bad.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba382145fafff04a1d3f360e8a13fdf74e5ff687 --- /dev/null +++ b/pool/shard007/C++/0094752_CWE194_Unexpected_Sign_Extension__connect_socket_malloc_81_bad.cpp @@ -0,0 +1,42 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE194_Unexpected_Sign_Extension__connect_socket_malloc_81_bad.cpp +Label Definition File: CWE194_Unexpected_Sign_Extension.label.xml +Template File: sources-sink-81_bad.tmpl.cpp +*/ +/* + * @description + * CWE: 194 Unexpected Sign Extension + * BadSource: connect_socket Read data using a connect socket (client side) + * GoodSource: Positive integer + * Sinks: malloc + * BadSink : Allocate memory using malloc() with the size of data + * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference + * + * */ +#ifndef OMITBAD + +#include "std_testcase.h" +#include "CWE194_Unexpected_Sign_Extension__connect_socket_malloc_81.h" + +namespace CWE194_Unexpected_Sign_Extension__connect_socket_malloc_81 +{ + +void CWE194_Unexpected_Sign_Extension__connect_socket_malloc_81_bad::action(short data) const +{ + /* Assume we want to allocate a relatively small buffer */ + if (data < 100) + { + /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative, + * the conversion will cause malloc() to allocate a very large amount of data or fail */ + char * dataBuffer = (char *)malloc(data); + if (dataBuffer == NULL) {exit(-1);} + /* Do something with dataBuffer */ + memset(dataBuffer, 'A', data-1); + dataBuffer[data-1] = '\0'; + printLine(dataBuffer); + free(dataBuffer); + } +} + +} +#endif /* OMITBAD */ diff --git a/pool/shard007/C++/0094753_PresetReaderJson.cpp b/pool/shard007/C++/0094753_PresetReaderJson.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8dbeba38edc746dbd528f55d10cf4c395011aaad --- /dev/null +++ b/pool/shard007/C++/0094753_PresetReaderJson.cpp @@ -0,0 +1,108 @@ +/* + * File: PresetReaderJson.cpp + * Author: HoelscJ + * + * Created on 23. Mai 2011, 16:24 + */ +#include "org/esb/db/HiveDb.hpp" +#include "PresetReaderJson.h" +#include "org/esb/util/Log.h" +#include "org/esb/util/StringUtil.h" +#include "org/esb/libjson/libjson.h" +#include "org/esb/av/AV.h" +#include "org/esb/lang/Exception.h" +#include "org/esb/config/config.h" +#include "DatabaseService.h" +namespace org { + namespace esb { + namespace hive { + using org::esb::util::StringUtil; + PresetReaderJson::PresetReaderJson(std::string data) { + LOGDEBUG("Preset Data:" << data); + JSONNode node = libjson::parse(data); + if(node.contains("profile-uuid")){ + db::HiveDb db=DatabaseService::getDatabase();//"sqlite3", org::esb::config::Config::get("db.url")); + litesql::DataSource<db::Preset>s = litesql::select<db::Preset > (db, db::Preset::Uuid == node["profile-uuid"].as_string()); + if(s.count()==1){ + data=s.one().data; + }else{ + throw org::esb::lang::Exception(__FILE__,__LINE__,"profile defined by profile-uuid not found"); + } + node = libjson::parse(data); + } + if (node.contains("format") && node["format"].contains("id")) { + _preset["id"] = node["format"]["id"].as_string(); + if(node.contains("name")){ + _preset["name"]=node["name"].as_string(); + } + }else{ + throw org::esb::lang::Exception(__FILE__,__LINE__,"no format attribute found"); + } + std::string type; + type = "video"; + if (node.contains(type)) { + int c = node[type].size(); + for (int a = 0; a < c; a++) { + JSONNode n = node[type].at(a); + std::string name = n.name(); + std::string value = n.as_string(); + /*filter out some unwanted attributes*/ + if (name == "frame_size"){ + int width; + int height; + int result=sscanf(value.c_str(),"%dx%d", &width, &height); + LOGDEBUG("width="<<width); + LOGDEBUG("width="<<height); + _codecs[type]["width"]=StringUtil::toString(width); + _codecs[type]["height"]=StringUtil::toString(height); + continue; + } + //LOGDEBUG("json type : "<<n.type()); + if (name == "id") { + name = "codec_id"; + } + if (name == "b" || name == "maxrate" || name == "bt" || name == "bufsize" || name == "minrate") + value += "000"; + LOGDEBUG("Name=" << name << " val=" << value); + + _codecs[type][name] = value; //.insert(std::pair<std::string, std::string>(name,value)); + } + }else{ + throw org::esb::lang::Exception(__FILE__,__LINE__,"no video attribute found"); + } + type = "audio"; + if (node.contains(type)) { + int c = node[type].size(); + for (int a = 0; a < c; a++) { + JSONNode n = node[type].at(a); + LOGDEBUG("Name=" << n.name() << " val=" << n.as_string()); + if (n.name() == "id") { + n.set_name("codec_id"); + //AVCodec * codec=avcodec_find_encoder_by_name(n.as_string().c_str()); + //n=JSONNode("codec_id",codec->id); + } + _codecs[type][n.name()] = n.as_string(); //.insert(std::pair<std::string, std::string>(n.name(),n.as_string())); + } + }else{ + throw org::esb::lang::Exception(__FILE__,__LINE__,"no audio attribute found"); + } + } + + PresetReaderJson::~PresetReaderJson() { + } + + PresetReaderJson::Preset PresetReaderJson::getPreset() { + return _preset; + } + + PresetReaderJson::CodecList PresetReaderJson::getCodecList() { + return _codecs; + } + + PresetReaderJson::FilterList PresetReaderJson::getFilterList() { + return _filters; + } + + } + } +} diff --git a/pool/shard007/C++/0094754_main.cpp b/pool/shard007/C++/0094754_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..75dec839c2c38231fbfaa3049ab20616b2b82719 --- /dev/null +++ b/pool/shard007/C++/0094754_main.cpp @@ -0,0 +1,130 @@ +#define H2D_REPORT_WARN +#define H2D_REPORT_INFO +#define H2D_REPORT_VERBOSE +#define H2D_REPORT_FILE "application.log" +#include "hermes2d.h" +#include "function.h" + +// This example shows how to set an arbitrary initial guess for the +// Newton's method, and nonzero Dirichlet boundary conditions. +// +// PDE: stationary heat transfer equation with nonlinear thermal +// conductivity, - div[lambda(u)grad u] = 0 +// +// Domain: unit square (-10,10)^2 +// +// BC: Dirichlet, see function dir_lift() below. +// +// The following parameters can be changed: + +const int P_INIT = 2; // Initial polynomial degree +const double NEWTON_TOL = 1e-6; // Stopping criterion for the Newton's method +const int NEWTON_MAX_ITER = 100; // Maximum allowed number of Newton iterations +const int INIT_GLOB_REF_NUM = 3; // Number of initial uniform mesh refinements +const int INIT_BDY_REF_NUM = 4; // Number of initial refinements towards boundary + +// Thermal conductivity (temperature-dependent). +// Note: for any u, this function has to be positive. +template<typename Real> +Real lam(Real u) +{ + return 1 + pow(u, 4); +} + +// Derivative of the thermal conductivity with respect to 'u'. +template<typename Real> +Real dlam_du(Real u) { + return 4*pow(u, 3); +} + +// This function is used to define Dirichlet boundary conditions. +double dir_lift(double x, double y, double& dx, double& dy) { + dx = (y+10)/10.; + dy = (x+10)/10.; + return (x+10)*(y+10)/100.; +} + +// Initial condition. It will be projected on the FE mesh +// to obtain initial coefficient vector for the Newton's method. +scalar init_cond(double x, double y, double& dx, double& dy) +{ + // Using the Dirichlet lift elevated by two + double val = dir_lift(x, y, dx, dy) + 2; + return val; +} + +// Boundary condition types. +BCType bc_types(int marker) +{ + return BC_ESSENTIAL; +} + +// Essential (Dirichlet) boundary condition values. +scalar essential_bc_values(int ess_bdy_marker, double x, double y) +{ + double dx, dy; + return dir_lift(x, y, dx, dy); +} + +// Heat sources (can be a general function of 'x' and 'y'). +template<typename Real> +Real heat_src(Real x, Real y) +{ + return 1.0; +} + +// Weak forms. +#include "forms.cpp" + +int main(int argc, char* argv[]) +{ + // Load the mesh. + Mesh mesh; + H2DReader mloader; + mloader.load("square.mesh", &mesh); + + // Perform initial mesh refinements. + for(int i = 0; i < INIT_GLOB_REF_NUM; i++) mesh.refine_all_elements(); + mesh.refine_towards_boundary(1,INIT_BDY_REF_NUM); + + // Create an H1 space with default shapeset. + H1Space space(&mesh, bc_types, essential_bc_values, P_INIT); + + // Previous solution for the Newton's method. + Solution u_prev; + + // Initialize the weak formulation + WeakForm wf; + wf.add_matrix_form(callback(jac), H2D_UNSYM, H2D_ANY, &u_prev); + wf.add_vector_form(callback(res), H2D_ANY, &u_prev); + + // Initialize the linear system. + NonlinSystem nls(&wf, &space); + + // Project the function init_cond() on the FE space + // to obtain initial coefficient vector for the Newton's method. + info("Projecting initial condition to obtain initial vector for the Newton'w method."); + nls.project_global(init_cond, &u_prev); + + // Perform Newton's iteration. + info("Performing Newton's iteration."); + bool verbose = true; // Default is false. + if (!nls.solve_newton(&u_prev, NEWTON_TOL, NEWTON_MAX_ITER, verbose)) + error("Newton's method did not converge."); + + // Visualise the solution and mesh. + ScalarView sview("Solution", 0, 0, 400, 300); + OrderView oview("Mesh", 410, 0, 400, 300); + char title[100]; + sprintf(title, "Solution"); + sview.set_title(title); + sview.show(&u_prev); + sprintf(title, "Mesh"); + oview.set_title(title); + oview.show(&space); + + // Wait for all views to be closed. + View::wait(); + return 0; +} + diff --git a/pool/shard007/C++/0094758_dijkstra_no_color_map_compare.cpp b/pool/shard007/C++/0094758_dijkstra_no_color_map_compare.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7f39e0daf9140f4e9f610f3648241f497b1da957 --- /dev/null +++ b/pool/shard007/C++/0094758_dijkstra_no_color_map_compare.cpp @@ -0,0 +1,122 @@ +//======================================================================= +// Copyright 2009 Trustees of Indiana University. +// Authors: Michael Hansen +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +//======================================================================= + +#include <iostream> +#include <map> +#include <vector> + +#include <boost/lexical_cast.hpp> +#include <boost/random.hpp> +#include <boost/graph/adjacency_list.hpp> +#include <boost/graph/dijkstra_shortest_paths.hpp> +#include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp> +#include <boost/graph/properties.hpp> +#include <boost/graph/random.hpp> +#include <boost/test/minimal.hpp> +#include <boost/graph/iteration_macros.hpp> + +#define INITIALIZE_VERTEX 0 +#define DISCOVER_VERTEX 1 +#define EXAMINE_VERTEX 2 +#define EXAMINE_EDGE 3 +#define EDGE_RELAXED 4 +#define EDGE_NOT_RELAXED 5 +#define FINISH_VERTEX 6 + +template <typename Graph> +void run_dijkstra_test(const Graph& graph) +{ + using namespace boost; + + // Set up property maps + typedef typename graph_traits<Graph>::vertex_descriptor vertex_t; + + typedef typename std::map<vertex_t, vertex_t> vertex_map_t; + typedef associative_property_map<vertex_map_t> predecessor_map_t; + vertex_map_t default_vertex_map, no_color_map_vertex_map; + predecessor_map_t default_predecessor_map(default_vertex_map), + no_color_map_predecessor_map(no_color_map_vertex_map); + + typedef typename std::map<vertex_t, double> vertex_double_map_t; + typedef associative_property_map<vertex_double_map_t> distance_map_t; + vertex_double_map_t default_vertex_double_map, no_color_map_vertex_double_map; + distance_map_t default_distance_map(default_vertex_double_map), + no_color_map_distance_map(no_color_map_vertex_double_map); + + // Run dijkstra algoirthms + dijkstra_shortest_paths(graph, vertex(0, graph), + predecessor_map(default_predecessor_map) + .distance_map(default_distance_map)); + + dijkstra_shortest_paths_no_color_map(graph, vertex(0, graph), + predecessor_map(no_color_map_predecessor_map) + .distance_map(no_color_map_distance_map)); + + // Verify that predecessor maps are equal + BOOST_CHECK(std::equal(default_vertex_map.begin(), default_vertex_map.end(), + no_color_map_vertex_map.begin())); + + // Verify that distance maps are equal + BOOST_CHECK(std::equal(default_vertex_double_map.begin(), default_vertex_double_map.end(), + no_color_map_vertex_double_map.begin())); +} + +int test_main(int argc, char* argv[]) +{ + using namespace boost; + + int vertices_to_create = 10; + int edges_to_create = 500; + std::size_t random_seed = time(0); + + if (argc > 1) { + vertices_to_create = lexical_cast<int>(argv[1]); + } + + if (argc > 2) { + edges_to_create = lexical_cast<int>(argv[2]); + } + + if (argc > 3) { + random_seed = lexical_cast<std::size_t>(argv[3]); + } + + minstd_rand generator(random_seed); + + // Set up graph + typedef adjacency_list<listS, listS, directedS, + property<vertex_index_t, int >, + property<edge_weight_t, double> > graph_t; + + typedef graph_traits<graph_t>::vertex_descriptor vertex_t; + typedef graph_traits<graph_t>::edge_descriptor edge_t; + + graph_t graph; + generate_random_graph(graph, vertices_to_create, edges_to_create, generator); + + // Set up property maps + typedef property_map<graph_t, vertex_index_t>::type index_map_t; + index_map_t index_map = get(vertex_index, graph); + int vertex_index = 0; + + BGL_FORALL_VERTICES(current_vertex, graph, graph_t) { + put(index_map, current_vertex, vertex_index++); + } + + randomize_property<edge_weight_t>(graph, generator); + + // Run comparison test with original dijkstra_shortest_paths + std::cout << "Running dijkstra shortest paths test with " << num_vertices(graph) << + " vertices and " << num_edges(graph) << " edges " << std::endl; + + run_dijkstra_test(graph); + + return 0; +} + diff --git a/pool/shard007/C++/0094760_parallel_vector_06.cc b/pool/shard007/C++/0094760_parallel_vector_06.cc new file mode 100644 index 0000000000000000000000000000000000000000..f35732e78bb6dfcb0c3fefdfd0c1b0dd525a11e6 --- /dev/null +++ b/pool/shard007/C++/0094760_parallel_vector_06.cc @@ -0,0 +1,164 @@ +// --------------------------------------------------------------------- +// +// Copyright (C) 2011 - 2016 by the deal.II authors +// +// This file is part of the deal.II library. +// +// The deal.II library is free software; you can use it, redistribute +// it, and/or modify it under the terms of the GNU Lesser General +// Public License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// The full text of the license can be found in the file LICENSE at +// the top level of the deal.II distribution. +// +// --------------------------------------------------------------------- + + +// check global reduction operation (norms, operator==, operator!=) on +// parallel vector + +#include "../tests.h" +#include <deal.II/base/utilities.h> +#include <deal.II/base/index_set.h> +#include <deal.II/lac/la_parallel_vector.h> +#include <iostream> +#include <vector> + + +void test () +{ + unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD); + unsigned int numproc = Utilities::MPI::n_mpi_processes (MPI_COMM_WORLD); + + if (myid==0) deallog << "numproc=" << numproc << std::endl; + + + // each processor from processor 1 to 8 + // owns 2 indices (the other processors do + // not own any dof), and all processors are + // ghosting element 1 (the second) + IndexSet local_owned(std::min(16U,numproc*2)); + if (myid < 8) + local_owned.add_range(myid*2,myid*2+2); + IndexSet local_relevant(numproc*2); + local_relevant = local_owned; + local_relevant.add_range(1,2); + + LinearAlgebra::distributed::Vector<double> v(local_owned, local_owned, MPI_COMM_WORLD); + + // set local values + if (myid < 8) + { + v(myid*2)=myid*2.0; + v(myid*2+1)=myid*2.0+1.0; + } + v.compress(VectorOperation::insert); + v*=2.0; + if (myid < 8) + { + AssertThrow(v(myid*2) == myid*4.0, ExcInternalError()); + AssertThrow(v(myid*2+1) == myid*4.0+2.0, ExcInternalError()); + } + + // check l2 norm + { + const double l2_norm = v.l2_norm(); + if (myid == 0) + deallog << "l2 norm: " << l2_norm << std::endl; + } + + // check l1 norm + { + const double l1_norm = v.l1_norm(); + if (myid == 0) + deallog << "l1 norm: " << l1_norm << std::endl; + } + + // check linfty norm + { + const double linfty_norm = v.linfty_norm(); + if (myid == 0) + deallog << "linfty norm: " << linfty_norm << std::endl; + } + + // check lp norm + { + const double lp_norm = v.lp_norm(2.2); + if (myid == 0) + deallog << "l2.2 norm: " << lp_norm << std::endl; + + Assert (std::fabs (v.l2_norm() - v.lp_norm(2.0)) < 1e-14, + ExcInternalError()); + } + + // check mean value (should be equal to l1 + // norm divided by vector size here since we + // have no negative entries) + { + const double mean = v.mean_value(); + if (myid == 0) + deallog << "Mean value: " << mean << std::endl; + + Assert (std::fabs (mean * v.size() - v.l1_norm()) < 1e-15, + ExcInternalError()); + } + // check inner product + { + const double norm_sqr = v.l2_norm() * v.l2_norm(); + AssertThrow (std::fabs(v * v - norm_sqr) < 1e-15, + ExcInternalError()); + LinearAlgebra::distributed::Vector<double> v2; + v2 = v; + AssertThrow (std::fabs(v2 * v - norm_sqr) < 1e-15, + ExcInternalError()); + + if (myid<8) + v2.local_element(0) = -1; + const double inner_prod = v * v2; + if (myid == 0) + deallog << "Inner product: " << inner_prod << std::endl; + } + + // check all_zero + { + bool allzero = v.all_zero(); + if (myid == 0) + deallog << " v==0 ? " << allzero << std::endl; + LinearAlgebra::distributed::Vector<double> v2; + v2.reinit (v); + allzero = v2.all_zero(); + if (myid == 0) + deallog << " v2==0 ? " << allzero << std::endl; + + // now change one element to nonzero + if (myid == 0) + v2.local_element(1) = 1; + allzero = v2.all_zero(); + if (myid == 0) + deallog << " v2==0 ? " << allzero << std::endl; + } + + if (myid == 0) + deallog << "OK" << std::endl; +} + + + +int main (int argc, char **argv) +{ + Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, testing_max_num_threads()); + + unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD); + deallog.push(Utilities::int_to_string(myid)); + + if (myid == 0) + { + initlog(); + deallog << std::setprecision(4); + + test(); + } + else + test(); + +} diff --git a/pool/shard007/C++/0094761_Instance.cpp b/pool/shard007/C++/0094761_Instance.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a179fa14f72432ddf58daee411510e4c51c28c4f --- /dev/null +++ b/pool/shard007/C++/0094761_Instance.cpp @@ -0,0 +1,134 @@ +// Copyright 2004-present Facebook. All Rights Reserved. + +#include "Instance.h" + +#include "Executor.h" +#include "MethodCall.h" +#include "SystraceSection.h" + +#include <folly/json.h> +#include <folly/Memory.h> +#include <folly/MoveWrapper.h> + +#include <glog/logging.h> + +#include <condition_variable> +#include <fstream> +#include <mutex> +#include <string> + +namespace facebook { +namespace react { + +Instance::~Instance() { + if (nativeToJsBridge_) { + nativeToJsBridge_->destroy(); + } +} + +void Instance::initializeBridge( + std::unique_ptr<InstanceCallback> callback, + std::shared_ptr<JSExecutorFactory> jsef, + std::shared_ptr<MessageQueueThread> jsQueue, + std::unique_ptr<MessageQueueThread> nativeQueue, + std::shared_ptr<ModuleRegistry> moduleRegistry) { + callback_ = std::move(callback); + + jsQueue->runOnQueueSync( + [this, &jsef, moduleRegistry, jsQueue, + nativeQueue=folly::makeMoveWrapper(std::move(nativeQueue))] () mutable { + nativeToJsBridge_ = folly::make_unique<NativeToJsBridge>( + jsef.get(), moduleRegistry, jsQueue, nativeQueue.move(), callback_); + }); + + CHECK(nativeToJsBridge_); +} + +void Instance::loadScriptFromString(std::unique_ptr<const JSBigString> string, + std::string sourceURL) { + callback_->incrementPendingJSCalls(); + SystraceSection s("reactbridge_xplat_loadScriptFromString", + "sourceURL", sourceURL); + // TODO mhorowitz: ReactMarker around loadApplicationScript + nativeToJsBridge_->loadApplicationScript(std::move(string), std::move(sourceURL)); +} + +void Instance::loadScriptFromFile(const std::string& filename, + const std::string& sourceURL) { + // TODO mhorowitz: ReactMarker around file read + std::unique_ptr<JSBigBufferString> buf; + { + SystraceSection s("reactbridge_xplat_loadScriptFromFile", + "fileName", filename); + + std::ifstream jsfile(filename); + if (!jsfile) { + LOG(ERROR) << "Unable to load script from file" << filename; + } else { + jsfile.seekg(0, std::ios::end); + buf.reset(new JSBigBufferString(jsfile.tellg())); + jsfile.seekg(0, std::ios::beg); + jsfile.read(buf->data(), buf->size()); + } + } + + loadScriptFromString(std::move(buf), sourceURL); +} + +void Instance::loadUnbundle(std::unique_ptr<JSModulesUnbundle> unbundle, + std::unique_ptr<const JSBigString> startupScript, + std::string startupScriptSourceURL) { + callback_->incrementPendingJSCalls(); + SystraceSection s("reactbridge_xplat_setJSModulesUnbundle"); + nativeToJsBridge_->loadApplicationUnbundle(std::move(unbundle), std::move(startupScript), + std::move(startupScriptSourceURL)); +} + +bool Instance::supportsProfiling() { + return nativeToJsBridge_->supportsProfiling(); +} + +void Instance::startProfiler(const std::string& title) { + return nativeToJsBridge_->startProfiler(title); +} + +void Instance::stopProfiler(const std::string& title, const std::string& filename) { + return nativeToJsBridge_->stopProfiler(title, filename); +} + +void Instance::setGlobalVariable(std::string propName, + std::unique_ptr<const JSBigString> jsonValue) { + nativeToJsBridge_->setGlobalVariable(std::move(propName), std::move(jsonValue)); +} + +void Instance::callJSFunction(ExecutorToken token, const std::string& module, const std::string& method, + folly::dynamic&& params, const std::string& tracingName) { + SystraceSection s(tracingName.c_str()); + callback_->incrementPendingJSCalls(); + nativeToJsBridge_->callFunction(token, module, method, std::move(params), tracingName); +} + +void Instance::callJSCallback(ExecutorToken token, uint64_t callbackId, folly::dynamic&& params) { + SystraceSection s("<callback>"); + callback_->incrementPendingJSCalls(); + nativeToJsBridge_->invokeCallback(token, (double) callbackId, std::move(params)); +} + +ExecutorToken Instance::getMainExecutorToken() { + return nativeToJsBridge_->getMainExecutorToken(); +} + +void Instance::handleMemoryPressureUiHidden() { + nativeToJsBridge_->handleMemoryPressureUiHidden(); +} + +void Instance::handleMemoryPressureModerate() { + nativeToJsBridge_->handleMemoryPressureModerate(); +} + +void Instance::handleMemoryPressureCritical() { + nativeToJsBridge_->handleMemoryPressureCritical(); +} + +} // namespace react +} // namespace facebook diff --git a/pool/shard007/C++/0094762_moc_bitcoinaddressvalidator.cpp b/pool/shard007/C++/0094762_moc_bitcoinaddressvalidator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..401e595ffbd64ee1ab2330c9e47feeacd778065c --- /dev/null +++ b/pool/shard007/C++/0094762_moc_bitcoinaddressvalidator.cpp @@ -0,0 +1,81 @@ +/**************************************************************************** +** Meta object code from reading C++ file 'bitcoinaddressvalidator.h' +** +** Created: Tue Oct 29 13:05:59 2013 +** by: The Qt Meta Object Compiler version 63 (Qt 4.8.1) +** +** WARNING! All changes made in this file will be lost! +*****************************************************************************/ + +#include "../src/qt/bitcoinaddressvalidator.h" +#if !defined(Q_MOC_OUTPUT_REVISION) +#error "The header file 'bitcoinaddressvalidator.h' doesn't include <QObject>." +#elif Q_MOC_OUTPUT_REVISION != 63 +#error "This file was generated using the moc from 4.8.1. It" +#error "cannot be used with the include files from this version of Qt." +#error "(The moc has changed too much.)" +#endif + +QT_BEGIN_MOC_NAMESPACE +static const uint qt_meta_data_BitcoinAddressValidator[] = { + + // content: + 6, // revision + 0, // classname + 0, 0, // classinfo + 0, 0, // methods + 0, 0, // properties + 0, 0, // enums/sets + 0, 0, // constructors + 0, // flags + 0, // signalCount + + 0 // eod +}; + +static const char qt_meta_stringdata_BitcoinAddressValidator[] = { + "BitcoinAddressValidator\0" +}; + +void BitcoinAddressValidator::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) +{ + Q_UNUSED(_o); + Q_UNUSED(_id); + Q_UNUSED(_c); + Q_UNUSED(_a); +} + +const QMetaObjectExtraData BitcoinAddressValidator::staticMetaObjectExtraData = { + 0, qt_static_metacall +}; + +const QMetaObject BitcoinAddressValidator::staticMetaObject = { + { &QValidator::staticMetaObject, qt_meta_stringdata_BitcoinAddressValidator, + qt_meta_data_BitcoinAddressValidator, &staticMetaObjectExtraData } +}; + +#ifdef Q_NO_DATA_RELOCATION +const QMetaObject &BitcoinAddressValidator::getStaticMetaObject() { return staticMetaObject; } +#endif //Q_NO_DATA_RELOCATION + +const QMetaObject *BitcoinAddressValidator::metaObject() const +{ + return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; +} + +void *BitcoinAddressValidator::qt_metacast(const char *_clname) +{ + if (!_clname) return 0; + if (!strcmp(_clname, qt_meta_stringdata_BitcoinAddressValidator)) + return static_cast<void*>(const_cast< BitcoinAddressValidator*>(this)); + return QValidator::qt_metacast(_clname); +} + +int BitcoinAddressValidator::qt_metacall(QMetaObject::Call _c, int _id, void **_a) +{ + _id = QValidator::qt_metacall(_c, _id, _a); + if (_id < 0) + return _id; + return _id; +} +QT_END_MOC_NAMESPACE diff --git a/pool/shard007/C++/0094767_workerthread.cpp b/pool/shard007/C++/0094767_workerthread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..860b8959a35e864dac4ff623df3c964d197928b2 --- /dev/null +++ b/pool/shard007/C++/0094767_workerthread.cpp @@ -0,0 +1,223 @@ + +// +// This source file is part of appleseed. +// Visit http://appleseedhq.net/ for additional information and resources. +// +// This software is released under the MIT license. +// +// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited +// Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +// Interface header. +#include "workerthread.h" + +// appleseed.foundation headers. +#include "foundation/platform/snprintf.h" +#include "foundation/platform/types.h" +#include "foundation/utility/job/ijob.h" +#include "foundation/utility/job/jobmanager.h" +#include "foundation/utility/job/jobqueue.h" +#include "foundation/utility/log.h" + +// Standard headers. +#include <exception> + +using namespace boost; +using namespace std; + +namespace foundation +{ + +// +// WorkerThread class implementation. +// + +WorkerThread::WorkerThread( + const size_t index, + Logger& logger, + JobQueue& job_queue, + const int flags) + : m_index(index) + , m_logger(logger) + , m_job_queue(job_queue) + , m_flags(flags) + , m_thread_func(*this) + , m_thread(nullptr) +{ +} + +WorkerThread::~WorkerThread() +{ + stop(); +} + +void WorkerThread::start() +{ + // Don't do anything if the worker thread is already running. + if (m_thread) + return; + + assert(m_pause_flag.is_clear()); + assert(!m_abort_switch.is_aborted()); + + // Start the thread. + m_thread = new boost::thread(m_thread_func); +} + +void WorkerThread::stop() +{ + // Don't do anything if the worker thread is already stopped. + if (!m_thread) + return; + + // Resume the thread if it was paused. + m_pause_flag.clear(); + m_pause_event.notify_all(); + + // Ask the thread to stop, and wait until it has. + m_abort_switch.abort(); + m_job_queue.signal_event(); + m_thread->join(); + m_abort_switch.clear(); + + // Delete the thread object. + delete m_thread; + m_thread = nullptr; +} + +void WorkerThread::pause() +{ + // Don't do anything if the worker thread is not running. + if (!m_thread) + return; + + boost::mutex::scoped_lock lock(m_pause_mutex); + m_pause_flag.set(); +} + +void WorkerThread::resume() +{ + // Don't do anything if the worker thread is not running. + if (!m_thread) + return; + + boost::mutex::scoped_lock lock(m_pause_mutex); + m_pause_flag.clear(); + m_pause_event.notify_all(); +} + +void WorkerThread::set_thread_name() +{ + char thread_name[16]; + portable_snprintf(thread_name, sizeof(thread_name), "worker_%03lu", (long unsigned int)m_index); + set_current_thread_name(thread_name); +} + +void WorkerThread::run() +{ + set_thread_name(); + + while (!m_abort_switch.is_aborted()) + { + if (m_pause_flag.is_set()) + { + // Wait until the resume event. + boost::mutex::scoped_lock lock(m_pause_mutex); + while (m_pause_flag.is_set()) + m_pause_event.wait(lock); + } + + // Acquire a job. + const JobQueue::RunningJobInfo running_job_info = + m_job_queue.wait_for_scheduled_job(m_abort_switch); + + // Handle the case where the job queue is empty. + if (running_job_info.first.m_job == nullptr) + { + if (m_flags & JobManager::KeepRunningOnEmptyQueue) + { + // Keep the thread running and waiting for new jobs. + continue; + } + else + { + // Terminate the thread. + break; + } + } + + // Execute the job. + const bool success = execute_job(*running_job_info.first.m_job); + + // Retire the job. + m_job_queue.retire_running_job(running_job_info); + + // Handle job execution failures. + if (!success && !(m_flags & JobManager::KeepRunningOnJobFailure)) + { + m_job_queue.clear_scheduled_jobs(); + break; + } + } +} + +bool WorkerThread::execute_job(IJob& job) +{ + try + { + job.execute(m_index); + } + catch (const bad_alloc&) + { + LOG_ERROR( + m_logger, + "worker thread " FMT_SIZE_T ": job was terminated (ran out of memory).", + m_index); + + return false; + } +#ifdef NDEBUG + catch (const std::exception& e) + { + LOG_ERROR( + m_logger, + "worker thread " FMT_SIZE_T ": job was terminated (%s).", + m_index, + e.what()[0] != '\0' ? e.what() : "no details available"); + + return false; + } + catch (...) + { + LOG_ERROR( + m_logger, + "worker thread " FMT_SIZE_T ": job was terminated (unknown exception).", + m_index); + + return false; + } +#endif + + return true; +} + +} // namespace foundation diff --git a/pool/shard007/C++/0094769_proxyClientTcpAcceptor.cc b/pool/shard007/C++/0094769_proxyClientTcpAcceptor.cc new file mode 100644 index 0000000000000000000000000000000000000000..d34df3536c255301d03c7dd2a489d229c94f4000 --- /dev/null +++ b/pool/shard007/C++/0094769_proxyClientTcpAcceptor.cc @@ -0,0 +1,96 @@ +/* +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to <http://unlicense.org> +*/ + +#include "proxyClientTcpAcceptor.h" +#include "proxyClientConn.h" +#include "fdThreadLauncher.h" + +#include <sys/socket.h> +#include <netinet/in.h> +#include <errno.h> +#include <string.h> +#include <stdlib.h> +#include <unistd.h> +#include <iostream> + +using namespace std; + +proxyClientTcpAcceptor :: proxyClientTcpAcceptor(short listenPort, + std::string _proxy, + bool _proxyConnect, + std::string _url) +{ + proxy = _proxy; + proxyConnect = _proxyConnect; + url = _url; + + fd = fdThreadLauncher::makeListeningSocket( listenPort ); + + make_nonblocking(); +} + +/*virtual*/ +proxyClientTcpAcceptor :: ~proxyClientTcpAcceptor(void) +{ + close(fd); +} + +/*virtual*/ +fd_interface::rw_response +proxyClientTcpAcceptor :: read ( fd_mgr * mgr ) +{ + struct sockaddr_in sa; + socklen_t salen; + + salen = sizeof( sa ); + int new_fd = accept4( fd, (struct sockaddr *)&sa, &salen, SOCK_CLOEXEC ); + + if ( new_fd < 0 ) + { + if ( errno != EAGAIN ) + cerr << "accept: " << strerror( errno ) << endl; + return OK; + } + + proxyClientConn * pcc = new proxyClientConn(proxy, url, + proxyConnect, new_fd); + + mgr->register_fd(pcc); + + pcc->startClient(); + + return OK; +} + +/*virtual*/ +void +proxyClientTcpAcceptor :: select_rw ( fd_mgr *mgr, + bool * do_read, bool * do_write ) +{ + *do_read = true; + *do_write = false; +} diff --git a/pool/shard007/C++/0094775_clothes.cpp b/pool/shard007/C++/0094775_clothes.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f39a2a980136896450a6c8be85fa073174f95a5e --- /dev/null +++ b/pool/shard007/C++/0094775_clothes.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2015 LINK/2012 <dma_2012@hotmail.com> + * Licensed under the MIT License, see LICENSE at top level directory. + * + */ +#include <stdinc.hpp> +#include "../data_traits.hpp" +using namespace modloader; + +struct clothes_traits +{ + struct dtraits : modloader::dtraits::OpenFile + { + static const char* what() { return "clothes rules"; } + }; +}; + +using OpenClothesDetour = modloader::OpenFileDetour<0x5A7B54, clothes_traits::dtraits>; + +static auto xinit = initializer([](DataPlugin* plugin_ptr) +{ + if(gvm.IsSA()) + { + auto ReloadClothes = injector::cstd<void()>::call<0x5A7B30>; + plugin_ptr->AddDetour("clothes.dat", reinstall_since_load, OpenClothesDetour(), gdir_refresh(ReloadClothes)); + } +}); + diff --git a/pool/shard007/C++/0094776_GATabControl.cpp b/pool/shard007/C++/0094776_GATabControl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5aaaf50704ac7d60bd37c95f12e8c13599399738 --- /dev/null +++ b/pool/shard007/C++/0094776_GATabControl.cpp @@ -0,0 +1,77 @@ +/* +* This file is part of NWFramework. +* Copyright (c) InCrew Software and Others. +* (See the AUTHORS file in the root of this distribution.) +* +* NWFramework is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation; either version 2 of the License, or +* (at your option) any later version. +* +* NWFramework is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with NWFramework; if not, write to the Free Software +* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + + +#include "PchGUI.h" +#include "GATabControl.h" + +//******************************************************************** +// +//******************************************************************** +//-------------------------------------------------------------------- +// +//-------------------------------------------------------------------- +bool GATabControlString::initAdapter() +{ + mControl->setTabControlEventHandler(this); + return true; +} + +//-------------------------------------------------------------------- +// +//-------------------------------------------------------------------- +void GATabControlString::tabControlModified(::TabControl* _tabControl) +{ + ASSERT(_tabControl == mControl); + Tab* tab = mControl->getActiveTab(); + if ( tab ) + mData.set(tab->getName()); +} + +//-------------------------------------------------------------------- +// +//-------------------------------------------------------------------- +void GATabControlString::update(const char * _contextName, const char * _objName) +{ + std::string val = mData.get(); + Tab* tab = mControl->getTabByName(val.c_str()); + ASSERT(tab); + if ( tab ) + tab->setActive(); +} diff --git a/pool/shard007/C++/0094778_x86_conv.cpp b/pool/shard007/C++/0094778_x86_conv.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f2c4b177991326df24f69a82d0f92a72c44a23c9 --- /dev/null +++ b/pool/shard007/C++/0094778_x86_conv.cpp @@ -0,0 +1,130 @@ +#include "analysis/control_flow_graph.hpp" +#include "analysis/live_variables.hpp" +#include "ir/ir_printer.hpp" +#include "x86_assembler.hpp" +#include "x86_conv.hpp" +#include "utils/headers.hpp" + +#include <list> +#include <iostream> + +namespace +{ + +Ir::Block rewrite_block(SymbolTable &st, const Ir::Block &_block) +{ + + Ir::Block result = _block; + + step("live variables"); + + auto cfg = buildControlFlowGraph(result); + auto lv = LiveVariablesDataFlowAnalysis::analyse(cfg); + LiveVariablesDataFlowAnalysis::dump(std::cerr, cfg, lv); + + auto it = result.begin(); + + std::set<int> visited; + + step("input"); + std::cerr << to_string(result) << "\n"; + + step("transformation"); + + while (it != result.end()) { + if (it->type == Ir::InstructionType::Call and visited.find(it->extra) == visited.end()) { + auto v = it->extra; + auto lv_in = lv.entry[v]; + const auto &fdef = st.getFunction(it->arguments[0]); + visited.insert(v); + + auto orig_it = it; + + std::cerr << "found call: " << to_string(*it) << "\n"; + std::cerr << "live variables at entry: " << LiveVariablesDataFlowAnalysis::to_string(lv.entry.at(v)) << "\n"; + std::string ret; + for (auto r : fdef.modifiedRegs) { + ret += " "; + ret += to_string(r); + } + std::cerr << "function modifies: " << ret << "\n"; + + + bool hasArguments = false; + do { + --it; + hasArguments |= it->type == Ir::InstructionType::Push; + } while (it->type == Ir::InstructionType::Push); + ++it; + + std::list<Ir::Argument> saved; + for (auto r : lv_in) { + if (r.is(Ir::ArgumentType::PinnedHardRegister) and fdef.modifiedRegs.find(r) != fdef.modifiedRegs.end()) { + auto helper = Ir::Instruction{Ir::InstructionType::Push, {r}, 0}; + result.insert(it, helper); + saved.push_front(r); + } + } + + if (saved.size() > 0) { + it = orig_it; + ++it; + + if (hasArguments) ++it; + + for (auto r : saved) { + auto helper = Ir::Instruction{Ir::InstructionType::Pop, {r}, 0}; + result.insert(it, helper); + } + } + + } + + // TODO: temporary remove of Meta instructions CallerSave/CallerRestore + if (it->type == Ir::InstructionType::Meta) { + if (it->arguments[0].content == int(Ir::MetaTag::CallerSave) + or it->arguments[0].content == int(Ir::MetaTag::CallerRestore)) { + it = result.erase(it); + } + } else { + ++it; + } + } + + step("output"); + std::cerr << to_string(result) << "\n"; + + return result; +} + +} // end of anonymous namespace + +std::set<Ir::Argument> getAllGeneralPurposeHardRegisters() +{ + std::set<Ir::Argument> ir; + + for (int i = 0; i < 6; i++) { + ir.insert(Ir::Argument::PinnedHardRegister(i)); + } + + return ir; +} + +void x86_conv(SymbolTable &st) +{ + for (auto &p : st.functionsMap) { + if (p.second.predefined) { + p.second.modifiedRegs = getAllGeneralPurposeHardRegisters(); + } else { + p.second.modifiedRegs = computeModifiedRegisters(p.second.body); + } + } + + for (auto &p : st.functionsMap) { + if (not p.second.predefined) { + subpass("fuction " + p.second.name); + p.second.body = rewrite_block(st, p.second.body); + } + } +} + diff --git a/pool/shard007/C++/0094782_Copy.cpp b/pool/shard007/C++/0094782_Copy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..946230357de1c7bf59c35f9bf5b81dd1f0486015 --- /dev/null +++ b/pool/shard007/C++/0094782_Copy.cpp @@ -0,0 +1,86 @@ +#include "..\..\stdafx.h" + +#include "Copy.hpp" + +#include <intrin.h> +#include "../Types.hpp" + +namespace caspar{ +namespace utils{ +namespace image{ + +CopyFun GetCopyFun(SIMD simd) +{ + if(simd >= SSE2) + return Copy_SSE2; + else + return Copy_REF; +} + +// TODO: (R.N) optimize => prefetch and cacheline loop unroll +void Copy_SSE2(void* dest, const void* source, size_t size) +{ + __m128i val = _mm_setzero_si128(); + __m128i* pD = reinterpret_cast<__m128i*>(dest); + const __m128i* pS = reinterpret_cast<const __m128i*>(source); + + int times = size / 16; + for(int i=0; i < times; ++i) + { + val = _mm_load_si128(pS); + _mm_stream_si128(pD, val); + + ++pD; + ++pS; + } + _mm_mfence(); //ensure last WC buffers get flushed to memory +} + +void Copy_REF(void* dest, const void* source, size_t size) +{ + __movsd(reinterpret_cast<unsigned long*>(dest), reinterpret_cast<const unsigned long*>(source), size/4); +} + +CopyFieldFun GetCopyFieldFun(SIMD simd) +{ + if(simd >= SSE2) + return CopyField_SSE2; + else + return CopyField_REF; +} + +// TODO: (R.N) optimize => prefetch and cacheline loop unroll +void CopyField_SSE2(unsigned char* pDest, unsigned char* pSrc, size_t fieldIndex, size_t width, size_t height) +{ + for(int rowIndex=fieldIndex; rowIndex < height; rowIndex+=2) + { + int offset = width*4*rowIndex; + + __m128i val = _mm_setzero_si128(); + __m128i* pD = reinterpret_cast<__m128i*>(&(pDest[offset])); + const __m128i* pS = reinterpret_cast<const __m128i*>(&(pSrc[offset])); + + int times = width / 4; + for(int i=0; i < times; ++i) + { + val = _mm_load_si128(pS); + _mm_stream_si128(pD, val); + + ++pD; + ++pS; + } + } +} + +void CopyField_REF(unsigned char* pDest, unsigned char* pSrc, size_t fieldIndex, size_t width, size_t height) +{ + for(int rowIndex=fieldIndex; rowIndex < height; rowIndex+=2) + { + int offset = width*4*rowIndex; + __movsd(reinterpret_cast<unsigned long*>(&(pDest[offset])), reinterpret_cast<const unsigned long*>(&(pSrc[offset])), width); + } +} + +} +} +} \ No newline at end of file diff --git a/pool/shard007/C++/0094783_S2PGlobal.cpp b/pool/shard007/C++/0094783_S2PGlobal.cpp new file mode 100644 index 0000000000000000000000000000000000000000..280d50c7d4cee5efdaf93fc4f71420fa8c469aab --- /dev/null +++ b/pool/shard007/C++/0094783_S2PGlobal.cpp @@ -0,0 +1,125 @@ +/*---------------------------------------------------------------------------- +* spp2pgs - Generates BluRay PG Stream from Subtitles or AviSynth scripts +* by Giton Xu <adm@subelf.net> +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see <http://www.gnu.org/licenses/>. +*----------------------------------------------------------------------------*/ + +#include "pch.h" +#include "S2PGlobal.h" + +#include <Shlwapi.h> +#include "Win32StreamEx.h" + +namespace spp2pgs +{ + using namespace std; + + std::unique_ptr<StreamEx> OpenTempFile(TCHAR const *path, unsigned __int64 requireFreeSpace) + { + TCHAR tempPathBuffer[MAX_PATH]; + TCHAR tempFname[MAX_PATH]; + DWORD result = ::GetTempPath(MAX_PATH, tempPathBuffer); + + auto const &tempPath = ::PathIsDirectory(path) ? path : tempPathBuffer; + + if (!result) + { + throw TempOutputException(TempOutputExceptionType::FetchTempOutputPathFailed, result); + } + + ULARGE_INTEGER freeSpace; + result = ::GetDiskFreeSpaceEx(tempPath, &freeSpace, nullptr, nullptr); + + if (!result) + { + throw TempOutputException(TempOutputExceptionType::QueryFreeSpaceFailed, result); + } + + if (requireFreeSpace) + { + if (freeSpace.QuadPart < requireFreeSpace) + { + throw TempOutputException(TempOutputExceptionType::NotEnoughFreeSpace, result); + } + } + + result = ::GetTempFileName(tempPath, _T("a2p"), 0, tempFname); + if (!result) + { + throw TempOutputException(TempOutputExceptionType::FetchTempFileNameFailed, result); + } + + HANDLE tempFile = ::CreateFile( + tempFname, + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ, + NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, + NULL + ); + if (tempFile == INVALID_HANDLE_VALUE) + { + throw TempOutputException(TempOutputExceptionType::TempFileCreateFailed, result); + } + + return unique_ptr<StreamEx>(new Win32StreamEx(tempFile, true, true, true, nullptr)); + } + + unsigned __int64 ReadBE(unsigned __int8 const * buffer, int index, unsigned __int8 length) + { + int tByteIndex = (index >> 3); + int tShift = (length + index - (tByteIndex << 3)); + unsigned __int64 tMaskAll = -1; + tMaskAll = ~(tMaskAll << length); + + unsigned __int64 tRet = 0; + + while ((tShift -= 8) >= 0) + { + unsigned __int64 tByte = buffer[tByteIndex++]; + tRet |= (tByte << tShift); + } + + tRet |= (buffer[tByteIndex++] >> -tShift); + return tRet & tMaskAll; + } + + void WriteBE(unsigned __int8 * buffer, int index, unsigned __int8 length, unsigned __int64 value) + { + int tByteIndex = (index >> 3); + int tShift = (length + index - (tByteIndex << 3)); + unsigned __int64 tMaskAll = -1; + tMaskAll = ~(tMaskAll << length); + + unsigned __int8 tMask = 0; + unsigned __int64 tValue = value & tMaskAll; + + while ((tShift -= 8) >= 0) + { + tMask = static_cast<unsigned __int8>(tMaskAll >> tShift); + buffer[tByteIndex] &= ~tMask; + buffer[tByteIndex] |= (tValue >> tShift); + + tByteIndex++; + } + + tMask = static_cast<unsigned __int8>(tMaskAll << -tShift); + buffer[tByteIndex] &= ~tMask; + buffer[tByteIndex] |= (tValue << -tShift); + } + + +} \ No newline at end of file diff --git a/pool/shard007/C++/0094785_tabxcl.cpp b/pool/shard007/C++/0094785_tabxcl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d354f556ca1da063ccbad2bb1c70d8f237a37548 --- /dev/null +++ b/pool/shard007/C++/0094785_tabxcl.cpp @@ -0,0 +1,298 @@ +/************* TabXcl CPP Declares Source Code File (.CPP) *************/ +/* Name: TABXCL.CPP Version 1.0 */ +/* */ +/* (C) Copyright to the author Olivier BERTRAND 2013-2017 */ +/* */ +/* XCOL: Table having one column containing several values */ +/* comma separated. When creating the table, the name of the X */ +/* column is given by the Name option. */ +/* This first version has one limitation: */ +/* - The X column has the same length than in the physical file. */ +/* This tables produces as many rows for a physical row than the */ +/* number of items in the X column (eventually 0). */ +/***********************************************************************/ + +/***********************************************************************/ +/* Include relevant section of system dependant header files. */ +/***********************************************************************/ +#include "my_global.h" +#include "table.h" // MySQL table definitions +#if defined(_WIN32) +#include <stdlib.h> +#include <stdio.h> +#if defined(__BORLANDC__) +#define __MFC_COMPAT__ // To define min/max as macro +#endif +//#include <windows.h> +#else +#if defined(UNIX) +#include <fnmatch.h> +#include <errno.h> +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include "osutil.h" +#else +//#include <io.h> +#endif +//#include <fcntl.h> +#endif + +/***********************************************************************/ +/* Include application header files: */ +/***********************************************************************/ +#include "global.h" +#include "plgdbsem.h" +#include "plgcnx.h" // For DB types +#include "resource.h" +#include "xtable.h" +#include "tabext.h" +#include "filamtxt.h" +#include "tabdos.h" +#include "tabcol.h" +#include "tabxcl.h" +#include "tabmysql.h" +#include "ha_connect.h" + +/* -------------- Implementation of the XCOL classes ---------------- */ + +/***********************************************************************/ +/* XCLDEF constructor. */ +/***********************************************************************/ +XCLDEF::XCLDEF(void) + { + Xcol = NULL; + Sep = ','; + Mult = 10; +} // end of XCLDEF constructor + +/***********************************************************************/ +/* DefineAM: define specific AM block values from XCOL table. */ +/***********************************************************************/ +bool XCLDEF::DefineAM(PGLOBAL g, LPCSTR am, int poff) + { + char buf[8]; + + Xcol = GetStringCatInfo(g, "Colname", ""); + GetCharCatInfo("Separator", ",", buf, sizeof(buf)); + Sep = (strlen(buf) == 2 && buf[0] == '\\' && buf[1] == 't') ? '\t' : *buf; + Mult = GetIntCatInfo("Mult", 10); + return PRXDEF::DefineAM(g, am, poff); + } // end of DefineAM + +/***********************************************************************/ +/* GetTable: makes a new TDB of the proper type. */ +/***********************************************************************/ +PTDB XCLDEF::GetTable(PGLOBAL g, MODE) + { + if (Catfunc == FNC_COL) + return new(g) TDBTBC(this); + else + return new(g) TDBXCL(this); + + } // end of GetTable + +/* ------------------------------------------------------------------- */ + +/***********************************************************************/ +/* Implementation of the TDBXCL class. */ +/***********************************************************************/ +TDBXCL::TDBXCL(PXCLDEF tdp) : TDBPRX(tdp) + { + Xcolumn = tdp->Xcol; // CSV column name + Xcolp = NULL; // To the XCLCOL column + Mult = tdp->Mult; // Multiplication factor + N = 0; // The current table index + M = 0; // The occurrence rank + RowFlag = 0; // 0: Ok, 1: Same, 2: Skip + New = TRUE; // TRUE for new line + Sep = tdp->Sep; // The Xcol separator + } // end of TDBXCL constructor + +/***********************************************************************/ +/* Allocate XCL column description block. */ +/***********************************************************************/ +PCOL TDBXCL::MakeCol(PGLOBAL g, PCOLDEF cdp, PCOL cprec, int n) + { + PCOL colp; + + if (!stricmp(cdp->GetName(), Xcolumn)) { + Xcolp = new(g) XCLCOL(cdp, this, cprec, n); + colp = Xcolp; + } else + colp = new(g) PRXCOL(cdp, this, cprec, n); + + return colp; + } // end of MakeCol + +/***********************************************************************/ +/* XCL GetMaxSize: returns the maximum number of rows in the table. */ +/***********************************************************************/ +int TDBXCL::GetMaxSize(PGLOBAL g) + { + if (MaxSize < 0) { + if (InitTable(g)) + return 0; + + MaxSize = Mult * Tdbp->GetMaxSize(g); + } // endif MaxSize + + return MaxSize; + } // end of GetMaxSize + +/***********************************************************************/ +/* For this table type, ROWID is the (virtual) row number, */ +/* while ROWNUM is be the occurrence rank in the multiple column. */ +/***********************************************************************/ +int TDBXCL::RowNumber(PGLOBAL, bool b) + { + return (b) ? M : N; + } // end of RowNumber + +/***********************************************************************/ +/* XCL Access Method opening routine. */ +/***********************************************************************/ +bool TDBXCL::OpenDB(PGLOBAL g) + { + if (Use == USE_OPEN) { + /*******************************************************************/ + /* Table already open, just replace it at its beginning. */ + /*******************************************************************/ + M = N = 0; + RowFlag = 0; + New = TRUE; + return Tdbp->OpenDB(g); + } // endif use + + if (Mode != MODE_READ) { + /*******************************************************************/ + /* Currently XCOL tables cannot be modified. */ + /*******************************************************************/ + strcpy(g->Message, "XCOL tables are read only"); + return TRUE; + } // endif Mode + + if (InitTable(g)) + return TRUE; + + /*********************************************************************/ + /* Check and initialize the subtable columns. */ + /*********************************************************************/ + for (PCOL cp = Columns; cp; cp = cp->GetNext()) + if (!cp->IsSpecial()) + if (((PPRXCOL)cp)->Init(g, NULL)) + return TRUE; + + /*********************************************************************/ + /* Physically open the object table. */ + /*********************************************************************/ + if (Tdbp->OpenDB(g)) + return TRUE; + + Use = USE_OPEN; + return FALSE; + } // end of OpenDB + +/***********************************************************************/ +/* Data Base read routine for XCL access method. */ +/***********************************************************************/ +int TDBXCL::ReadDB(PGLOBAL g) + { + int rc = RC_OK; + + /*********************************************************************/ + /* Now start the multi reading process. */ + /*********************************************************************/ + do { + if (RowFlag != 1) { + if ((rc = Tdbp->ReadDB(g)) != RC_OK) + break; + + New = TRUE; + M = 1; + } else { + New = FALSE; + M++; + } // endif RowFlag + + if (Xcolp) { + RowFlag = 0; + Xcolp->ReadColumn(g); + } // endif Xcolp + + N++; + } while (RowFlag == 2); + + return rc; + } // end of ReadDB + + +// ------------------------ XCLCOL functions ---------------------------- + +/***********************************************************************/ +/* XCLCOL public constructor. */ +/***********************************************************************/ +XCLCOL::XCLCOL(PCOLDEF cdp, PTDB tdbp, PCOL cprec, int i) + : PRXCOL(cdp, tdbp, cprec, i, "XCL") + { + // Set additional XXL access method information for column. + Cbuf = NULL; // Will be allocated later + Cp = NULL; // Pointer to current position in Cbuf + Sep = ((PTDBXCL)tdbp)->Sep; + AddStatus(BUF_READ); // Only evaluated from TDBXCL::ReadDB + } // end of XCLCOL constructor + +/***********************************************************************/ +/* XCLCOL initialization routine. */ +/* Allocate Cbuf that will contain the Colp value. */ +/***********************************************************************/ +bool XCLCOL::Init(PGLOBAL g, PTDB tp) + { + if (PRXCOL::Init(g, tp)) + return true; + + Cbuf = (char*)PlugSubAlloc(g, NULL, Colp->GetLength() + 1); + return false; + } // end of Init + +/***********************************************************************/ +/* What this routine does is to get the comma-separated string */ +/* from the source table column, extract the single values and */ +/* set the flag for the table ReadDB function. */ +/***********************************************************************/ +void XCLCOL::ReadColumn(PGLOBAL g) + { + if (((PTDBXCL)To_Tdb)->New) { + Colp->Reset(); // Moved here in case of failed filtering + Colp->Eval(g); + strncpy(Cbuf, To_Val->GetCharValue(), Colp->GetLength()); + Cbuf[Colp->GetLength()] = 0; + Cp = Cbuf; + } // endif New + + if (*Cp) { + PSZ p; + + // Trim left + for (p = Cp; *p == ' '; p++) + ; + + if ((Cp = strchr(Cp, Sep))) + // Separator is found + *Cp++ = '\0'; + + Value->SetValue_psz(p); + } else if (Nullable) { + Value->Reset(); + Value->SetNull(true); + } else { + // Skip that row + ((PTDBXCL)To_Tdb)->RowFlag = 2; + Colp->Reset(); + } // endif Cp + + if (Cp && *Cp) + // More to come from the same row + ((PTDBXCL)To_Tdb)->RowFlag = 1; + + } // end of ReadColumn diff --git a/pool/shard007/C++/0094790_audioinput-gmconf-bridge.cpp b/pool/shard007/C++/0094790_audioinput-gmconf-bridge.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cc617414882e867c7f2338362d1b9afea3704ec6 --- /dev/null +++ b/pool/shard007/C++/0094790_audioinput-gmconf-bridge.cpp @@ -0,0 +1,85 @@ + +/* + * Ekiga -- A VoIP and Video-Conferencing application + * Copyright (C) 2000-2009 Damien Sandras <dsandras@seconix.com> + + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or (at + * your option) any later version. This program is distributed in the hope + * that it will be useful, but WITHOUT ANY WARRANTY; without even the + * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + * Ekiga is licensed under the GPL license and as a special exception, you + * have permission to link or otherwise combine this program with the + * programs OPAL, OpenH323 and PWLIB, and distribute the combination, without + * applying the requirements of the GNU GPL to the OPAL, OpenH323 and PWLIB + * programs, as long as you do follow the requirements of the GNU GPL for all + * the rest of the software thus combined. + */ + + +/* + * audioinput-gmconf-bridge.cpp - description + * ------------------------------------------ + * begin : written in 2008 by Matthias Schneider + * copyright : (c) 2008 by Matthias Schneider + * description : Declaration of the bridge between the gmconf + * and the audioinput-core.. + * + */ + +#include "config.h" + +#include "audioinput-gmconf-bridge.h" +#include "audioinput-core.h" + +#define AUDIO_DEVICES_KEY "/apps/" PACKAGE_NAME "/devices/audio/" +#define AUDIO_CODECS_KEY "/apps/" PACKAGE_NAME "/codecs/audio/" + +using namespace Ekiga; + +AudioInputCoreConfBridge::AudioInputCoreConfBridge (Ekiga::Service & _service) + : Ekiga::ConfBridge (_service) +{ + Ekiga::ConfKeys keys; + property_changed.connect (sigc::mem_fun (this, &AudioInputCoreConfBridge::on_property_changed)); + + keys.push_back (AUDIO_DEVICES_KEY "input_device"); + load (keys); +} + +void AudioInputCoreConfBridge::on_property_changed (std::string key, GmConfEntry *entry) +{ + AudioInputCore & audioinput_core = (AudioInputCore &) service; + + if (key == AUDIO_DEVICES_KEY "input_device") { + + PTRACE(4, "AudioInputCoreConfBridge\tUpdating device"); + + AudioInputDevice device; + if (gm_conf_entry_get_string (entry) == NULL) { + PTRACE(1, "AudioInputCoreConfBridge\t" << AUDIO_DEVICES_KEY "input_device" << " is NULL"); + } + else { + device.SetFromString(gm_conf_entry_get_string (entry)); + } + + if ( (device.type == "" ) || + (device.source == "") || + (device.name == "" ) ) { + PTRACE(1, "AudioInputCore\tTried to set malformed device"); + device.type = AUDIO_INPUT_FALLBACK_DEVICE_TYPE; + device.source = AUDIO_INPUT_FALLBACK_DEVICE_SOURCE; + device.name = AUDIO_INPUT_FALLBACK_DEVICE_NAME; + } + + audioinput_core.set_device (device); + } +} + diff --git a/pool/shard007/C++/0094791_7.cpp b/pool/shard007/C++/0094791_7.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f3312cd48aba658f8d6b552efc56937eadf26cf5 --- /dev/null +++ b/pool/shard007/C++/0094791_7.cpp @@ -0,0 +1,69 @@ +#include <iostream> +#include <stack> +#include <fstream> +#include <sstream> +#include <string> + +bool isop(char p) { + + return (p == "+" || p == "*" || p == "/"); +} + +char math(int a, int b, char c) { + + switch(c): + case "+": + return a + b; + break; + case "*": + return a * b; + break; + case "/": + return b / a; + break; +} + +int main(int argc, char** argv){ + + ifstream file; + file.open(argv[1]); + + stack<char> data; + + char input; + + string line; + + while(file.good()){ + + getline(file, line); + istringstream iss(line); + + int balance; + + while (iss >> input) { + + if (isop) + balance = 2; + else + balance -= 1; + data.push(input); + + while (balance == 0 && !data.empty()) { + int a = data.top() - '0'; + data.pop(); + int b = data.top() - '0'; + data.pop(); + char c = data.top(); + data.pop(); + + + + if(isop(data.top()) || data.empty()) + balance = 1; + } + } + + } + +} diff --git a/pool/shard007/C++/0094794_Level0.cpp b/pool/shard007/C++/0094794_Level0.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1e591eb2cf50217a15af7b0596e159acc855694f --- /dev/null +++ b/pool/shard007/C++/0094794_Level0.cpp @@ -0,0 +1,173 @@ +/* + * Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/> + * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "Common.h" +#include "DatabaseEnv.h" +#include "World.h" +#include "Player.h" +#include "Opcodes.h" +#include "Chat.h" +#include "ObjectAccessor.h" +#include "Language.h" +#include "AccountMgr.h" +#include "SystemConfig.h" +#include "revision.h" +#include "Util.h" + +bool ChatHandler::HandleHelpCommand(const char* args) +{ + char* cmd = strtok((char*)args, " "); + if (!cmd) + { + ShowHelpForCommand(getCommandTable(), "help"); + ShowHelpForCommand(getCommandTable(), ""); + } + else + { + if (!ShowHelpForCommand(getCommandTable(), cmd)) + SendSysMessage(LANG_NO_HELP_CMD); + } + + return true; +} + +bool ChatHandler::HandleCommandsCommand(const char* /*args*/) +{ + ShowHelpForCommand(getCommandTable(), ""); + return true; +} + +bool ChatHandler::HandleStartCommand(const char* /*args*/) +{ + Player *chr = m_session->GetPlayer(); + + /* Partimos por revisar la clase (esto solo afecta a los DK*/ + if(chr->getClass() == CLASS_DEATH_KNIGHT) + { + //Comprueba las tres quest donde siempre se bugean y usan el comando + if(chr->GetQuestStatus(12801) == QUEST_STATUS_INCOMPLETE || chr->GetQuestStatus(13165) == QUEST_STATUS_INCOMPLETE ) + { + SendSysMessage(LANG_YOURS_SECURITY_IS_LOW); + SetSentErrorMessage(true); + return false; + } + + //Comprueba la spell "Portón de la muerte" http://es.wowhead.com/spell=50977/ + if(!chr->HasSpell(50977)) + { + SendSysMessage(LANG_YOURS_SECURITY_IS_LOW); + SetSentErrorMessage(true); + return false; + } + } + + if (chr->isInFlight()) + { + SendSysMessage(LANG_YOU_IN_FLIGHT); + SetSentErrorMessage(true); + return false; + } + + if (chr->isInCombat()) + { + SendSysMessage(LANG_YOU_IN_COMBAT); + SetSentErrorMessage(true); + return false; + } + + if ((chr->isDead()) || (chr->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))) + { + // if player is dead and stuck, send ghost to graveyard + chr->RepopAtGraveyard(); + return true; + } + + // cast spell Stuck + chr->CastSpell(chr, 7355, false); + return true; +} + +bool ChatHandler::HandleServerInfoCommand(const char* /*args*/) +{ + uint32 PlayersNum = sWorld->GetPlayerCount(); + uint32 MaxPlayersNum = sWorld->GetMaxPlayerCount(); + uint32 activeClientsNum = sWorld->GetActiveSessionCount(); + uint32 queuedClientsNum = sWorld->GetQueuedSessionCount(); + uint32 maxActiveClientsNum = sWorld->GetMaxActiveSessionCount(); + uint32 maxQueuedClientsNum = sWorld->GetMaxQueuedSessionCount(); + std::string uptime = secsToTimeString(sWorld->GetUptime()); + uint32 updateTime = sWorld->GetUpdateTime(); + + PSendSysMessage(_FULLVERSION); + PSendSysMessage(LANG_CONNECTED_PLAYERS, PlayersNum, MaxPlayersNum); + PSendSysMessage(LANG_CONNECTED_USERS, activeClientsNum, maxActiveClientsNum, queuedClientsNum, maxQueuedClientsNum); + PSendSysMessage(LANG_UPTIME, uptime.c_str()); + PSendSysMessage("Update time diff: %u.", updateTime); + + return true; +} + +bool ChatHandler::HandleDismountCommand(const char* /*args*/) +{ + //If player is not mounted, so go out :) + if (!m_session->GetPlayer()->IsMounted()) + { + SendSysMessage(LANG_CHAR_NON_MOUNTED); + SetSentErrorMessage(true); + return false; + } + + if (m_session->GetPlayer()->isInFlight()) + { + SendSysMessage(LANG_YOU_IN_FLIGHT); + SetSentErrorMessage(true); + return false; + } + + m_session->GetPlayer()->Unmount(); + m_session->GetPlayer()->RemoveAurasByType(SPELL_AURA_MOUNTED); + return true; +} + +bool ChatHandler::HandleSaveCommand(const char* /*args*/) +{ + Player *player = m_session->GetPlayer(); + + // save GM account without delay and output message + if (m_session->GetSecurity() > SEC_PLAYER) + { + player->SaveToDB(); + SendSysMessage(LANG_PLAYER_SAVED); + return true; + } + + // save if the player has last been saved over 20 seconds ago + uint32 save_interval = sWorld->getIntConfig(CONFIG_INTERVAL_SAVE); + if (save_interval == 0 || (save_interval > 20*IN_MILLISECONDS && player->GetSaveTimer() <= save_interval - 20*IN_MILLISECONDS)) + player->SaveToDB(); + + return true; +} + +/// Display the 'Message of the day' for the realm +bool ChatHandler::HandleServerMotdCommand(const char* /*args*/) +{ + PSendSysMessage(LANG_MOTD_CURRENT, sWorld->GetMotd()); + return true; +} + diff --git a/pool/shard007/C++/0094795_complex_vector_22.cc b/pool/shard007/C++/0094795_complex_vector_22.cc new file mode 100644 index 0000000000000000000000000000000000000000..5022b4478e5837c61a76db94f6808288fa41c1e3 --- /dev/null +++ b/pool/shard007/C++/0094795_complex_vector_22.cc @@ -0,0 +1,81 @@ +// --------------------------------------------------------------------- +// +// Copyright (C) 2004 - 2017 by the deal.II authors +// +// This file is part of the deal.II library. +// +// The deal.II library is free software; you can use it, redistribute +// it, and/or modify it under the terms of the GNU Lesser General +// Public License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// The full text of the license can be found in the file LICENSE at +// the top level of the deal.II distribution. +// +// --------------------------------------------------------------------- + + + +// check Vector<std::complex<double> >::operator*(Vector) on two vectors that are +// orthogonal + +#include "../tests.h" +#include <deal.II/lac/vector.h> +#include <vector> + + +void test (Vector<std::complex<double> > &v, + Vector<std::complex<double> > &w) +{ + // set only certain elements of each + // vector, but disjoint sets of elements + for (unsigned int i=0; i<v.size(); ++i) + if (i%3 == 0) + v(i) = std::complex<double> (i+1., i+2.); + else + w(i) = std::complex<double> (i+1., i+2.); + v.compress (); + w.compress (); + + // make sure the scalar product is zero + AssertThrow (v*w == std::complex<double>(0), ExcInternalError()); + + deallog << "OK" << std::endl; +} + + + +int main () +{ + initlog(); + + try + { + Vector<std::complex<double> > v (100); + Vector<std::complex<double> > w (100); + test (v,w); + } + catch (std::exception &exc) + { + deallog << std::endl << std::endl + << "----------------------------------------------------" + << std::endl; + deallog << "Exception on processing: " << std::endl + << exc.what() << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + + return 1; + } + catch (...) + { + deallog << std::endl << std::endl + << "----------------------------------------------------" + << std::endl; + deallog << "Unknown exception!" << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + }; +} diff --git a/pool/shard007/C++/0094801_local_device_info_provider_impl.cc b/pool/shard007/C++/0094801_local_device_info_provider_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..bc8e14a35801d58a6ee7376250d0ab0433f57f28 --- /dev/null +++ b/pool/shard007/C++/0094801_local_device_info_provider_impl.cc @@ -0,0 +1,154 @@ +// 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 "base/bind.h" +#include "chrome/browser/sync/glue/local_device_info_provider_impl.h" +#include "chrome/common/chrome_version_info.h" +#include "content/public/browser/browser_thread.h" +#include "sync/util/get_session_name.h" +#include "ui/base/device_form_factor.h" + +namespace browser_sync { + +namespace { + +// Converts VersionInfo::Channel to string for user-agent string. +std::string ChannelToString(chrome::VersionInfo::Channel channel) { + switch (channel) { + case chrome::VersionInfo::CHANNEL_UNKNOWN: + return "unknown"; + case chrome::VersionInfo::CHANNEL_CANARY: + return "canary"; + case chrome::VersionInfo::CHANNEL_DEV: + return "dev"; + case chrome::VersionInfo::CHANNEL_BETA: + return "beta"; + case chrome::VersionInfo::CHANNEL_STABLE: + return "stable"; + default: + NOTREACHED(); + return "unknown"; + } +} + +#if defined(OS_ANDROID) +bool IsTabletUI() { + return ui::GetDeviceFormFactor() == ui::DEVICE_FORM_FACTOR_TABLET; +} +#endif + +sync_pb::SyncEnums::DeviceType GetLocalDeviceType() { +#if defined(OS_CHROMEOS) + return sync_pb::SyncEnums_DeviceType_TYPE_CROS; +#elif defined(OS_LINUX) + return sync_pb::SyncEnums_DeviceType_TYPE_LINUX; +#elif defined(OS_MACOSX) + return sync_pb::SyncEnums_DeviceType_TYPE_MAC; +#elif defined(OS_WIN) + return sync_pb::SyncEnums_DeviceType_TYPE_WIN; +#elif defined(OS_ANDROID) + return IsTabletUI() ? sync_pb::SyncEnums_DeviceType_TYPE_TABLET + : sync_pb::SyncEnums_DeviceType_TYPE_PHONE; +#else + return sync_pb::SyncEnums_DeviceType_TYPE_OTHER; +#endif +} + +} // namespace + +LocalDeviceInfoProviderImpl::LocalDeviceInfoProviderImpl() + : weak_factory_(this) { +} + +LocalDeviceInfoProviderImpl::~LocalDeviceInfoProviderImpl() { +} + +// static. +std::string LocalDeviceInfoProviderImpl::MakeUserAgentForSyncApi( + const chrome::VersionInfo& version_info) { + std::string user_agent; + user_agent = "Chrome "; +#if defined(OS_WIN) + user_agent += "WIN "; +#elif defined(OS_CHROMEOS) + user_agent += "CROS "; +#elif defined(OS_ANDROID) + if (IsTabletUI()) + user_agent += "ANDROID-TABLET "; + else + user_agent += "ANDROID-PHONE "; +#elif defined(OS_LINUX) + user_agent += "LINUX "; +#elif defined(OS_FREEBSD) + user_agent += "FREEBSD "; +#elif defined(OS_OPENBSD) + user_agent += "OPENBSD "; +#elif defined(OS_MACOSX) + user_agent += "MAC "; +#endif + if (!version_info.is_valid()) { + DLOG(ERROR) << "Unable to create chrome::VersionInfo object"; + return user_agent; + } + + user_agent += version_info.Version(); + user_agent += " (" + version_info.LastChange() + ")"; + if (!version_info.IsOfficialBuild()) { + user_agent += "-devel"; + } else { + user_agent += + " channel(" + ChannelToString(version_info.GetChannel()) + ")"; + } + + return user_agent; +} + +const sync_driver::DeviceInfo* +LocalDeviceInfoProviderImpl::GetLocalDeviceInfo() const { + return local_device_info_.get(); +} + +std::string LocalDeviceInfoProviderImpl::GetLocalSyncCacheGUID() const { + return cache_guid_; +} + +scoped_ptr<sync_driver::LocalDeviceInfoProvider::Subscription> +LocalDeviceInfoProviderImpl::RegisterOnInitializedCallback( + const base::Closure& callback) { + DCHECK(!local_device_info_.get()); + return callback_list_.Add(callback); +} + +void LocalDeviceInfoProviderImpl::Initialize( + const std::string& cache_guid, const std::string& signin_scoped_device_id) { + DCHECK(!cache_guid.empty()); + cache_guid_ = cache_guid; + + syncer::GetSessionName( + content::BrowserThread::GetBlockingPool(), + base::Bind(&LocalDeviceInfoProviderImpl::InitializeContinuation, + weak_factory_.GetWeakPtr(), + cache_guid, + signin_scoped_device_id)); +} + +void LocalDeviceInfoProviderImpl::InitializeContinuation( + const std::string& guid, + const std::string& signin_scoped_device_id, + const std::string& session_name) { + chrome::VersionInfo version_info; + + local_device_info_.reset( + new sync_driver::DeviceInfo(guid, + session_name, + version_info.CreateVersionString(), + MakeUserAgentForSyncApi(version_info), + GetLocalDeviceType(), + signin_scoped_device_id)); + + // Notify observers. + callback_list_.Notify(); +} + +} // namespace browser_sync diff --git a/pool/shard007/C++/0094806_window_test_gtk.cc b/pool/shard007/C++/0094806_window_test_gtk.cc new file mode 100644 index 0000000000000000000000000000000000000000..3ebebab7cdd22f3b97ecfc5073cd1b7ae96f833f --- /dev/null +++ b/pool/shard007/C++/0094806_window_test_gtk.cc @@ -0,0 +1,81 @@ +// Copyright (c) 2013 The Chromium Embedded Framework 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 "appshell/browser/window_test.h" + +#include <gtk/gtk.h> + +#include "appshell/browser/root_window.h" + +namespace client { +namespace window_test { + +namespace { + +GtkWindow* GetWindow(CefRefPtr<CefBrowser> browser) { + scoped_refptr<RootWindow> root_window = + RootWindow::GetForBrowser(browser->GetIdentifier()); + if (root_window.get()) + return GTK_WINDOW(root_window->GetWindowHandle()); + return NULL; +} + +bool IsMaximized(GtkWindow* window) { + GdkWindow* gdk_window = gtk_widget_get_window(GTK_WIDGET(window)); + gint state = gdk_window_get_state(gdk_window); + return (state & GDK_WINDOW_STATE_MAXIMIZED) ? true : false; +} + +} // namespace + +void SetPos(CefRefPtr<CefBrowser> browser, int x, int y, int width, + int height) { + GtkWindow* window = GetWindow(browser); + GdkWindow* gdk_window = gtk_widget_get_window(GTK_WIDGET(window)); + + // Make sure the window isn't minimized or maximized. + if (IsMaximized(window)) + gtk_window_unmaximize(window); + else + gtk_window_present(window); + + // Retrieve information about the display that contains the window. + GdkScreen* screen = gdk_screen_get_default(); + gint monitor = gdk_screen_get_monitor_at_window(screen, gdk_window); + GdkRectangle rect; + gdk_screen_get_monitor_geometry(screen, monitor, &rect); + + // Make sure the window is inside the display. + CefRect display_rect(rect.x, rect.y, rect.width, rect.height); + CefRect window_rect(x, y, width, height); + ModifyBounds(display_rect, window_rect); + + gdk_window_move_resize(gdk_window, window_rect.x, window_rect.y, + window_rect.width, window_rect.height); +} + +void Minimize(CefRefPtr<CefBrowser> browser) { + GtkWindow* window = GetWindow(browser); + + // Unmaximize the window before minimizing so restore behaves correctly. + if (IsMaximized(window)) + gtk_window_unmaximize(window); + + gtk_window_iconify(window); +} + +void Maximize(CefRefPtr<CefBrowser> browser) { + gtk_window_maximize(GetWindow(browser)); +} + +void Restore(CefRefPtr<CefBrowser> browser) { + GtkWindow* window = GetWindow(browser); + if (IsMaximized(window)) + gtk_window_unmaximize(window); + else + gtk_window_present(window); +} + +} // namespace window_test +} // namespace client diff --git a/pool/shard007/C++/0094810_pop_heap.pass.cpp b/pool/shard007/C++/0094810_pop_heap.pass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..823985df6ca0dab7c94e0975f6a41493f4926270 --- /dev/null +++ b/pool/shard007/C++/0094810_pop_heap.pass.cpp @@ -0,0 +1,39 @@ +//===----------------------------------------------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is dual licensed under the MIT and the University of Illinois Open +// Source Licenses. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +// <algorithm> + +// template<RandomAccessIterator Iter> +// requires ShuffleIterator<Iter> && LessThanComparable<Iter::value_type> +// void +// pop_heap(Iter first, Iter last); + +#include <algorithm> +#include <cassert> + +void test(unsigned N) +{ + int* ia = new int [N]; + for (int i = 0; i < N; ++i) + ia[i] = i; + std::random_shuffle(ia, ia+N); + std::make_heap(ia, ia+N); + for (int i = N; i > 0; --i) + { + std::pop_heap(ia, ia+i); + assert(std::is_heap(ia, ia+i-1)); + } + std::pop_heap(ia, ia); + delete [] ia; +} + +int main() +{ + test(1000); +} diff --git a/pool/shard007/C++/0094811_screen_resolution.cc b/pool/shard007/C++/0094811_screen_resolution.cc new file mode 100644 index 0000000000000000000000000000000000000000..db8ff4a90342ff588c7f01bae2bde33b7fe39f38 --- /dev/null +++ b/pool/shard007/C++/0094811_screen_resolution.cc @@ -0,0 +1,50 @@ +// 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 "remoting/host/base/screen_resolution.h" + +#include <stdint.h> + +#include <algorithm> +#include <limits> + +#include "base/check_op.h" + +namespace remoting { + +ScreenResolution::ScreenResolution() + : dimensions_(webrtc::DesktopSize(0, 0)), + dpi_(webrtc::DesktopVector(0, 0)) {} + +ScreenResolution::ScreenResolution(const webrtc::DesktopSize& dimensions, + const webrtc::DesktopVector& dpi) + : dimensions_(dimensions), dpi_(dpi) { + // Check that dimensions are not negative. + DCHECK(!dimensions.is_empty() || dimensions.equals(webrtc::DesktopSize())); + DCHECK_GE(dpi.x(), 0); + DCHECK_GE(dpi.y(), 0); +} + +webrtc::DesktopSize ScreenResolution::ScaleDimensionsToDpi( + const webrtc::DesktopVector& new_dpi) const { + int64_t width = dimensions_.width(); + int64_t height = dimensions_.height(); + + // Scale the screen dimensions to new DPI. + width = std::min(width * new_dpi.x() / dpi_.x(), + static_cast<int64_t>(std::numeric_limits<int32_t>::max())); + height = std::min(height * new_dpi.y() / dpi_.y(), + static_cast<int64_t>(std::numeric_limits<int32_t>::max())); + return webrtc::DesktopSize(width, height); +} + +bool ScreenResolution::IsEmpty() const { + return dimensions_.is_empty() || dpi_.is_zero(); +} + +bool ScreenResolution::Equals(const ScreenResolution& other) const { + return dimensions_.equals(other.dimensions()) && dpi_.equals(other.dpi()); +} + +} // namespace remoting diff --git a/pool/shard007/C++/0094812_timezonecombo.cpp b/pool/shard007/C++/0094812_timezonecombo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..51335e830c5a25737b0c55bc19e78eccfc92a8bd --- /dev/null +++ b/pool/shard007/C++/0094812_timezonecombo.cpp @@ -0,0 +1,55 @@ +/* + * timezonecombo.cpp - time zone selection combo box + * Program: kalarm + * Copyright © 2006,2008,2009 by David Jarvie <djarvie@kde.org> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#include "timezonecombo.moc" +#include <ksystemtimezone.h> +#include <kglobal.h> +#include <klocale.h> + + +TimeZoneCombo::TimeZoneCombo(QWidget* parent) + : ComboBox(parent) +{ + KGlobal::locale()->insertCatalog( "timezones4" ); // for time zone translations + QString utc = KTimeZone::utc().name(); + addItem(utc); // put UTC at start of list + mZoneNames << utc; + const KTimeZones::ZoneMap zones = KSystemTimeZones::zones(); + for (KTimeZones::ZoneMap::ConstIterator it = zones.constBegin(); it != zones.constEnd(); ++it) + if (it.key() != utc) + { + mZoneNames << it.key(); + addItem(i18n(it.key().toUtf8()).replace('_', ' ')); + } +} + +KTimeZone TimeZoneCombo::timeZone() const +{ + return KSystemTimeZones::zone(mZoneNames[currentIndex()]); +} + +void TimeZoneCombo::setTimeZone(const KTimeZone& tz) +{ + if (!tz.isValid()) + return; + int index = mZoneNames.indexOf(tz.name()); + if (index >= 0) + setCurrentIndex(index); +} diff --git a/pool/shard007/C++/0094813_functor.cpp b/pool/shard007/C++/0094813_functor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..26a1dc3af8b475522a072f244e6deedd1c6acd51 --- /dev/null +++ b/pool/shard007/C++/0094813_functor.cpp @@ -0,0 +1,331 @@ +/* + * @file $/source/libnparse_script/src/script/joints/functor.cpp + * +This file is a part of the "nParse" project - + a general purpose parsing framework, version 0.1.8 + +The MIT License (MIT) +Copyright (c) 2007-2017 Alex Kudinov <alex.s.kudinov@gmail.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#include <nparse/nparse.hpp> +#include <anta/sas/test.hpp> +#include <anta/sas/symbol.hpp> +#include "../_varname.hpp" +#include "../../tokenizer.hpp" +#include "../_punct.hpp" +#include "_priority.hpp" +#include "../../static.hpp" + +namespace { + +using namespace nparse; + +// The external trace context is referred by a special zero length key which +// shouldn't be used explicitly in semantic actions. +static const IEnvironment::key_type zero = IEnvironment::key_type(); + +// ext = self(); +// push ext; +class PreCond: public IAction +{ +public: + // Overridden from IAction: + + result_type evalVal (IEnvironment& a_env) const + { + // Evaluate initializer expression. + result_type init; + if (m_init) + { + m_init. evalVal(a_env). swap(init); + } + else + { + result_type(a_env. create()). swap(init); + } + + // Get processor reference. + anta::Processor<NLG>& processor = a_env. get_processor(); + + // Get current context without doing any instantiation. + anta::ndl::Context<NLG>* self = processor. get_state(). context(NULL); + + // If the initializer is an array then do context forwarding, + // i.e. substitute initializer array for the current context. + if (init. is_array()) + { + processor. get_state(). substitute(&* init. as_array()); + } + + // Otherwise, check if the initializer can be reduced to the positive + // logical value. + else if (! init. as_boolean()) + { + throw flow_control(false); + } + + // Save previous context in a special variable representing the external + // context. + processor. ref(zero, true) = a_env. create(self); + + // Mark the special variable as pushed. + processor. get_state(). context(&processor) -> push(zero); + + // Return nothing. + return result_type(); + } + +public: + PreCond (const action_pointer& a_init = action_pointer()): + m_init (a_init) + { + } + +private: + action_pointer m_init; + +}; + +// pop ext; +// res = self(ext); +class PostCond: public IAction +{ +public: + // Overridden from IAction: + + result_type evalVal (IEnvironment& a_env) const + { + // First, evaluate and check the post-condition. + if (m_cond && ! m_cond. evalVal(a_env). as_boolean()) + { + throw flow_control(false); + } + + // Get processor reference. + anta::Processor<NLG>& processor = a_env. get_processor(); + + // Get current context, instantiate if it's necessary. + anta::ndl::Context<NLG>* self = + processor. get_state(). context(&processor); + + // Pop the special variable that holds the external context. + self -> pop(zero); + + // Get the value of the special variable (supposed to be array). + result_type val = self -> val(zero); + assert(val. is_array()); + + // Substitute restored external context for the current. + processor. get_state(). substitute(&* val. as_array()); + + // Save previous context as the result in another special variable. + if (! m_alias. empty()) + { + const IEnvironment::key_type key(m_alias); + processor. ref(key, true) = + anta::aux::array<NLG>::type(a_env. create(self)); + } + + // Return nothing. + return result_type(); + } + +public: + PostCond (const string_t& a_alias = string_t(), + const action_pointer& a_cond = action_pointer()): + m_alias (a_alias), m_cond (a_cond) + { + } + +private: + string_t m_alias; + action_pointer m_cond; + +}; + +class Operator: public IOperator +{ +// <LOCAL_PARSER_DATA> + string_t m_alias, m_target; + action_pointer m_pre_cond, m_post_cond; + +// </LOCAL_PARSER_DATA> + + // Defines alias. + bool set_alias (const hnd_arg_t& arg) + { + m_alias = get_accepted_str(arg); + return true; + } + + // Defines no-alias mode. + bool no_alias (const hnd_arg_t& arg) + { + m_alias. clear(); + return true; + } + + // Defines auto-alias mode. + bool auto_alias (const hnd_arg_t& arg) + { + m_alias = "*"; + return true; + } + + // Defines target (the callee node). + bool set_target (const hnd_arg_t& arg) + { + m_target = Tokenizer::decode(get_accepted_range(arg)); + + if (m_alias. size() == 1 && static_cast<char>(m_alias[0]) == '*') + m_alias = m_target; + + return true; + } + + // Defines pre-condition that is evaluated on entry. + bool set_pre_cond (const hnd_arg_t& arg) + { + m_pre_cond. reset(new PreCond(arg. staging. pop())); + return true; + } + + // Defines default (empty) pre-condition. + bool no_pre_cond (const hnd_arg_t& arg) + { + m_pre_cond. reset(new PreCond()); + return true; + } + + // Defines post-condition that is evaluated on exit. + bool set_post_cond (const hnd_arg_t& arg) + { + m_post_cond. reset(new PostCond(m_alias, arg. staging. pop())); + return true; + } + + // Defines default (empty) post-condition. + bool no_post_cond (const hnd_arg_t& arg) + { + m_post_cond. reset(new PostCond(m_alias)); + return true; + } + + // Creates joint representing external syntactic functor. + bool create_functor1 (const hnd_arg_t& arg) + { + // Create a new joint of appropriate compound type. + IStaging::joint_pointer joint( + anta::ndl::JointCall<NLG>(arg. staging. cluster(m_target)) + [ m_post_cond ] & m_pre_cond + ); + // Push the new joint into the LL stack. + joint -> set_flavor(0, 1); + joint -> set_flavor(1, 1); + arg. staging. pushJoint(joint); + // Reset condition pointers. + m_pre_cond. reset(); + m_post_cond. reset(); + return true; + } + + // Creates joint representing local syntactic functor. + bool create_functor2 (const hnd_arg_t& arg) + { + // Instantiate trivial pre and post contitional actions. + no_alias(arg); + no_pre_cond(arg); + no_post_cond(arg); + // Create a new joint of appropriate compound type. + IStaging::joint_pointer joint( + (*arg. staging. popJoint()) [ m_post_cond ] & m_pre_cond + ); + // Push the new joint into the LL stack. + joint -> set_flavor(0, 1); + joint -> set_flavor(1, 1); + arg. staging. pushJoint(joint); + // Reset condition pointers. + m_pre_cond. reset(); + m_post_cond. reset(); + return true; + } + + plugin::instance<IConstruct> m_expression; + anta::Label<SG> m_set_alias, m_no_alias, m_auto_alias, m_set_target, + m_set_pre_cond, m_no_pre_cond, m_set_post_cond, m_no_post_cond, + m_create_functor1, m_create_functor2; + +public: + Operator (): + m_expression ("nparse.script.Expression") + { + m_set_alias = hnd_t(this, &Operator::set_alias); + m_no_alias = hnd_t(this, &Operator::no_alias); + m_auto_alias = hnd_t(this, &Operator::auto_alias); + m_set_target = hnd_t(this, &Operator::set_target); + m_set_pre_cond = hnd_t(this, &Operator::set_pre_cond); + m_no_pre_cond = hnd_t(this, &Operator::no_pre_cond); + m_set_post_cond = hnd_t(this, &Operator::set_post_cond); + m_no_post_cond = hnd_t(this, &Operator::no_post_cond); + m_create_functor1 = hnd_t(this, &Operator::create_functor1); + m_create_functor2 = hnd_t(this, &Operator::create_functor2); + } + +public: + int priority () const + { + return PRIORITY_FUNCTOR; + } + + void deploy (level_t a_current, level_t a_previous, const levels_t& a_top) + const + { + using namespace anta::ndl::terminals; + + a_current = + a_previous + // External functor: < res : Target {pre-cond} post-cond > + | ( '<' + // Optional variable name to store the result context. + > ( space > (varName * m_set_alias > space | pass * m_no_alias) + > ':' + | pass * m_auto_alias + ) + // Target node name. + > token<Separator>(PUNCT, true) * m_set_target + // Optional pre and post-conditions. + > ( space > m_expression -> entry() > pass * m_set_pre_cond + > ( space > m_expression -> entry() > pass * m_set_post_cond + | pass * m_no_post_cond + ) + | pass * m_no_pre_cond > pass * m_no_post_cond + ) + > space * m_create_functor1 + > '>' + ) + // Inlined (screening) functor: [ a b c ] + | '[' > space > a_top. back() > space * m_create_functor2 > ']'; + } + +}; + +} // namespace + +PLUGIN(Operator, joint_functor, nparse.script.joints.Functor) diff --git a/pool/shard007/C++/0094814_fleet.cc b/pool/shard007/C++/0094814_fleet.cc new file mode 100644 index 0000000000000000000000000000000000000000..c6a68fa3e285d42fd49b1603778de6924ea748a5 --- /dev/null +++ b/pool/shard007/C++/0094814_fleet.cc @@ -0,0 +1,143 @@ +#include "fleet.h" +#include "areatime.h" +#include "keeper.h" +#include "totalpredator.h" +#include "linearpredator.h" +#include "numberpredator.h" +#include "effortpredator.h" +#include "quotapredator.h" +#include "readfunc.h" +#include "readword.h" +#include "errorhandler.h" +#include "gadget.h" +#include "global.h" + +Fleet::Fleet(CommentStream& infile, const char* givenname, const AreaClass* const Area, + const TimeClass* const TimeInfo, Keeper* const keeper, FleetType ftype) + : BaseClass(givenname), predator(0) { + + type = ftype; + char text[MaxStrLength]; + strncpy(text, "", MaxStrLength); + ifstream subfile; + CommentStream subcomment(subfile); + int tmpint = 0; + Formula multscaler; + IntVector tmpareas; + + keeper->addString("fleet"); + keeper->addString(this->getName()); + infile >> text >> ws; + if (strcasecmp(text, "livesonareas") != 0) + handle.logFileUnexpected(LOGFAIL, "livesonareas", text); + + char c = infile.peek(); + while (isdigit(c) && !infile.eof()) { + infile >> tmpint >> ws; + tmpareas.resize(1, Area->getInnerArea(tmpint)); + c = infile.peek(); + } + this->storeAreas(tmpareas); + + infile >> ws; + c = infile.peek(); + //JMB - removed the need to read in the fleet lengths + if ((c == 'l') || (c == 'L')) { + handle.logMessage(LOGWARN, "Warning in fleet - length data ignored"); + infile.get(c); + while (c != '\n' && !infile.eof()) + infile.get(c); + infile >> ws; + c = infile.peek(); + } + + if ((c == 'm') || (c == 'M')) + readWordAndVariable(infile, "multiplicative", multscaler); + else + multscaler.setValue(1.0); + + switch (type) { + case TOTALFLEET: + predator = new TotalPredator(infile, this->getName(), areas, TimeInfo, keeper, multscaler); + break; + case LINEARFLEET: + predator = new LinearPredator(infile, this->getName(), areas, TimeInfo, keeper, multscaler); + break; + case NUMBERFLEET: + predator = new NumberPredator(infile, this->getName(), areas, TimeInfo, keeper, multscaler); + break; + case EFFORTFLEET: + predator = new EffortPredator(infile, this->getName(), areas, TimeInfo, keeper, multscaler); + break; + case QUOTAFLEET: + predator = new QuotaPredator(infile, this->getName(), areas, TimeInfo, keeper, multscaler); + break; + default: + handle.logMessage(LOGFAIL, "Error in fleet - unrecognised fleet type for", this->getName()); + } + + //the next entry in the file will be the name of the amounts datafile + infile >> text >> ws; + subfile.open(text, ios::in); + handle.checkIfFailure(subfile, text); + handle.Open(text); + readAmounts(subcomment, areas, TimeInfo, Area, amount, this->getName()); + amount.Inform(keeper); + handle.Close(); + subfile.close(); + subfile.clear(); + + //resize tmpPopulation, and set the weight to 1 since this will never change + PopInfo tmppop; + tmppop.W = 1.0; + tmpPopulation.AddRows(Area->numAreas(), 1, tmppop); + + keeper->clearLast(); + keeper->clearLast(); +} + +Fleet::~Fleet() { + delete predator; +} + +void Fleet::calcEat(int area, + const AreaClass* const Area, const TimeClass* const TimeInfo) { + + if (this->isFleetStepArea(area, TimeInfo)) + predator->Eat(area, Area, TimeInfo); +} + +void Fleet::adjustEat(int area, const TimeClass* const TimeInfo) { + if (this->isFleetStepArea(area, TimeInfo)) + predator->adjustConsumption(area, TimeInfo); +} + +void Fleet::calcNumbers(int area, const TimeClass* const TimeInfo) { + if (this->isFleetStepArea(area, TimeInfo)) + predator->Sum(tmpPopulation[this->areaNum(area)], area); +} + +void Fleet::Reset(const TimeClass* const TimeInfo) { + int i; + predator->Reset(TimeInfo); + for (i = 0; i < tmpPopulation.Nrow(); i++) + if (this->isFleetStepArea(i, TimeInfo)) + tmpPopulation[this->areaNum(i)][0].N = amount[TimeInfo->getTime()][this->areaNum(i)]; +} + +void Fleet::Print(ofstream& outfile) const { + outfile << "\nFleet - type "; + predator->Print(outfile); +} + +int Fleet::isFleetStepArea(int area, const TimeClass* const TimeInfo) { + if ((this->isInArea(area) == 0) || isZero(predator->getMultScaler())) + return 0; + if (amount[TimeInfo->getTime()][this->areaNum(area)] < 0.0) + handle.logMessage(LOGWARN, "Warning in fleet - negative amount consumed for", this->getName()); + if ((predator->getType() == QUOTAPREDATOR) && (TimeInfo->getStep() == 1)) + return 1; //JMB need to check the first step + if (isZero(amount[TimeInfo->getTime()][this->areaNum(area)])) + return 0; + return 1; +} diff --git a/pool/shard007/C++/0094816_management_ui.cc b/pool/shard007/C++/0094816_management_ui.cc new file mode 100644 index 0000000000000000000000000000000000000000..4254c9ddf6b7b93a62fa9e16124acb7a5c8ff9ca --- /dev/null +++ b/pool/shard007/C++/0094816_management_ui.cc @@ -0,0 +1,194 @@ +// Copyright 2018 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 "chrome/browser/ui/webui/management_ui.h" + +#include <memory> + +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/policy/profile_policy_connector.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/management_ui_handler.h" +#include "chrome/browser/ui/webui/webui_util.h" +#include "chrome/common/url_constants.h" +#include "chrome/common/webui_url_constants.h" +#include "chrome/grit/browser_resources.h" +#include "chrome/grit/generated_resources.h" +#include "chrome/grit/theme_resources.h" +#include "components/safe_browsing/core/common/safebrowsing_constants.h" +#include "components/strings/grit/components_strings.h" +#include "extensions/buildflags/buildflags.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/base/resource/resource_bundle.h" +#include "ui/base/webui/web_ui_util.h" + +#if defined(OS_CHROMEOS) +#include "chrome/browser/browser_process.h" +#include "chrome/browser/browser_process_platform_part.h" +#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" +#include "chrome/grit/chromium_strings.h" +#include "ui/chromeos/devicetype_utils.h" +#else // defined(OS_CHROMEOS) +#include "chrome/browser/browser_process.h" +#include "chrome/browser/policy/chrome_browser_policy_connector.h" +#endif // defined(OS_CHROMEOS) + +namespace { + +content::WebUIDataSource* CreateManagementUIHtmlSource(Profile* profile) { + content::WebUIDataSource* source = + content::WebUIDataSource::Create(chrome::kChromeUIManagementHost); + + source->AddString("pageSubtitle", + ManagementUI::GetManagementPageSubtitle(profile)); + + static constexpr webui::LocalizedString kLocalizedStrings[] = { +#if defined(OS_CHROMEOS) + {"learnMore", IDS_LEARN_MORE}, + {"localTrustRoots", IDS_MANAGEMENT_LOCAL_TRUST_ROOTS}, + {"managementTrustRootsConfigured", IDS_MANAGEMENT_TRUST_ROOTS_CONFIGURED}, + {"deviceConfiguration", IDS_MANAGEMENT_DEVICE_CONFIGURATION}, + {"deviceReporting", IDS_MANAGEMENT_DEVICE_REPORTING}, + {kManagementLogUploadEnabled, IDS_MANAGEMENT_LOG_UPLOAD_ENABLED}, + {kManagementReportActivityTimes, + IDS_MANAGEMENT_REPORT_DEVICE_ACTIVITY_TIMES}, + {kManagementReportHardwareStatus, + IDS_MANAGEMENT_REPORT_DEVICE_HARDWARE_STATUS}, + {kManagementReportNetworkInterfaces, + IDS_MANAGEMENT_REPORT_DEVICE_NETWORK_INTERFACES}, + {kManagementReportUsers, IDS_MANAGEMENT_REPORT_DEVICE_USERS}, + {kManagementReportCrashReports, IDS_MANAGEMENT_REPORT_DEVICE_CRASH_REPORTS}, + {kManagementPrinting, IDS_MANAGEMENT_REPORT_PRINTING}, + {kManagementCrostini, IDS_MANAGEMENT_CROSTINI}, + {kManagementCrostiniContainerConfiguration, + IDS_MANAGEMENT_CROSTINI_CONTAINER_CONFIGURATION}, + {kManagementReportExtensions, IDS_MANAGEMENT_REPORT_EXTENSIONS}, + {kManagementReportAndroidApplications, + IDS_MANAGEMENT_REPORT_ANDROID_APPLICATIONS}, + {kManagementReportProxyServer, IDS_MANAGEMENT_REPORT_PROXY_SERVER}, +#endif // defined(OS_CHROMEOS) + {"browserReporting", IDS_MANAGEMENT_BROWSER_REPORTING}, + {"browserReportingExplanation", + IDS_MANAGEMENT_BROWSER_REPORTING_EXPLANATION}, + {"extensionReporting", IDS_MANAGEMENT_EXTENSION_REPORTING}, + {"extensionReportingTitle", IDS_MANAGEMENT_EXTENSIONS_INSTALLED}, + {"extensionName", IDS_MANAGEMENT_EXTENSIONS_NAME}, + {"extensionPermissions", IDS_MANAGEMENT_EXTENSIONS_PERMISSIONS}, + {"title", IDS_MANAGEMENT_TITLE}, + {"toolbarTitle", IDS_MANAGEMENT_TOOLBAR_TITLE}, + {"searchPrompt", IDS_SETTINGS_SEARCH_PROMPT}, + {"clearSearch", IDS_DOWNLOAD_CLEAR_SEARCH}, + {"backButton", IDS_ACCNAME_BACK}, + {kManagementExtensionReportMachineName, + IDS_MANAGEMENT_EXTENSION_REPORT_MACHINE_NAME}, + {kManagementExtensionReportMachineNameAddress, + IDS_MANAGEMENT_EXTENSION_REPORT_MACHINE_NAME_ADDRESS}, + {kManagementExtensionReportUsername, + IDS_MANAGEMENT_EXTENSION_REPORT_USERNAME}, + {kManagementExtensionReportVersion, + IDS_MANAGEMENT_EXTENSION_REPORT_VERSION}, + {kManagementExtensionReportExtensionsPlugin, + IDS_MANAGEMENT_EXTENSION_REPORT_EXTENSIONS_PLUGINS}, + {kManagementExtensionReportPerfCrash, + IDS_MANAGEMENT_EXTENSION_REPORT_PERF_CRASH}, + {kManagementExtensionReportUserBrowsingData, + IDS_MANAGEMENT_EXTENSION_REPORT_USER_BROWSING_DATA}, + {kThreatProtectionTitle, IDS_MANAGEMENT_THREAT_PROTECTION}, + {kManagementDataLossPreventionName, + IDS_MANAGEMENT_DATA_LOSS_PREVENTION_NAME}, + {kManagementDataLossPreventionPermissions, + IDS_MANAGEMENT_DATA_LOSS_PREVENTION_PERMISSIONS}, + {kManagementMalwareScanningName, IDS_MANAGEMENT_MALWARE_SCANNING_NAME}, + {kManagementMalwareScanningPermissions, + IDS_MANAGEMENT_MALWARE_SCANNING_PERMISSIONS}, + {kManagementEnterpriseReportingName, + IDS_MANAGEMENT_ENTERPRISE_REPORTING_NAME}, + {kManagementEnterpriseReportingPermissions, + IDS_MANAGEMENT_ENTERPRISE_REPORTING_PERMISSIONS}, + }; + + AddLocalizedStringsBulk(source, kLocalizedStrings); + + source->AddString(kManagementExtensionReportSafeBrowsingWarnings, + l10n_util::GetStringFUTF16( + IDS_MANAGEMENT_EXTENSION_REPORT_SAFE_BROWSING_WARNINGS, + base::UTF8ToUTF16(safe_browsing::kSafeBrowsingUrl))); +#if defined(OS_CHROMEOS) + source->AddString("managementDeviceLearnMoreUrl", + chrome::kLearnMoreEnterpriseURL); + source->AddString("managementAccountLearnMoreUrl", + chrome::kManagedUiLearnMoreUrl); +#endif // defined(OS_CHROMEOS) + + source->UseStringsJs(); + source->EnableReplaceI18nInJS(); + // Add required resources. + source->AddResourcePath("management_browser_proxy.js", + IDR_MANAGEMENT_BROWSER_PROXY_JS); + source->AddResourcePath("management_ui.js", IDR_MANAGEMENT_UI_JS); + source->AddResourcePath("icons.js", IDR_MANAGEMENT_ICONS_JS); + source->SetDefaultResource(IDR_MANAGEMENT_HTML); + return source; +} + +} // namespace + +// static +base::RefCountedMemory* ManagementUI::GetFaviconResourceBytes( + ui::ScaleFactor scale_factor) { + return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytesForScale( + IDR_MANAGEMENT_FAVICON, scale_factor); +} + +// static +base::string16 ManagementUI::GetManagementPageSubtitle(Profile* profile) { +#if defined(OS_CHROMEOS) + policy::BrowserPolicyConnectorChromeOS* connector = + g_browser_process->platform_part()->browser_policy_connector_chromeos(); + const auto device_type = ui::GetChromeOSDeviceTypeResourceId(); + if (!connector->IsEnterpriseManaged() && + !profile->GetProfilePolicyConnector()->IsManaged()) { + return l10n_util::GetStringFUTF16(IDS_MANAGEMENT_NOT_MANAGED_SUBTITLE, + l10n_util::GetStringUTF16(device_type)); + } + + std::string display_domain = connector->GetEnterpriseDisplayDomain(); + + if (display_domain.empty()) + display_domain = connector->GetRealm(); + if (display_domain.empty()) + display_domain = ManagementUIHandler::GetAccountDomain(profile); + if (display_domain.empty()) { + return l10n_util::GetStringFUTF16(IDS_MANAGEMENT_SUBTITLE_MANAGED, + l10n_util::GetStringUTF16(device_type)); + } + return l10n_util::GetStringFUTF16(IDS_MANAGEMENT_SUBTITLE_MANAGED_BY, + l10n_util::GetStringUTF16(device_type), + base::UTF8ToUTF16(display_domain)); +#else // defined(OS_CHROMEOS) + const auto management_domain = ManagementUIHandler::GetAccountDomain(profile); + const auto managed = + profile->GetProfilePolicyConnector()->IsManaged() || + g_browser_process->browser_policy_connector()->HasMachineLevelPolicies(); + if (management_domain.empty()) { + return l10n_util::GetStringUTF16(managed + ? IDS_MANAGEMENT_SUBTITLE + : IDS_MANAGEMENT_NOT_MANAGED_SUBTITLE); + } + if (managed) { + return l10n_util::GetStringFUTF16(IDS_MANAGEMENT_SUBTITLE_MANAGED_BY, + base::UTF8ToUTF16(management_domain)); + } + return l10n_util::GetStringUTF16(IDS_MANAGEMENT_NOT_MANAGED_SUBTITLE); +#endif // defined(OS_CHROMEOS) +} + +ManagementUI::ManagementUI(content::WebUI* web_ui) : WebUIController(web_ui) { + content::WebUIDataSource* source = + CreateManagementUIHtmlSource(Profile::FromWebUI(web_ui)); + ManagementUIHandler::Initialize(web_ui, source); + content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source); +} + +ManagementUI::~ManagementUI() {} diff --git a/pool/shard007/C++/0094821_AllenThreadPoolTest.cpp b/pool/shard007/C++/0094821_AllenThreadPoolTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..804fcc7e1c947c576847fc79c56e80507ff71573 --- /dev/null +++ b/pool/shard007/C++/0094821_AllenThreadPoolTest.cpp @@ -0,0 +1,29 @@ +#include "AllenThreadPool.hpp" +#include<iostream> +using namespace std; +using namespace std::chrono; + +int main() +{ + AllenThreadPool a(4); + + auto job = []() { + this_thread::sleep_for(1s); + }; + + int RunTimes = 8; + + auto StartTime = steady_clock::now(); + for (int i = 0; i < RunTimes; i++) + job(); + auto cost = steady_clock::now() - StartTime; + cout << "single thread finished cost " << duration_cast<milliseconds>(cost).count() << "ms" << endl; + + StartTime = steady_clock::now(); + a.AddJob(job, RunTimes); + a.Wait(); + cost = steady_clock::now() - StartTime; + cout << "thread pool finished cost " << duration_cast<milliseconds>(cost).count() << "ms" << endl; + + return 0; +} \ No newline at end of file diff --git a/pool/shard007/C++/0094822_main_cpu.cpp b/pool/shard007/C++/0094822_main_cpu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c93950847e0b9d8ff9ce213e1e0ea74f998f17b7 --- /dev/null +++ b/pool/shard007/C++/0094822_main_cpu.cpp @@ -0,0 +1,67 @@ +#include <stdio.h> +#include <string> +#include <iostream> +#include <vector> + +std::vector<int> GDistance; +std::vector<int> GForce; + +std::vector<int> gen_distance_array(int num_vectors) { + int i = 0; + std::vector<int> distance_array(num_vectors); + for (i = 0; i < num_vectors; i++) { + distance_array[i] = (i + 1) % 10; + if (distance_array[i] == 0) { + distance_array[i] = 10; + } + } + return distance_array; +} + +std::vector<int> gen_force_array(int num_vectors) { + int i, j, half_vectors; + half_vectors = num_vectors / 2; + std::vector<int> force_array(num_vectors); + + for (i = 0; i < num_vectors; i++) { + if (i < half_vectors) { + force_array[i] = i + 1; + } else { + force_array[i] = half_vectors + (half_vectors - i); + } + } + + return force_array; +} + +void printarray(std::vector<int> array, int size) { + for (int i = 0; i < size; i++) { + std::cout << array[i] << " "; + } +} + +int main(int argc, char *argv[]) { + int num_vectors = 0, half_vectors, i, j, temp; + long long s_dotproduct = 0; + if (argc < 2) { + std::cout << "Usage: cuda-musclework num_vectors" << std::endl; + } + num_vectors = atoi(argv[1]); + std::cout << "Using num_vectors: " << num_vectors << std::endl; + + // generate and compute the dot product, serially + clock_t cpu_start = clock(); + GDistance.resize(num_vectors, 0); + GForce.resize(num_vectors, 0); + GDistance = gen_distance_array(num_vectors); + GForce = gen_force_array(num_vectors); + for (i = 0; i < num_vectors; i++) { + temp = GDistance[i] * GForce[i]; + s_dotproduct = s_dotproduct + temp; + } + clock_t cpu_stop = clock(); + double elapsed_cpu = double(cpu_stop - cpu_start) / (CLOCKS_PER_SEC / 1000); + + std::cout << "CPU (serial) dot product: " << s_dotproduct << std::endl; + std::cout << "CPU Time Taken (msec): " << elapsed_cpu << std::endl; +} diff --git a/pool/shard007/C++/0094823_FialaTire.cpp b/pool/shard007/C++/0094823_FialaTire.cpp new file mode 100644 index 0000000000000000000000000000000000000000..529fd2c7da117f9081b98803cd06b8f13c9d918b --- /dev/null +++ b/pool/shard007/C++/0094823_FialaTire.cpp @@ -0,0 +1,130 @@ +// ============================================================================= +// PROJECT CHRONO - http://projectchrono.org +// +// Copyright (c) 2015 projectchrono.org +// All rights reserved. +// +// Use of this source code is governed by a BSD-style license that can be found +// in the LICENSE file at the top level of the distribution and at +// http://projectchrono.org/license-chrono.txt. +// +// ============================================================================= +// Authors: Radu Serban, Michael Taylor, Rainer Gericke +// ============================================================================= +// +// Fiala tire constructed with data from file (JSON format). +// +// ============================================================================= + +#include <algorithm> + +#include "chrono_vehicle/wheeled_vehicle/tire/FialaTire.h" +#include "chrono_vehicle/ChVehicleModelData.h" +#include "chrono_vehicle/utils/ChUtilsJSON.h" + +#include "chrono_thirdparty/rapidjson/filereadstream.h" + +using namespace rapidjson; + +namespace chrono { +namespace vehicle { + +// ----------------------------------------------------------------------------- +// ----------------------------------------------------------------------------- +FialaTire::FialaTire(const std::string& filename) : ChFialaTire(""), m_has_mesh(false) { + FILE* fp = fopen(filename.c_str(), "r"); + + char readBuffer[65536]; + FileReadStream is(fp, readBuffer, sizeof(readBuffer)); + + fclose(fp); + + Document d; + d.ParseStream<ParseFlag::kParseCommentsFlag>(is); + + Create(d); + + GetLog() << "Loaded JSON: " << filename.c_str() << "\n"; +} + +FialaTire::FialaTire(const rapidjson::Document& d) : ChFialaTire(""), m_has_mesh(false) { + Create(d); +} + +FialaTire::~FialaTire() { +} + +void FialaTire::Create(const rapidjson::Document& d) { + // Invoke base class method. + ChPart::Create(d); + + m_mass = d["Mass"].GetDouble(); + m_inertia = LoadVectorJSON(d["Inertia"]); + if (d.HasMember("Coefficient of Friction")) { + // Default value = 0.8 + m_mu_0 = d["Coefficient of Friction"].GetDouble(); + } + if(d.HasMember("Nominal Vertical Force [N]")) { + // Helpful for plotting + m_Fz_nom = d["Nominal Vertical Force [N]"].GetDouble(); + } + // Read in Fiala tire model parameters + m_unloaded_radius = d["Fiala Parameters"]["Unloaded Radius"].GetDouble(); + m_width = d["Fiala Parameters"]["Width"].GetDouble(); + m_normalStiffness = d["Fiala Parameters"]["Vertical Stiffness"].GetDouble(); + m_normalDamping = d["Fiala Parameters"]["Vertical Damping"].GetDouble(); + m_rolling_resistance = d["Fiala Parameters"]["Rolling Resistance"].GetDouble(); + m_c_slip = d["Fiala Parameters"]["CSLIP"].GetDouble(); + m_c_alpha = d["Fiala Parameters"]["CALPHA"].GetDouble(); + m_u_min = d["Fiala Parameters"]["UMIN"].GetDouble(); + m_u_max = d["Fiala Parameters"]["UMAX"].GetDouble(); + m_relax_length_x = d["Fiala Parameters"]["X Relaxation Length"].GetDouble(); + m_relax_length_y = d["Fiala Parameters"]["Y Relaxation Length"].GetDouble(); + if(m_relax_length_x <= 0.0 || m_relax_length_y <= 0.0) { + m_dynamic_mode = false; + } + m_visualization_width = m_width; + + // Check how to visualize this tire. + if (d.HasMember("Visualization")) { + if (d["Visualization"].HasMember("Mesh Filename")) { + m_meshFile = d["Visualization"]["Mesh Filename"].GetString(); + m_meshName = d["Visualization"]["Mesh Name"].GetString(); + m_has_mesh = true; + } + + if (d["Visualization"].HasMember("Width")) { + m_visualization_width = d["Visualization"]["Width"].GetDouble(); + } + } +} + +// ----------------------------------------------------------------------------- +void FialaTire::AddVisualizationAssets(VisualizationType vis) { + if (vis == VisualizationType::MESH && m_has_mesh) { + geometry::ChTriangleMeshConnected trimesh; + trimesh.LoadWavefrontMesh(vehicle::GetDataFile(m_meshFile), false, false); + m_trimesh_shape = std::make_shared<ChTriangleMeshShape>(); + m_trimesh_shape->SetMesh(trimesh); + m_trimesh_shape->SetName(m_meshName); + m_trimesh_shape->SetStatic(true); + m_wheel->AddAsset(m_trimesh_shape); + } + else { + ChFialaTire::AddVisualizationAssets(vis); + } +} + +void FialaTire::RemoveVisualizationAssets() { + ChFialaTire::RemoveVisualizationAssets(); + + // Make sure we only remove the assets added by FialaTire::AddVisualizationAssets. + // This is important for the ChTire object because a wheel may add its own assets + // to the same body (the spindle/wheel). + auto it = std::find(m_wheel->GetAssets().begin(), m_wheel->GetAssets().end(), m_trimesh_shape); + if (it != m_wheel->GetAssets().end()) + m_wheel->GetAssets().erase(it); +} + +} // end namespace vehicle +} // end namespace chrono diff --git a/pool/shard007/C++/0094827_Classmate.cpp b/pool/shard007/C++/0094827_Classmate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..52e97cee118e538cebc34f79b7af48b9b97f04f3 --- /dev/null +++ b/pool/shard007/C++/0094827_Classmate.cpp @@ -0,0 +1,69 @@ +//Ryan Andrews Date: 4/23/14 +//Class CS 53 Section: B + +#include "Classmate.h" +using namespace std; + +ostream& operator<<(ostream& os, Classmate& Mate) +{ + os << Mate.m_Name << " has IQ " << Mate.m_IQ << " and is at (" + << Mate.m_Posx << ", " << Mate.m_Posy << ")." << endl; + + return os; +} + +void Classmate::Move(const int YardSize) +{ + const int MOVE_DIR = rand()%2; //0: Move up/left, 1: Move down/right + const int MOVE_POS = rand()%2; //0: Move y, 1: Move x + + int DirMax = 0; + //DirMax: the maximum distance the Mate can move + + if (MOVE_POS) //If moving Horizontal + { + if (!MOVE_DIR) //If moving Left + { + DirMax = m_Posx; + m_Posx -= rand()%(DirMax+1); + } + else //If moving Right + { + DirMax = YardSize-m_Posx; + m_Posx += rand()%(DirMax+1); + } + } + else //If moving Vertical + { + if (!MOVE_DIR) //If moving Up + { + DirMax = m_Posy; + m_Posy -= rand()%(DirMax+1); + } + else //If moving Down + { + DirMax = YardSize-m_Posy; + m_Posy += rand()%(DirMax+1); + } + } + return; +} + +void Classmate::SetIQ(const int IQ) +{ + m_IQ = IQ; +} +void Classmate::Place() +{ + const int YARD_SIZE = 25; //Maximum yard size that can be created + //Used to place ralphy in the yard. + m_Posx = rand()%(YARD_SIZE); + m_Posy = rand()%(YARD_SIZE); + + return; +} + +int Classmate::GetIQ() +{ + return m_IQ; +} \ No newline at end of file diff --git a/pool/shard007/C++/0094830_ch_track_main.cc b/pool/shard007/C++/0094830_ch_track_main.cc new file mode 100644 index 0000000000000000000000000000000000000000..75c0862517eb6f0517166c6648d433e4ad37558b --- /dev/null +++ b/pool/shard007/C++/0094830_ch_track_main.cc @@ -0,0 +1,463 @@ +/*************************************************************************/ +/* */ +/* Centre for Speech Technology Research */ +/* University of Edinburgh, UK */ +/* Copyright (c) 1994,1995,1996 */ +/* All Rights Reserved. */ +/* */ +/* Permission is hereby granted, free of charge, to use and distribute */ +/* this software and its documentation without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of this work, and to */ +/* permit persons to whom this work is furnished to do so, subject to */ +/* the following conditions: */ +/* 1. The code must retain the above copyright notice, this list of */ +/* conditions and the following disclaimer. */ +/* 2. Any modifications must be clearly marked as such. */ +/* 3. Original authors' names are not deleted. */ +/* 4. The authors' names are not used to endorse or promote products */ +/* derived from this software without specific prior written */ +/* permission. */ +/* */ +/* THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK */ +/* DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING */ +/* ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT */ +/* SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE */ +/* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES */ +/* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN */ +/* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, */ +/* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF */ +/* THIS SOFTWARE. */ +/* */ +/*************************************************************************/ +/* Author : Paul Taylor */ +/* Date : June 1994 */ +/*-----------------------------------------------------------------------*/ +/* EST_Track file manipulation program */ +/* */ +/*=======================================================================*/ + +#include "EST.h" +#include "EST_Wave.h" +#include "EST_cmd_line_options.h" + +#define DEFAULT_TIME_SCALE 0.001 + +int StrListtoIList(EST_StrList &s, EST_IList &il); +void extract_channel(EST_Track &orig, EST_Track &nt, EST_IList &ch_list); + +EST_write_status save_snns_pat(const EST_String filename, + EST_TrackList &inpat, EST_TrackList &outpat); + +EST_read_status read_TrackList(EST_TrackList &tlist, EST_StrList &files, + EST_Option &al); + +void extract(EST_Track &tr, EST_Option &al); +/** @name <command>ch_track</command> <emphasis>Track file manipulation</emphasis> + * @id ch-track-manual + * @toc + */ + +//@{ + + +/**@name Synopsis + */ +//@{ + +//@synopsis + +/** +ch_track is used to manipulate the format of a track +file. Operations include: + +<itemizedlist> +<listitem><para>file format conversion</para></listitem> +<listitem><para>smoothing</para></listitem> +<listitem><para>changing the frame spacing of a track (resampling)</para></listitem> +<listitem><para>producing differentiated and delta tracks</para></listitem> +<listitem><para>Using a threshold to convert a track file to a label file</para></listitem> + +<listitem><para>making multiple input files into a single multi-channel output file</para></listitem> +<listitem><para>extracting a single channel from a multi-channel track</para></listitem> +<listitem><para>extracting a time-delimited portion of the waveform</para></listitem> +</itemizedlist> + + */ + +//@} + +/**@name Options + */ +//@{ + +//@options + +//@} + + +int main(int argc, char *argv[]) +{ + EST_String in_file("-"), out_file("-"); + EST_Option al, settings; + EST_String fname, ftmp; + EST_StrList files; + EST_Track tr; + EST_TrackList trlist; + EST_Litem *p; + + parse_command_line( + argc, argv, + EST_String("[input file] -o [output file] [options]\n")+ + "Summary: change/copy track files\n" + "use \"-\" to make input and output files stdin/out\n" + "-h Options help\n"+ + options_track_input()+ "\n"+ + options_track_output()+ "\n" + "-info Print information about file and header. \n" + " This option gives useful information such as file \n" + " length, file type, channel names. No output is produced\n\n" + "-track_names <string> \n" + " File containing new names for output channels\n\n" + "-diff Differentiate contour. This performs simple \n" + " numerical differentiation on the contour by \n" + " subtracting the amplitude of the current frame \n" + " from the amplitude of the next. Although quick, \n" + " this technique is crude and not recommende as the \n" + " estimation of the derivate is done on only one point\n\n" + "-delta <int> Make delta coefficients (better form of differentiate).\n" + " The argument to this option is the regression length of \n" + " of the delta calculation and can be between 2 and 4 \n\n" + "-sm <float> Length of smoothing window in seconds. Various types of \n" + " smoothing are available for tracks. This options specifies \n" + " length of the smooting window which effects the degree of \n" + " smoothing, i.e. a longer value means more smoothing \n\n" + "-smtype <string> Smooth type, median or mean\n" + "-style <string> Convert track to other form. Currently only one form \n" + " \"label\" is supported. This uses a specified cut off to \n" + " make a label file, with two labels, one for above the \n" + " cut off (-pos) and one for below (-neg)\n\n" + "-t <float> threshold for track to label conversion \n" + "-neg <string> Name of negative label in track to label conversion \n" + "-pos <string> Name of positive label in track to label conversion \n" + "-pc <string> Combine given tracks in parallel. If option \n" + " is longest, pad shorter tracks to longest, else if \n" + " first pad/cut to match first input track \n" + + options_track_filetypes_long(), + files, al); + +/*redundant options + "-time_channel <string>\n"+ + " Which track in track file holds pitchmark times\n"+ + "-time_scale <float> \n"+ + " Scale of pitchmarks (default 0.001 = milliseconds)\n"+ +*/ + + + override_lib_ops(settings, al); + out_file = al.present("-o") ? al.val("-o") : (EST_String)"-"; + + EST_TokenStream ts; + +// ts.open(files.first()); +// tr.load(ts); +// cout << tr; + + if (read_TrackList(trlist, files, al) != read_ok) + exit(0); + + if (files.length() == 0) + { + cerr << argv[0] << ": no input files specified\n"; + exit(-1); + } + + if (al.present("-info")) + { + for (p = trlist.head(); p; p = p->next()) + track_info(trlist(p)); + exit(0); + } + + if (al.present("-pc")) // parallelize them + ParallelTracks(tr, trlist, al.val("-pc")); + + else if (al.val("-otype", 0) == "snns") + { // sometime this will generalise for multiple input files + EST_TrackList inpat, outpat; + inpat.append(trlist.nth(0)); + outpat.append(trlist.nth(1)); + save_snns_pat(out_file, inpat, outpat); + exit(0); + } + else // concatenate them + { + tr.resize(0, tr.num_channels()); + // Reorg -- fix += to resize to largest num_channels (with warning) + for (p = trlist.head(); p; p = p->next()) + tr += trlist(p); + } + + if (al.present("-S")) + tr.sample(al.fval("-S")); + if (al.present("-sm")) + { + track_smooth(tr, al.fval("-sm"),al.val("-smtype")); + } + + if (al.present("-diff") && al.present("-delta")) + { + cerr << "Using -diff and -delta together makes no sense !\n"; + exit(-1); + } + if (al.present("-diff")) + { + tr = differentiate(tr); + } + if (al.present("-delta")) + { + EST_Track ntr = tr; // to copy size !; + delta(tr,ntr,al.ival("-delta")); + tr = ntr; + } + + + if (al.present("-c")) + { + EST_StrList s; + EST_Track ntr; + EST_IList il; + StringtoStrList(al.val("-c"), s, " ,"); // separator can be space or comma + StrListtoIList(s, il); + extract_channel(tr, ntr, il); + tr = ntr; + } + + if (al.present("-start") || al.present("-end") + || al.present("-to") || al.present("-from")) + extract(tr, al); + +// tr.assign_map(&LPCTrackMap); +// tr.set_space_type("VARI"); + + + // optionally rename output tracks before saving + + if (al.present("-track_names")) + { + EST_StrList new_names; + if(load_StrList(al.val("-track_names"),new_names) != format_ok) + { + cerr << "Failed to load new track names file." << endl; + exit(-1); + } + /* + if (tr.num_channels() != new_names.length()) + { + cerr << "Number of names in output track names file ("; + cerr << new_names.length() << ") " << endl; + cerr << " does not match number of output channels ("; + cerr << tr.num_channels() << ")" << endl; + exit(-1); + } + + EST_Litem *np; + int ni; + for (np = new_names.head(),ni=0; np; np = np->next(),ni++) + tr.set_channel_name(new_names(np),ni); + */ + tr.resize(EST_CURRENT, new_names); + } + + // track_info(tr); + +/* tr.resize(EST_CURRENT, 10); + + cout << "new\n"; + track_info(tr); + + EST_StrList x; + x.append("a"); + x.append("c"); + x.append("d"); + + + + cout << "new\n"; + track_info(tr); +*/ + + + // Write out file in appropriate format + + if (al.val("-style",0) == "label") + { + EST_Relation lab; + if (al.present("-t")) + track_to_label(tr, lab, al.fval("-t")); + else + track_to_label(tr, lab); + if (al.present("-pos")) + change_label(lab, "pos", al.val("-pos")); + if (al.present("-neg")) + change_label(lab, "neg", al.val("-neg")); + if (lab.save(out_file) != write_ok) + exit(-1); + } +/* else if (al.val("-style",0) == "pm") + { + EST_Relation lab; + + if (!al.present("-f")) + { + cerr << "must specify sample rate (with -f) for pm style\n"; + exit(-1); + } + int sample_rate = al.ival("-f", 0); + + track_to_pm(tr, sample_rate, lab); + + if (lab.save(out_file) != write_ok) + exit(-1); + } +*/ + else + { + if (tr.save(out_file, al.val("-otype")) != write_ok) + exit(-1); + } + + return 0; +} + +void override_lib_ops(EST_Option &a_list, EST_Option &al) +{ + a_list.override_val("ishift", al.val("-s", 0)); + a_list.override_val("color", al.val("-color", 0)); + a_list.override_val("in_track_file_type", al.val("-itype", 0)); + a_list.override_val("out_track_file_type", al.val("-otype", 0)); + a_list.override_val("tr_to_label_thresh", al.val("-t", 0)); + a_list.override_fval("time_scale", DEFAULT_TIME_SCALE); + + if (al.val("-style", 0) == "label") + a_list.override_val("lab_file_type", al.val("-otype", 0)); + if (al.present("-time_scale")) + a_list.override_fval("time_scale", al.fval("-time_scale", 1)); + if (al.present("-time_channel")) + a_list.override_val("time_channel", al.sval("-time_channel", 1)); +} + + +/** @name Making multiple tracks into a single track + +If multiple input files are specified, by default they are concatenated into +the output file. +<para> +<screen> +$ ch_track kdt_010.tr kdt_011.tr kdt_012.tr kdt_013.tr -o out.tr +</screen> +</para> +<para> +In the above example, 4 multi channel input files are converted to +one single channel output file. Multi-channel tracks can +concatenated provided they all have the same number of input channels. + +</para><para> + +Multiple input files can be made into a multi-channel output file by +using the -pc option: + +</para><para> +<screen> +$ ch_track kdt_010.tr kdt_011.tr kdt_012.tr kdt_013.tr -o -pc longest out.tr +</screen> +</para> +<para> +The argument to -pc can either be longest, in which the output +track is the length of the longest input file, or first in which it +is the length of the first input file. + +*/ + +//@{ +//@} + +/** @name Extracting channels from multi-channel tracks + +The -c option is used to specify channels which should be extracted +from the input. If the input is a 4 channel track, +</para><para> +<screen> +$ ch_track kdt_m.tr -o a.tr -c "0 2" +</screen> +</para> +<para> +will extract the 0th and 2nd channel (counting starts from 0). The +argument to -c can be either a single number of a list of numbers +(wrapped in quotes). + + */ +//@{ +//@} + + +/** @name Extracting of a single region from a track + +There are several ways of extracting a region of a track. The +simplest way is by using the start, end, to and from commands to +delimit a sub portion of the input track. For example +</para><para> +<screen> +$ ch_track kdt_010.tr -o small.tr -start 1.45 -end 1.768 +</screen> +</para> +<para> +extracts a subtrack starting at 1.45 seconds and extending to 1.768 seconds. +alternatively, +</para><para> +<screen> +$ ch_track kdt_010.tr -o small.tr -from 50 -to 100 +</screen> +</para> +<para> +extracts a subtrack starting at 50 frames and extending to 100 +frames. Times and frames can be mixed in sub-track extraction. The +output track will have the same number of channels as the input track. + + +*/ +//@{ +//@} + +/** @name Adding headers and format conversion + +It is usually a good idea for all track files to have headers as this +way different files can be handled safely. ch_track provides a means +of adding headers to unheadered files. These files are assumed to +be ascii floats with one channel per line. + +The following adds a header to an ascii file. +</para> +<para> +<screen> +$ ch_track kdt_010.atr -o kdt_010.h5.tr -otype est -s 0.01 +</screen> +</para> +<para> +ch_track can change the frame shift of a fixed frame file, or convert +a variable frame shift file into a fixed frame shift. At present this +is done with a very crude resampling technique and hence the output +file may suffer from anti-aliasing distortion.</para><para> + + +Change to a frame spacing of 0.02 seconds: +</para><para> +<screen> +$ ch_track kdt_010.tr -o kdt_010.tr2 -S 0.02 +</screen> +*/ + //@{ + //@} + +//@} + diff --git a/pool/shard007/C++/0094834_minimum.cpp b/pool/shard007/C++/0094834_minimum.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ae1253c29ac8d91d49d3db14525d811663166e1d --- /dev/null +++ b/pool/shard007/C++/0094834_minimum.cpp @@ -0,0 +1,52 @@ +#include "iroha/iroha.h" + +using namespace iroha; + +IDesign *build_design() { + IDesign *design = new IDesign; + + IModule *module = new IModule(design, "M"); + design->modules_.push_back(module); + ITable *table = new ITable(module); + module->tables_.push_back(table); + IState *st1 = new IState(table); + IState *st2 = new IState(table); + table->states_.push_back(st1); + table->states_.push_back(st2); + + IResource *assign = DesignTool::GetOneResource(table, resource::kSet); + IInsn *insn = new IInsn(assign); + IRegister *dst = DesignTool::AllocRegister(table, "dst_reg", 32); + IRegister *src = DesignTool::AllocConstNum(table, 32, 123); + insn->inputs_.push_back(src); + insn->outputs_.push_back(dst); + + st1->insns_.push_back(insn); + + table->SetInitialState(st1); + DesignTool::AddNextState(st1, st2); + DesignTool::Validate(design); + + return design; +} + +int main(int argc, char **argv) { + Iroha::Init(); + + IDesign *design = build_design(); + + OptAPI *opt = Iroha::CreateOptimizer(design); + opt->ApplyPass("a_pass"); + + iroha::WriterAPI *writer = Iroha::CreateWriter(design); + // Use S-Expression. + writer->SetLanguage(""); + writer->Write("/dev/stdout"); + + writer->SetLanguage("verilog"); + writer->Write("/dev/stdout"); + + delete design; + + return 0; +} diff --git a/pool/shard007/C++/0094837_kiokdeconnect.cpp b/pool/shard007/C++/0094837_kiokdeconnect.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b7420934ccfa66efee854a3ae16214f11a8d4129 --- /dev/null +++ b/pool/shard007/C++/0094837_kiokdeconnect.cpp @@ -0,0 +1,235 @@ +/** + * Copyright 2013 Albert Vaca <albertvaka@gmail.com> + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License or (at your option) version 3 or any later version + * accepted by the membership of KDE e.V. (or its successor approved + * by the membership of KDE e.V.), which shall act as a proxy + * defined in Section 14 of version 3 of the license. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "kiokdeconnect.h" + +#include <QtCore/QThread> +#include <QDBusMetaType> + +#include <KDebug> +#include <KComponentData> +#include <KCmdLineArgs> +#include <KAboutData> +#include <KProcess> +#include <KApplication> +#include <KLocale> + +#include <core/kdebugnamespace.h> + +extern "C" int KDE_EXPORT kdemain(int argc, char **argv) +{ + KAboutData about("kiokdeconnect", "kdeconnect-kio", ki18n("kiokdeconnect"), "1.0"); + KCmdLineArgs::init(&about); + + KApplication app; + + if (argc != 4) { + fprintf(stderr, "Usage: kio_kdeconnect protocol pool app\n"); + exit(-1); + } + + KioKdeconnect slave(argv[2], argv[3]); + slave.dispatchLoop(); + return 0; +} + +//Some useful error mapping +KIO::Error toKioError(const QDBusError::ErrorType type) +{ + switch (type) + { + case QDBusError::NoError: + return KIO::Error(KJob::NoError); + case QDBusError::NoMemory: + return KIO::ERR_OUT_OF_MEMORY; + case QDBusError::Timeout: + return KIO::ERR_SERVER_TIMEOUT; + case QDBusError::TimedOut: + return KIO::ERR_SERVER_TIMEOUT; + default: + return KIO::ERR_INTERNAL; + }; +}; + +template <typename T> +bool handleDBusError(QDBusReply<T>& reply, KIO::SlaveBase* slave) +{ + if (!reply.isValid()) + { + kDebug(debugArea()) << "Error in DBus request:" << reply.error(); + slave->error(toKioError(reply.error().type()),reply.error().message()); + return true; + } + return false; +} + +KioKdeconnect::KioKdeconnect(const QByteArray &pool, const QByteArray &app) + : SlaveBase("kdeconnect", pool, app), + m_dbusInterface(new DaemonDbusInterface(this)) +{ + +} + +void KioKdeconnect::listAllDevices() +{ + infoMessage(i18n("Listing devices...")); + + //TODO: Change to all devices and show different icons for connected and disconnected? + QStringList devices = m_dbusInterface->devices(true, true); + + totalSize(devices.length()); + + int i = 0; + Q_FOREACH(const QString& deviceId, devices) { + + DeviceDbusInterface interface(deviceId); + + if (!interface.hasPlugin("kdeconnect_sftp")) continue; + + const QString target = QString("kdeconnect://").append(deviceId).append("/"); + const QString name = interface.name(); + const QString icon = "kdeconnect"; + + KIO::UDSEntry entry; + entry.insert(KIO::UDSEntry::UDS_NAME, name); + entry.insert(KIO::UDSEntry::UDS_ICON_NAME, icon); + entry.insert(KIO::UDSEntry::UDS_FILE_TYPE, S_IFDIR); + entry.insert(KIO::UDSEntry::UDS_ACCESS, S_IRUSR | S_IRGRP | S_IROTH); + entry.insert(KIO::UDSEntry::UDS_MIME_TYPE, ""); + entry.insert(KIO::UDSEntry::UDS_URL, target); + listEntry(entry, false); + + processedSize(i++); + + } + + listEntry(KIO::UDSEntry(), true); + infoMessage(""); + finished(); +} + +void KioKdeconnect::listDevice() +{ + infoMessage(i18n("Accessing device...")); + + kDebug(debugArea()) << "ListDevice" << m_currentDevice; + + SftpDbusInterface interface(m_currentDevice); + + QDBusReply<bool> mountreply = interface.mountAndWait(); + + if (handleDBusError(mountreply, this)) { + return; + } + + if (!mountreply.value()) { + error(KIO::ERR_COULD_NOT_MOUNT, i18n("Could not mount device filesystem")); + return; + } + + QDBusReply< QVariantMap > urlreply = interface.getDirectories(); + + if (handleDBusError(urlreply, this)) { + return; + } + + QVariantMap urls = urlreply.value(); + + for (QVariantMap::iterator it = urls.begin(); it != urls.end(); it++) { + + QString path = it.key(); + QString name = it.value().toString(); + + KIO::UDSEntry entry; + entry.insert(KIO::UDSEntry::UDS_NAME, "files"); + entry.insert(KIO::UDSEntry::UDS_DISPLAY_NAME, name); + entry.insert(KIO::UDSEntry::UDS_ICON_NAME, "folder"); + entry.insert(KIO::UDSEntry::UDS_FILE_TYPE, S_IFDIR); + entry.insert(KIO::UDSEntry::UDS_ACCESS, S_IRUSR | S_IRGRP | S_IROTH); + entry.insert(KIO::UDSEntry::UDS_MIME_TYPE, ""); + entry.insert(KIO::UDSEntry::UDS_URL, path); + listEntry(entry, false); + } + + listEntry(KIO::UDSEntry(), true); + infoMessage(""); + finished(); + +} + + + +void KioKdeconnect::listDir(const KUrl &url) +{ + kDebug(debugArea()) << "Listing..." << url; + + /// Url is not used here becuase all we could care about the url is the host, and that's already + /// handled in @p setHost + Q_UNUSED(url); + + if (!m_dbusInterface->isValid()) { + infoMessage(i18n("Could not contact background service.")); + listEntry(KIO::UDSEntry(), true); + finished(); + return; + } + + if (m_currentDevice.isEmpty()) { + listAllDevices(); + } else { + listDevice(); + } +} + +void KioKdeconnect::stat(const KUrl &url) +{ + kDebug(debugArea()) << "Stat: " << url; + + KIO::UDSEntry entry; + entry.insert(KIO::UDSEntry::UDS_FILE_TYPE, S_IFDIR); + statEntry(entry); + + finished(); +} + +void KioKdeconnect::get(const KUrl &url) +{ + kDebug(debugArea()) << "Get: " << url; + mimeType(""); + finished(); +} + +void KioKdeconnect::setHost(const QString &hostName, quint16 port, const QString &user, const QString &pass) +{ + + //This is called before everything else to set the file we want to show + + kDebug(debugArea()) << "Setting host: " << hostName; + + // In this kio only the hostname is used + Q_UNUSED(port) + Q_UNUSED(user) + Q_UNUSED(pass) + + m_currentDevice = hostName; + +} + diff --git a/pool/shard007/C++/0094838_sha1_win.cc b/pool/shard007/C++/0094838_sha1_win.cc new file mode 100644 index 0000000000000000000000000000000000000000..b64c9eb858322fcdc828d656326c0bdf63018e71 --- /dev/null +++ b/pool/shard007/C++/0094838_sha1_win.cc @@ -0,0 +1,67 @@ +// Copyright (c) 2011 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/sha1.h" + +#include <windows.h> +#include <wincrypt.h> + +// This file is not being compiled at the moment (see bug 47218). If we keep +// sha1 inside base, we cannot depend on src/crypto. +// #include "crypto/scoped_capi_types.h" +#include "base/logging.h" + +namespace base { + +std::string SHA1HashString(const std::string& str) { + ScopedHCRYPTPROV provider; + if (!CryptAcquireContext(provider.receive(), NULL, NULL, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT)) { + DPLOG(ERROR) << "CryptAcquireContext failed"; + return std::string(kSHA1Length, '\0'); + } + + { + ScopedHCRYPTHASH hash; + if (!CryptCreateHash(provider, CALG_SHA1, 0, 0, hash.receive())) { + DPLOG(ERROR) << "CryptCreateHash failed"; + return std::string(kSHA1Length, '\0'); + } + + if (!CryptHashData(hash, reinterpret_cast<CONST BYTE*>(str.data()), + static_cast<DWORD>(str.length()), 0)) { + DPLOG(ERROR) << "CryptHashData failed"; + return std::string(kSHA1Length, '\0'); + } + + DWORD hash_len = 0; + DWORD buffer_size = sizeof hash_len; + if (!CryptGetHashParam(hash, HP_HASHSIZE, + reinterpret_cast<unsigned char*>(&hash_len), + &buffer_size, 0)) { + DPLOG(ERROR) << "CryptGetHashParam(HP_HASHSIZE) failed"; + return std::string(kSHA1Length, '\0'); + } + + std::string result; + if (!CryptGetHashParam(hash, HP_HASHVAL, + // We need the + 1 here not because the call will write a trailing \0, + // but so that result.length() is correctly set to |hash_len|. + reinterpret_cast<BYTE*>(WriteInto(&result, hash_len + 1)), &hash_len, + 0))) { + DPLOG(ERROR) << "CryptGetHashParam(HP_HASHVAL) failed"; + return std::string(kSHA1Length, '\0'); + } + + if (hash_len != kSHA1Length) { + DLOG(ERROR) << "Returned hash value is wrong length: " << hash_len + << " should be " << kSHA1Length; + return std::string(kSHA1Length, '\0'); + } + + return result; + } +} + +} // namespace base diff --git a/pool/shard007/C++/0094840_variant_polymorphic_get_test.cpp b/pool/shard007/C++/0094840_variant_polymorphic_get_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..411f0af88daaabefb7456b83f1cb8a5684a5ca89 --- /dev/null +++ b/pool/shard007/C++/0094840_variant_polymorphic_get_test.cpp @@ -0,0 +1,81 @@ +//----------------------------------------------------------------------------- +// boost-libs variant/test/variant_plymorphic_get_test.cpp source file +// See http://www.boost.org for updates, documentation, and revision history. +//----------------------------------------------------------------------------- +// +// Copyright (c) 2003 Eric Friedman +// Copyright (c) 2013-2021 Antony Polukhin +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +#include "boost/variant/variant.hpp" +#include "boost/variant/apply_visitor.hpp" +#include "boost/variant/static_visitor.hpp" +#include "boost/variant/polymorphic_get.hpp" +#include "boost/core/lightweight_test.hpp" + +struct base {int trash;}; +struct derived1 : base{}; +struct derived2 : base{}; + +struct vbase { short trash; virtual ~vbase(){} virtual int foo() const { return 0; } }; +struct vderived1 : virtual vbase{ virtual int foo() const { return 1; } }; +struct vderived2 : virtual vbase{ virtual int foo() const { return 3; } }; +struct vderived3 : vderived1, vderived2 { virtual int foo() const { return 3; } }; + +template <class T, class Variant> +inline void check_throws(Variant& v) { + try { + boost::polymorphic_get<T>(v); + BOOST_TEST(false); + } catch (const boost::bad_polymorphic_get& e) { + BOOST_TEST(!!e.what()); + BOOST_TEST(std::string(e.what()) != boost::bad_get().what()); + } +} + +int main() +{ + typedef boost::variant<int, base, derived1, derived2> var_t; + + var_t var1; + BOOST_TEST(!boost::polymorphic_get<base>(&var1)); + check_throws<base>(var1); + BOOST_TEST(!boost::polymorphic_get<const base>(&var1)); + check_throws<base, const var_t>(var1); + + var1 = derived1(); + BOOST_TEST(boost::polymorphic_get<base>(&var1)); + BOOST_TEST(boost::polymorphic_get<const base>(&var1)); + + derived2 d; + d.trash = 777; + var_t var2 = d; + BOOST_TEST(boost::polymorphic_get<base>(var2).trash == 777); + BOOST_TEST(boost::polymorphic_get<const base>(var2).trash == 777); + + var2 = 777; + BOOST_TEST(!boost::polymorphic_get<base>(&var2)); + check_throws<base>(var2); + BOOST_TEST(!boost::polymorphic_get<const base>(&var2)); + check_throws<base, const var_t>(var2); + BOOST_TEST(boost::polymorphic_get<int>(var2) == 777); + BOOST_TEST(boost::polymorphic_get<const int>(var2) == 777); + + typedef boost::variant<int, vbase, vderived1, vderived2, vderived3> vvar_t; + + vvar_t v = vderived3(); + boost::polymorphic_get<vderived3>(v).trash = 777; + const vvar_t& cv = v; + BOOST_TEST(boost::polymorphic_get<vbase>(cv).trash == 777); + BOOST_TEST(boost::polymorphic_get<const vbase>(cv).trash == 777); + + BOOST_TEST(boost::polymorphic_get<vbase>(cv).foo() == 3); + BOOST_TEST(boost::polymorphic_get<vbase>(v).foo() == 3); + BOOST_TEST(boost::polymorphic_get<const vbase>(cv).foo() == 3); + BOOST_TEST(boost::polymorphic_get<const vbase>(v).foo() == 3); + + return boost::report_errors(); +} diff --git a/pool/shard007/C++/0094843_Player.cpp b/pool/shard007/C++/0094843_Player.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ae7583749e95b32c9a87bf329b5d0071814690dc --- /dev/null +++ b/pool/shard007/C++/0094843_Player.cpp @@ -0,0 +1,70 @@ +#include "Player.hpp" + +#include "Game.hpp" + +#include <map> + +#include <VirtualGameConsole/VGCClock.h> +#include <VirtualGameConsole/VGCKeyboard.h> + +static const int PLAYER_SPEED = 5; +static const int BULLET_SPEED = 10; + +static const int BULLET_DAMAGE = 10; +static const double BULLET_FIRE_RATE = 0.2; + +static const std::map<VGCKey, VGCVector> MovementKeys = { + { VGCKey::ARROW_LEFT_KEY, {-1, 0 } }, + { VGCKey::ARROW_UP_KEY, { 0, -1 } }, + { VGCKey::ARROW_RIGHT_KEY, { 1, 0 } }, + { VGCKey::ARROW_DOWN_KEY, { 0, 1 } } +}; + +static const VGCVector BulletDirections[3] = { + {-1, -1}, {0, -1}, {1, -1} +}; + +Player::Player(Game* game, VGCVector size, VGCVector position) + : game(game), size(size), position(position) {} + +void Player::Update() { + auto bullet = bullets.begin(); + + while (bullet != bullets.end()) { + bullet->position += bullet->direction * bullet->speed; + + if (game->CheckIfBulletHitEnemy(*bullet)) { + bullet = bullets.erase(bullet); + } + else { + ++bullet; + } + } + + if (VGCKeyboard::isPressed(VGCKey::SPACE_KEY) && (VGCClock::getTime() - lastFire) >= BULLET_FIRE_RATE) { + lastFire = VGCClock::getTime(); + + // Pew pew pew. + for (auto const &dir : BulletDirections) { + VGCVector playerFrontCenter = position + VGCVector(size.getX() / 2, 0); + bullets.emplace_back(playerFrontCenter, dir, BULLET_DAMAGE, BULLET_SPEED); + } + } + + VGCVector newPos = position; + + for (auto const &key : MovementKeys) { + if (VGCKeyboard::isPressed(key.first)) { + newPos += key.second * PLAYER_SPEED; + } + } + + // Boundary collision detection. + if (newPos.getX() >= 0 && newPos.getX() < (game->windowSize.getX() - size.getX())) { + position.setX(newPos.getX()); + } + + if (newPos.getY() >= 0 && newPos.getY() < (game->windowSize.getY() - size.getY())) { + position.setY(newPos.getY()); + } +} diff --git a/pool/shard007/C++/0094846_EdLevelResourcesWindow.cpp b/pool/shard007/C++/0094846_EdLevelResourcesWindow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..904baaba7e2332033fa410a3b0c5e2f52fe3eb0c --- /dev/null +++ b/pool/shard007/C++/0094846_EdLevelResourcesWindow.cpp @@ -0,0 +1,170 @@ +//============================================================================== +/// +/// File: EdLevelResourcesWindow.cpp +/// +/// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved. +/// +/// This file is subject to the terms and conditions defined in +/// file 'LICENSE.txt', which is part of this source code package. +/// +//============================================================================== + +// Editor include +#include "EdLevelResourcesWindow.hpp" +#include "EdLevelDocument.hpp" +#include "EdLevelResourceImage.hpp" +#include "EdLevelResourceSound.hpp" + +// Qt include +#include <QtWidgets/QHeaderView> +#include <QtCore/QFileInfo> +#include <QtCore/QDateTime> + +// Engine includes +#include "DT3Core/Types/Utility/DirectoryLister.hpp" +#include "DT3Core/Types/Utility/MoreStrings.hpp" +#include "DT3Core/Resources/Importers/ImporterImage.hpp" +#include "DT3Core/Resources/Importers/ImporterSound.hpp" +#include "DT3Core/Resources/Importers/ImporterMaterial.hpp" +#include "DT3Core/System/Factory.hpp" + +//============================================================================== +//============================================================================== + +using namespace DT3; + +//============================================================================== +//============================================================================== + +EdLevelResourcesWindow::EdLevelResourcesWindow(QWidget *parent, QToolBar *toolbar, EdLevelDocument *document, QGLWidget *gl) + : QTreeWidget (parent) +{ + _document = document; + _toolbar = toolbar; + + _gl = gl; + + setSelectionMode(QAbstractItemView::ExtendedSelection); + setSelectionBehavior(QAbstractItemView::SelectRows); + + setDragEnabled(true); + setAcceptDrops(false); + //setDropIndicatorShown(true); + + setColumnCount(3); + + setAlternatingRowColors(true); + + QTreeWidgetItem *header_item = new QTreeWidgetItem(); + header_item->setText(0, "Name"); + header_item->setText(1, "Size"); + header_item->setText(2, "Modification Date"); + header_item->setFlags (0); + + setHeaderItem (header_item); + header()->resizeSection(0, 220); + + + onRefreshResources(); +} + +//============================================================================== +//============================================================================== + +QMimeData* EdLevelResourcesWindow::mimeData (const QList<QTreeWidgetItem *> items) const +{ + if (items.size() == 0) + return NULL; + + QMimeData *mime = new QMimeData(); + + FOR_EACH (i,items) { + QString data = (**i).data(0,Qt::UserRole).toString(); + mime->setText(data); + } + + return mime; +} + +//============================================================================== +//============================================================================== + +void EdLevelResourcesWindow::buildTree (QTreeWidgetItem *parent, const FilePath &dir) +{ + + DirectoryLister lister; + lister.scan_path(dir, false); // Include dirs, not recursive + + for (DTuint i = 0; i < lister.num_files(); ++i) { + QTreeWidgetItem *item = new QTreeWidgetItem(); + item->setData(0, Qt::UserRole, QString("{") + QString(lister.file_name(i).c_str()) + QString("}") ); + parent->addChild(item); + + // A little heavy - see if there's an importer by trying to create one + std::shared_ptr<BaseClass> importer = Factory::create_importer(lister.file_path(i).file_ext()); + + // Figure out which widget to use based on the file kind + if (importer && importer->isa(ImporterImage::kind())) { + EdLevelResourceImage *itemWidget = new EdLevelResourceImage(lister.file_path(i)); + + setItemWidget(item,0,itemWidget); + item->setSizeHint(0,itemWidget->minimumSize()); + + } else if (importer && importer->isa(ImporterSound::kind())) { + EdLevelResourceSound *itemWidget = new EdLevelResourceSound(lister.file_path(i)); + + setItemWidget(item,0,itemWidget); + item->setSizeHint(0,itemWidget->minimumSize()); + + } else { + item->setText(0, lister.file_path(i).file_name().c_str() ); + } + + // Add meta info + QFileInfo file_info(lister.file_path(i).full_path().c_str()); + + // Size + if (file_info.size() < 1024) + item->setText(1, (MoreStrings::cast_to_string(file_info.size()) + " bytes").c_str() ); + else + item->setText(1, (MoreStrings::cast_to_string(file_info.size()/1024.0F) + " kb").c_str() ); + + // Modification + item->setText(2, file_info.lastModified().toString("ddd MMMM d, yyyy") ); + + // Recurse + if (lister.is_directory(i)) + buildTree( item, lister.file_path(i) ); + + /*ResourceCache c; + c._path = lister.getFilePath(i); + _resource_cache.pushBack(c);*/ + + } + +} + +//============================================================================== +//============================================================================== + +void EdLevelResourcesWindow::onRefreshResources (void) +{ + clear(); + + QTreeWidgetItem *root_item = invisibleRootItem(); + root_item->setFlags (0); + + _top_level = new QTreeWidgetItem(); + _top_level->setText(0, "Resources"); + //_top_level->setFlags (Qt::ItemIsDropEnabled | Qt::ItemIsEnabled | Qt::ItemIsSelectable); + + addTopLevelItem(_top_level); + + buildTree(_top_level, FilePath("{ED_DATA_PATH}")); +} + +//============================================================================== +//============================================================================== + +#include "moc_EdLevelResourcesWindow.cpp" + diff --git a/pool/shard007/C++/0094847_ReadHpcgDat.cpp b/pool/shard007/C++/0094847_ReadHpcgDat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6657acfae4aaec3721420ecf45d8b6a24ed0fb4c --- /dev/null +++ b/pool/shard007/C++/0094847_ReadHpcgDat.cpp @@ -0,0 +1,66 @@ + +//@HEADER +// *************************************************** +// +// HPCG: High Performance Conjugate Gradient Benchmark +// +// Contact: +// Michael A. Heroux ( maherou@sandia.gov) +// Jack Dongarra (dongarra@eecs.utk.edu) +// Piotr Luszczek (luszczek@eecs.utk.edu) +// +// *************************************************** +//@HEADER + +#include <cstdio> + +#include "ReadHpcgDat.hpp" + +static int +SkipUntilEol(FILE *stream) { + int chOrEof; + bool finished; + + do { + chOrEof = fgetc( stream ); + finished = (chOrEof == EOF) || (chOrEof == '\n') || (chOrEof == '\r'); + } while (! finished); + + if ('\r' == chOrEof) { // on Windows, \r might be followed by \n + int chOrEofExtra = fgetc( stream ); + + if ('\n' == chOrEofExtra || EOF == chOrEofExtra) + chOrEof = chOrEofExtra; + else + ungetc(chOrEofExtra, stream); + } + + return chOrEof; +} + +int +ReadHpcgDat(int *localDimensions, int *secondsPerRun) { + FILE * hpcgStream = fopen("hpcg.dat", "r"); + + if (! hpcgStream) + return -1; + + SkipUntilEol(hpcgStream); // skip the first line + + SkipUntilEol(hpcgStream); // skip the second line + + for (int i = 0; i < 3; ++i) + if (fscanf(hpcgStream, "%d", localDimensions+i) != 1 || localDimensions[i] < 16) + localDimensions[i] = 16; + + SkipUntilEol( hpcgStream ); // skip the rest of the second line + + if (secondsPerRun!=0) { // Only read number of seconds if the pointer is non-zero + if (fscanf(hpcgStream, "%d", secondsPerRun) != 1 || secondsPerRun[0] < 0) + secondsPerRun[0] = 30 * 60; // 30 minutes + } + + fclose(hpcgStream); + + return 0; +} diff --git a/pool/shard007/C++/0094849_node-intersection.cpp b/pool/shard007/C++/0094849_node-intersection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..23a39a09cbc73d81c9b2dda3feb903370ca98233 --- /dev/null +++ b/pool/shard007/C++/0094849_node-intersection.cpp @@ -0,0 +1,32 @@ +/* This file is part of Dilay + * Copyright © 2015-2018 Alexander Bau + * Use and redistribute under the terms of the GNU General Public License + */ +#include "sketch/mesh.hpp" +#include "sketch/node-intersection.hpp" + +SketchNodeIntersection::SketchNodeIntersection () + : _node (nullptr) +{ +} + +bool SketchNodeIntersection::update (float d, const glm::vec3& p, const glm::vec3& n, + SketchMesh& mesh, SketchNode& node) +{ + if (this->SketchMeshIntersection::update (d, p, n, mesh)) + { + this->_node = &node; + return true; + } + else + { + return false; + } +} + +SketchNode& SketchNodeIntersection::node () const +{ + assert (this->isIntersection ()); + assert (this->_node); + return *this->_node; +} diff --git a/pool/shard007/C++/0094852_policy_manager.cc b/pool/shard007/C++/0094852_policy_manager.cc new file mode 100644 index 0000000000000000000000000000000000000000..de3ecb0f82b2ddfe5725ceed7b479bd46fc06454 --- /dev/null +++ b/pool/shard007/C++/0094852_policy_manager.cc @@ -0,0 +1,67 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +#include "policy_manager.h" + +PromotionPolicy * +PolicyManager::coalescePolicy(PromotionPolicy *policy) +{ + std::string tag = policy->id(); + + if (tag.size() != 0) { + auto res = _policies.find(tag); + + TSDebug(PLUGIN_NAME, "looking up policy by tag: %s", tag.c_str()); + + if (res != _policies.end()) { + TSDebug(PLUGIN_NAME, "repurposing policy for tag: %s", tag.c_str()); + + ++res->second.second; + // Repurpose the existing policy, nuking this placeholder. + delete policy; + return res->second.first; + } else { + TSDebug(PLUGIN_NAME, "inserting policy for tag: %s", tag.c_str()); + _policies[tag] = std::make_pair(policy, 1); + } + } + + return policy; +} + +void +PolicyManager::releasePolicy(PromotionPolicy *policy) +{ + std::string tag = policy->id(); + + if (tag.size() != 0) { + auto res = _policies.find(tag); + + if (res != _policies.end()) { + if (0 == --res->second.second) { + TSDebug(PLUGIN_NAME, "releasing unused PromotionPolicy"); + delete res->second.first; + _policies.erase(res); + } + } else { + TSAssert(!"Trying to release a policy which was not acquired via PolicyManager"); + } + } else { + // Not managed by the policy manager, so just nuke it. + delete policy; + } +} diff --git a/pool/shard007/C++/0094853_rpcdump.cpp b/pool/shard007/C++/0094853_rpcdump.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0742d8321dbb3302ff646187ed377f027b287ee9 --- /dev/null +++ b/pool/shard007/C++/0094853_rpcdump.cpp @@ -0,0 +1,96 @@ +// Copyright (c) 2009-2012 Bitcoin Developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "init.h" // for pwalletMain +#include "bitcoinrpc.h" +#include "ui_interface.h" +#include "base58.h" + +#include <boost/lexical_cast.hpp> + +#define printf OutputDebugStringF + +using namespace json_spirit; +using namespace std; + +class CTxDump +{ +public: + CBlockIndex *pindex; + int64 nValue; + bool fSpent; + CWalletTx* ptx; + int nOut; + CTxDump(CWalletTx* ptx = NULL, int nOut = -1) + { + pindex = NULL; + nValue = 0; + fSpent = false; + this->ptx = ptx; + this->nOut = nOut; + } +}; + +Value importprivkey(const Array& params, bool fHelp) +{ + if (fHelp || params.size() < 1 || params.size() > 3) + throw runtime_error( + "importprivkey <Uroprivkey> [label] [rescan=true]\n" + "Adds a private key (as returned by dumpprivkey) to your wallet."); + + string strSecret = params[0].get_str(); + string strLabel = ""; + if (params.size() > 1) + strLabel = params[1].get_str(); + + // Whether to perform rescan after import + bool fRescan = true; + if (params.size() > 2) + fRescan = params[2].get_bool(); + + CBitcoinSecret vchSecret; + bool fGood = vchSecret.SetString(strSecret); + + if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); + + CKey key = vchSecret.GetKey(); + CPubKey pubkey = key.GetPubKey(); + CKeyID vchAddress = pubkey.GetID(); + { + LOCK2(cs_main, pwalletMain->cs_wallet); + + pwalletMain->MarkDirty(); + pwalletMain->SetAddressBookName(vchAddress, strLabel); + + if (!pwalletMain->AddKeyPubKey(key, pubkey)) + throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); + + if (fRescan) { + pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); + pwalletMain->ReacceptWalletTransactions(); + } + } + + return Value::null; +} + +Value dumpprivkey(const Array& params, bool fHelp) +{ + if (fHelp || params.size() != 1) + throw runtime_error( + "dumpprivkey <Uroaddress>\n" + "Reveals the private key corresponding to <Uroaddress>."); + + string strAddress = params[0].get_str(); + CBitcoinAddress address; + if (!address.SetString(strAddress)) + throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Uro address"); + CKeyID keyID; + if (!address.GetKeyID(keyID)) + throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); + CKey vchSecret; + if (!pwalletMain->GetKey(keyID, vchSecret)) + throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); + return CBitcoinSecret(vchSecret).ToString(); +} diff --git a/pool/shard007/C++/0094856_btbookshelfview.cpp b/pool/shard007/C++/0094856_btbookshelfview.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1a04effe21f470d561b243682bd8acff7a78df00 --- /dev/null +++ b/pool/shard007/C++/0094856_btbookshelfview.cpp @@ -0,0 +1,111 @@ +/********* +* +* In the name of the Father, and of the Son, and of the Holy Spirit. +* +* This file is part of BibleTime's source code, http://www.bibletime.info/. +* +* Copyright 1999-2014 by the BibleTime developers. +* The BibleTime source code is licensed under the GNU General Public License +* version 2.0. +* +**********/ + +#include "frontend/btbookshelfview.h" + +#include <QApplication> +#include <QMouseEvent> +#include "backend/bookshelfmodel/btbookshelftreemodel.h" +#include "backend/drivers/cswordmoduleinfo.h" + + +BtBookshelfView::BtBookshelfView(QWidget *parent) + : QTreeView(parent) +{ + setHeaderHidden(true); + + /* + Uncommenting the following statement will hide the [+]expand/[-]collapse + controls in front of first-level items, which might not be desirable since + hiding them also means that one has to do a total of 2 clicks (double- + click)to expand or collapse top-level items: + */ + // setRootIsDecorated(false); + + connect(this, SIGNAL(activated(QModelIndex)), + this, SLOT(slotItemActivated(QModelIndex))); + connect(this, SIGNAL(entered(QModelIndex)), + this, SLOT(slotItemHovered(QModelIndex))); +} + +CSwordModuleInfo * BtBookshelfView::getModule(const QModelIndex & index) const { + void * const module = model()->data(index, + BtBookshelfModel::ModulePointerRole).value<void *>(); + return static_cast<CSwordModuleInfo *>(module); +} + +void BtBookshelfView::keyPressEvent(QKeyEvent *event) { + switch (event->key()) { + case Qt::Key_Menu: + scrollTo(currentIndex()); + { + CSwordModuleInfo *i(getModule(currentIndex())); + QRect itemRect(visualRect(currentIndex())); + QPoint p(viewport()->mapToGlobal(itemRect.bottomLeft())); + if (i == 0) { + emit contextMenuActivated(p); + } + else { + emit moduleContextMenuActivated(i, p); + } + } + event->accept(); + break; + case Qt::Key_Return: + case Qt::Key_Enter: { + QModelIndex i(currentIndex()); + CSwordModuleInfo *m(getModule(i)); + if (m != 0) { + emit moduleActivated(m); + } + else { + setExpanded(i, !isExpanded(i)); + } + } + event->accept(); + break; + default: + QTreeView::keyPressEvent(event); + break; + } +} + +void BtBookshelfView::mousePressEvent(QMouseEvent *event) { + if (event->buttons() == Qt::RightButton) { + QModelIndex clickedItemIndex(indexAt(event->pos())); + if (clickedItemIndex.isValid()) { + setCurrentIndex(clickedItemIndex); + } + CSwordModuleInfo *i(getModule(clickedItemIndex)); + if (i == 0) { + emit contextMenuActivated(mapToGlobal(event->pos())); + } + else { + emit moduleContextMenuActivated(i, mapToGlobal(event->pos())); + } + event->accept(); + } + else { + QTreeView::mousePressEvent(event); + } +} + +void BtBookshelfView::slotItemActivated(const QModelIndex &index) { + CSwordModuleInfo *i(getModule(index)); + if (i != 0) { + emit moduleActivated(i); + } +} + +void BtBookshelfView::slotItemHovered(const QModelIndex &index) { + emit moduleHovered(getModule(index)); +} diff --git a/pool/shard007/C++/0094857_MultiPrintDOC.cpp b/pool/shard007/C++/0094857_MultiPrintDOC.cpp new file mode 100644 index 0000000000000000000000000000000000000000..49125e1e2d8c091c3ad21141b1f436ee9e89dad4 --- /dev/null +++ b/pool/shard007/C++/0094857_MultiPrintDOC.cpp @@ -0,0 +1,101 @@ +// MultiPrintDoc.cpp : implementation of the CMultiPrintDoc class +// + +#include "stdafx.h" +#include "MultiPrint.h" + +#include "MultiPrintDoc.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CMultiPrintDoc + +IMPLEMENT_DYNCREATE(CMultiPrintDoc, CDocument) + +BEGIN_MESSAGE_MAP(CMultiPrintDoc, CDocument) + //{{AFX_MSG_MAP(CMultiPrintDoc) + // NOTE - the ClassWizard will add and remove mapping macros here. + // DO NOT EDIT what you see in these blocks of generated code! + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CMultiPrintDoc construction/destruction + +CMultiPrintDoc::CMultiPrintDoc() +{ + // TODO: add one-time construction code here + m_LinePerPage=6;//ÿҳ´òÓ¡6ÐÐ +} + +CMultiPrintDoc::~CMultiPrintDoc() +{ +} + +BOOL CMultiPrintDoc::OnNewDocument() +{ + if (!CDocument::OnNewDocument()) + return FALSE; + + // TODO: add reinitialization code here + // (SDI documents will reuse this document) + m_stringArray.SetSize(16); + m_stringArray[0]="ÇáÇáµÄÎÒ×ßÁË£¬"; + m_stringArray[1]="ÕýÈçÎÒÇáÇáµÄÀ´£»"; + m_stringArray[2]="ÎÒÇáÇáµØÕÐÊÖ£¬"; + m_stringArray[3]="×÷±ðÎ÷ÌìµÄÔÆ²Ê¡£"; + m_stringArray[4]="ÄǺÓÅϵĽðÁø£¬"; + m_stringArray[5]="ÊÇϦÑôÖеÄÐÂÄ"; + m_stringArray[6]="²¨¹âÀïµÄÑÞÓ°£¬"; + m_stringArray[7]="ÔÚÎÒÐÄÍ·µ´Ñú¡£"; + m_stringArray[8]="ÈíÄàÉϵÄÇàÜô£¬"; + m_stringArray[9]="ÓÍÓ͵ÄÔÚË®µ×ÕÐÒ¡£»"; + m_stringArray[10]="ÔÚ¿µºÓµÄÈᲨÀ"; + m_stringArray[11]="ÎÒ¸ÊÐÄ×öÒ»ÌõË®²Ý¡£"; + m_stringArray[12]="ÄÇÓÜÒñϵÄһ̶£¬"; + m_stringArray[13]="²»ÊÇÇåȪ£¬ÊÇÌìÉϺ磻"; + m_stringArray[14]="ÈàËéµÄ¸¡Ôå¼ä£¬"; + m_stringArray[15]="³Áµí×ŲʺçËÆµÄÃΡ£"; + + return TRUE; +} + + + +///////////////////////////////////////////////////////////////////////////// +// CMultiPrintDoc serialization + +void CMultiPrintDoc::Serialize(CArchive& ar) +{ + if (ar.IsStoring()) + { + // TODO: add storing code here + } + else + { + // TODO: add loading code here + } +} + +///////////////////////////////////////////////////////////////////////////// +// CMultiPrintDoc diagnostics + +#ifdef _DEBUG +void CMultiPrintDoc::AssertValid() const +{ + CDocument::AssertValid(); +} + +void CMultiPrintDoc::Dump(CDumpContext& dc) const +{ + CDocument::Dump(dc); +} +#endif //_DEBUG + +///////////////////////////////////////////////////////////////////////////// +// CMultiPrintDoc commands diff --git a/pool/shard007/C++/0094859_rand_test.cc b/pool/shard007/C++/0094859_rand_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..9c69b8f63863d4e0864de3984caccae0c77da397 --- /dev/null +++ b/pool/shard007/C++/0094859_rand_test.cc @@ -0,0 +1,207 @@ +/* Copyright (c) 2018, Google Inc. + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION + * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ + +#include <openssl/rand.h> + +#include <stdio.h> + +#include <gtest/gtest.h> + +#include <openssl/cpu.h> +#include <openssl/span.h> + +#include "../fipsmodule/rand/internal.h" +#include "../test/abi_test.h" +#include "../test/test_util.h" + +#if defined(OPENSSL_THREADS) +#include <array> +#include <thread> +#include <vector> +#endif + +#if !defined(OPENSSL_WINDOWS) +#include <errno.h> +#include <sys/types.h> +#include <sys/wait.h> +#include <unistd.h> +#endif + + +// These tests are, strictly speaking, flaky, but we use large enough buffers +// that the probability of failing when we should pass is negligible. + +TEST(RandTest, NotObviouslyBroken) { + static const uint8_t kZeros[256] = {0}; + + uint8_t buf1[256], buf2[256]; + RAND_bytes(buf1, sizeof(buf1)); + RAND_bytes(buf2, sizeof(buf2)); + + EXPECT_NE(Bytes(buf1), Bytes(buf2)); + EXPECT_NE(Bytes(buf1), Bytes(kZeros)); + EXPECT_NE(Bytes(buf2), Bytes(kZeros)); +} + +#if !defined(OPENSSL_WINDOWS) && !defined(OPENSSL_IOS) && \ + !defined(OPENSSL_FUCHSIA) && !defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE) +static bool ForkAndRand(bssl::Span<uint8_t> out) { + int pipefds[2]; + if (pipe(pipefds) < 0) { + perror("pipe"); + return false; + } + + // This is a multi-threaded process, but GTest does not run tests concurrently + // and there currently are no threads, so this should be safe. + pid_t child = fork(); + if (child < 0) { + perror("fork"); + close(pipefds[0]); + close(pipefds[1]); + return false; + } + + if (child == 0) { + // This is the child. Generate entropy and write it to the parent. + close(pipefds[0]); + RAND_bytes(out.data(), out.size()); + while (!out.empty()) { + ssize_t ret = write(pipefds[1], out.data(), out.size()); + if (ret < 0) { + if (errno == EINTR) { + continue; + } + perror("write"); + _exit(1); + } + out = out.subspan(static_cast<size_t>(ret)); + } + _exit(0); + } + + // This is the parent. Read the entropy from the child. + close(pipefds[1]); + while (!out.empty()) { + ssize_t ret = read(pipefds[0], out.data(), out.size()); + if (ret <= 0) { + if (ret == 0) { + fprintf(stderr, "Unexpected EOF from child.\n"); + } else { + if (errno == EINTR) { + continue; + } + perror("read"); + } + close(pipefds[0]); + return false; + } + out = out.subspan(static_cast<size_t>(ret)); + } + close(pipefds[0]); + + // Wait for the child to exit. + int status; + if (waitpid(child, &status, 0) < 0) { + perror("waitpid"); + return false; + } + if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { + fprintf(stderr, "Child did not exit cleanly.\n"); + return false; + } + + return true; +} + +TEST(RandTest, Fork) { + static const uint8_t kZeros[16] = {0}; + + // Draw a little entropy to initialize any internal PRNG buffering. + uint8_t byte; + RAND_bytes(&byte, 1); + + // Draw entropy in two child processes and the parent process. This test + // intentionally uses smaller buffers than the others, to minimize the chance + // of sneaking by with a large enough buffer that we've since reseeded from + // the OS. + uint8_t buf1[16], buf2[16], buf3[16]; + ASSERT_TRUE(ForkAndRand(buf1)); + ASSERT_TRUE(ForkAndRand(buf2)); + RAND_bytes(buf3, sizeof(buf3)); + + // All should be different. + EXPECT_NE(Bytes(buf1), Bytes(buf2)); + EXPECT_NE(Bytes(buf2), Bytes(buf3)); + EXPECT_NE(Bytes(buf1), Bytes(buf3)); + EXPECT_NE(Bytes(buf1), Bytes(kZeros)); + EXPECT_NE(Bytes(buf2), Bytes(kZeros)); + EXPECT_NE(Bytes(buf3), Bytes(kZeros)); +} +#endif // !OPENSSL_WINDOWS && !OPENSSL_IOS && + // !OPENSSL_FUCHSIA && !BORINGSSL_UNSAFE_DETERMINISTIC_MODE + +#if defined(OPENSSL_THREADS) +static void RunConcurrentRands(size_t num_threads) { + static const uint8_t kZeros[256] = {0}; + + std::vector<std::array<uint8_t, 256>> bufs(num_threads); + std::vector<std::thread> threads(num_threads); + + for (size_t i = 0; i < num_threads; i++) { + threads[i] = + std::thread([i, &bufs] { RAND_bytes(bufs[i].data(), bufs[i].size()); }); + } + for (size_t i = 0; i < num_threads; i++) { + threads[i].join(); + } + + for (size_t i = 0; i < num_threads; i++) { + EXPECT_NE(Bytes(bufs[i]), Bytes(kZeros)); + for (size_t j = i + 1; j < num_threads; j++) { + EXPECT_NE(Bytes(bufs[i]), Bytes(bufs[j])); + } + } +} + +// Test that threads may concurrently draw entropy without tripping TSan. +TEST(RandTest, Threads) { + constexpr size_t kFewerThreads = 10; + constexpr size_t kMoreThreads = 20; + + // Draw entropy in parallel. + RunConcurrentRands(kFewerThreads); + // Draw entropy in parallel with higher concurrency than the previous maximum. + RunConcurrentRands(kMoreThreads); + // Draw entropy in parallel with lower concurrency than the previous maximum. + RunConcurrentRands(kFewerThreads); +} +#endif // OPENSSL_THREADS + +#if defined(OPENSSL_X86_64) && defined(SUPPORTS_ABI_TEST) +TEST(RandTest, RdrandABI) { + if (!have_rdrand()) { + fprintf(stderr, "rdrand not supported. Skipping.\n"); + return; + } + + uint8_t buf[32]; + CHECK_ABI_SEH(CRYPTO_rdrand, buf); + CHECK_ABI_SEH(CRYPTO_rdrand_multiple8_buf, nullptr, 0); + CHECK_ABI_SEH(CRYPTO_rdrand_multiple8_buf, buf, 8); + CHECK_ABI_SEH(CRYPTO_rdrand_multiple8_buf, buf, 16); + CHECK_ABI_SEH(CRYPTO_rdrand_multiple8_buf, buf, 24); + CHECK_ABI_SEH(CRYPTO_rdrand_multiple8_buf, buf, 32); +} +#endif // OPENSSL_X86_64 && SUPPORTS_ABI_TEST diff --git a/pool/shard007/C++/0094860_DeleteLaunchTemplateVersionsRequest.cpp b/pool/shard007/C++/0094860_DeleteLaunchTemplateVersionsRequest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fb39d5a64045c0469644e5310cb235dd254321a5 --- /dev/null +++ b/pool/shard007/C++/0094860_DeleteLaunchTemplateVersionsRequest.cpp @@ -0,0 +1,60 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include <aws/ec2/model/DeleteLaunchTemplateVersionsRequest.h> +#include <aws/core/utils/StringUtils.h> +#include <aws/core/utils/memory/stl/AWSStringStream.h> + +using namespace Aws::EC2::Model; +using namespace Aws::Utils; + +DeleteLaunchTemplateVersionsRequest::DeleteLaunchTemplateVersionsRequest() : + m_dryRun(false), + m_dryRunHasBeenSet(false), + m_launchTemplateIdHasBeenSet(false), + m_launchTemplateNameHasBeenSet(false), + m_versionsHasBeenSet(false) +{ +} + +Aws::String DeleteLaunchTemplateVersionsRequest::SerializePayload() const +{ + Aws::StringStream ss; + ss << "Action=DeleteLaunchTemplateVersions&"; + if(m_dryRunHasBeenSet) + { + ss << "DryRun=" << std::boolalpha << m_dryRun << "&"; + } + + if(m_launchTemplateIdHasBeenSet) + { + ss << "LaunchTemplateId=" << StringUtils::URLEncode(m_launchTemplateId.c_str()) << "&"; + } + + if(m_launchTemplateNameHasBeenSet) + { + ss << "LaunchTemplateName=" << StringUtils::URLEncode(m_launchTemplateName.c_str()) << "&"; + } + + if(m_versionsHasBeenSet) + { + unsigned versionsCount = 1; + for(auto& item : m_versions) + { + ss << "LaunchTemplateVersion." << versionsCount << "=" + << StringUtils::URLEncode(item.c_str()) << "&"; + versionsCount++; + } + } + + ss << "Version=2016-11-15"; + return ss.str(); +} + + +void DeleteLaunchTemplateVersionsRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const +{ + uri.SetQueryString(SerializePayload()); +} diff --git a/pool/shard007/C++/0094867_DHT_U.cpp b/pool/shard007/C++/0094867_DHT_U.cpp new file mode 100644 index 0000000000000000000000000000000000000000..efc7963c1a285a2aed8ee76e861e43422aad5c80 --- /dev/null +++ b/pool/shard007/C++/0094867_DHT_U.cpp @@ -0,0 +1,179 @@ +// DHT Temperature & Humidity Unified Sensor Library +// Copyright (c) 2014 Adafruit Industries +// Author: Tony DiCola + +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +#include "DHT_U.h" + +DHT_Unified::DHT_Unified(uint8_t pin, uint8_t type, uint8_t count, int32_t tempSensorId, int32_t humiditySensorId): + _dht(pin, type, count), + _type(type), + _temp(this, tempSensorId), + _humidity(this, humiditySensorId) +{} + +void DHT_Unified::begin() { + _dht.begin(); +} + +void DHT_Unified::setName(sensor_t* sensor) { + switch(_type) { + case DHT11: + strncpy(sensor->name, "DHT11", sizeof(sensor->name) - 1); + break; + case DHT21: + strncpy(sensor->name, "DHT21", sizeof(sensor->name) - 1); + break; + case DHT22: + strncpy(sensor->name, "DHT22", sizeof(sensor->name) - 1); + break; + default: + // TODO: Perhaps this should be an error? However main DHT library doesn't enforce + // restrictions on the sensor type value. Pick a generic name for now. + strncpy(sensor->name, "DHT?", sizeof(sensor->name) - 1); + break; + } + sensor->name[sizeof(sensor->name)- 1] = 0; +} + +void DHT_Unified::setMinDelay(sensor_t* sensor) { + switch(_type) { + case DHT11: + sensor->min_delay = 1000000L; // 1 second (in microseconds) + break; + case DHT21: + sensor->min_delay = 2000000L; // 2 seconds (in microseconds) + break; + case DHT22: + sensor->min_delay = 2000000L; // 2 seconds (in microseconds) + break; + default: + // Default to slowest sample rate in case of unknown type. + sensor->min_delay = 2000000L; // 2 seconds (in microseconds) + break; + } +} + +DHT_Unified::Temperature::Temperature(DHT_Unified* parent, int32_t id): + _parent(parent), + _id(id) +{} + +bool DHT_Unified::Temperature::getEvent(sensors_event_t* event) { + // Clear event definition. + memset(event, 0, sizeof(sensors_event_t)); + // Populate sensor reading values. + event->version = sizeof(sensors_event_t); + event->sensor_id = _id; + event->type = SENSOR_TYPE_AMBIENT_TEMPERATURE; + event->timestamp = millis(); + event->temperature = _parent->_dht.readTemperature(); + + return true; +} + +void DHT_Unified::Temperature::getSensor(sensor_t* sensor) { + // Clear sensor definition. + memset(sensor, 0, sizeof(sensor_t)); + // Set sensor name. + _parent->setName(sensor); + // Set version and ID + sensor->version = DHT_SENSOR_VERSION; + sensor->sensor_id = _id; + // Set type and characteristics. + sensor->type = SENSOR_TYPE_AMBIENT_TEMPERATURE; + _parent->setMinDelay(sensor); + switch (_parent->_type) { + case DHT11: + sensor->max_value = 50.0F; + sensor->min_value = 0.0F; + sensor->resolution = 2.0F; + break; + case DHT21: + sensor->max_value = 80.0F; + sensor->min_value = -40.0F; + sensor->resolution = 0.1F; + break; + case DHT22: + sensor->max_value = 125.0F; + sensor->min_value = -40.0F; + sensor->resolution = 0.1F; + break; + default: + // Unknown type, default to 0. + sensor->max_value = 0.0F; + sensor->min_value = 0.0F; + sensor->resolution = 0.0F; + break; + } +} + +DHT_Unified::Humidity::Humidity(DHT_Unified* parent, int32_t id): + _parent(parent), + _id(id) +{} + +bool DHT_Unified::Humidity::getEvent(sensors_event_t* event) { + // Clear event definition. + memset(event, 0, sizeof(sensors_event_t)); + // Populate sensor reading values. + event->version = sizeof(sensors_event_t); + event->sensor_id = _id; + event->type = SENSOR_TYPE_RELATIVE_HUMIDITY; + event->timestamp = millis(); + event->relative_humidity = _parent->_dht.readHumidity(); + + return true; +} + +void DHT_Unified::Humidity::getSensor(sensor_t* sensor) { + // Clear sensor definition. + memset(sensor, 0, sizeof(sensor_t)); + // Set sensor name. + _parent->setName(sensor); + // Set version and ID + sensor->version = DHT_SENSOR_VERSION; + sensor->sensor_id = _id; + // Set type and characteristics. + sensor->type = SENSOR_TYPE_RELATIVE_HUMIDITY; + _parent->setMinDelay(sensor); + switch (_parent->_type) { + case DHT11: + sensor->max_value = 80.0F; + sensor->min_value = 20.0F; + sensor->resolution = 5.0F; + break; + case DHT21: + sensor->max_value = 100.0F; + sensor->min_value = 0.0F; + sensor->resolution = 0.1F; + break; + case DHT22: + sensor->max_value = 100.0F; + sensor->min_value = 0.0F; + sensor->resolution = 0.1F; + break; + default: + // Unknown type, default to 0. + sensor->max_value = 0.0F; + sensor->min_value = 0.0F; + sensor->resolution = 0.0F; + break; + } +} diff --git a/pool/shard007/C++/0094869_random.cc b/pool/shard007/C++/0094869_random.cc new file mode 100644 index 0000000000000000000000000000000000000000..68821fe04124bf3cdc3691bdd23032f4149687d1 --- /dev/null +++ b/pool/shard007/C++/0094869_random.cc @@ -0,0 +1,112 @@ +/*! + * Copyright (c) 2017 by Contributors + * \file External random functions for tensor. + */ +#include <tvm/runtime/registry.h> +#include <tvm/runtime/util.h> +#include <dmlc/logging.h> +#include <dmlc/thread_local.h> +#include <algorithm> +#ifndef _LIBCPP_SGX_CONFIG +#include "mt_random_engine.cc" +#else +#include "sgx_random_engine.cc" +#endif + +#define DLPACK_INTEGER_TYPE_SWITCH(type, DType, ...) \ + if (type.code == kDLInt && type.bits == 32) { \ + typedef int32_t DType; \ + {__VA_ARGS__} \ + } else if (type.code == kDLInt && type.bits == 16) { \ + typedef int16_t DType; \ + {__VA_ARGS__} \ + } else if (type.code == kDLInt && type.bits == 8) { \ + typedef int8_t DType; \ + {__VA_ARGS__} \ + } else if (type.code == kDLUInt && type.bits == 32) { \ + typedef uint32_t DType; \ + {__VA_ARGS__} \ + } else if (type.code == kDLUInt && type.bits == 16) { \ + typedef uint16_t DType; \ + {__VA_ARGS__} \ + } else if (type.code == kDLUInt && type.bits == 8) { \ + typedef uint8_t DType; \ + {__VA_ARGS__} \ + } else { \ + LOG(FATAL) << "unknown data type"; \ + } + +namespace tvm { +namespace contrib { + +using namespace runtime; + +struct RandomThreadLocalEntry { + RandomEngine random_engine; + static RandomThreadLocalEntry* ThreadLocal(); +}; + +typedef dmlc::ThreadLocalStore<RandomThreadLocalEntry> RandomThreadLocalStore; + +RandomThreadLocalEntry* RandomThreadLocalEntry::ThreadLocal() { + return RandomThreadLocalStore::Get(); +} + + +TVM_REGISTER_GLOBAL("tvm.contrib.random.randint") +.set_body([](TVMArgs args, TVMRetValue *ret) { + RandomThreadLocalEntry *entry = RandomThreadLocalEntry::ThreadLocal(); + int64_t low = args[0]; + int64_t high = args[1]; + DLTensor* out = args[2]; + CHECK_GT(high, low) << "high must be bigger than low"; + CHECK(out->strides == nullptr); + + DLDataType dtype = out->dtype; + int64_t size = 1; + for (int i = 0; i < out->ndim; ++i) { + size *= out->shape[i]; + } + + DLPACK_INTEGER_TYPE_SWITCH(dtype, DType, { + int64_t numeric_low = std::numeric_limits<DType>::min(); + int64_t numeric_high = std::numeric_limits<DType>::max(); + numeric_high += 1; // exclusive upper bound + low = std::max(low, numeric_low); + high = std::min(high, numeric_high); + + if (out->ctx.device_type == kDLCPU) { + // file the data with random byte + std::generate_n(static_cast<DType*>(out->data), size, [&] () { + unsigned rint = entry->random_engine.GetRandInt(); + return low + rint % (high - low); + }); + } else { + LOG(FATAL) << "Do not support random.randint on this device yet"; + } + }) + }); + + +TVM_REGISTER_GLOBAL("tvm.contrib.random.uniform") +.set_body([](TVMArgs args, TVMRetValue *ret) { + RandomThreadLocalEntry *entry = RandomThreadLocalEntry::ThreadLocal(); + double low = args[0]; + double high = args[1]; + DLTensor* out = args[2]; + entry->random_engine.SampleUniform(out, low, high); + }); + + +TVM_REGISTER_GLOBAL("tvm.contrib.random.normal") +.set_body([](TVMArgs args, TVMRetValue *ret) { + RandomThreadLocalEntry *entry = RandomThreadLocalEntry::ThreadLocal(); + double loc = args[0]; + double scale = args[1]; + DLTensor* out = args[2]; + entry->random_engine.SampleNormal(out, loc, scale); + }); + + +} // namespace contrib +} // namespace tvm diff --git a/pool/shard007/C++/0094870_BurstRunEvents.cpp b/pool/shard007/C++/0094870_BurstRunEvents.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3b3fb1dab82339d3c2822e09539d7afa10c15afd --- /dev/null +++ b/pool/shard007/C++/0094870_BurstRunEvents.cpp @@ -0,0 +1,87 @@ +/* +--------------------------------------------------------------------------------------- +This source file is part of SWG:ANH (Star Wars Galaxies - A New Hope - Server Emulator) + +For more information, visit http://www.swganh.com + +Copyright (c) 2006 - 2010 The SWG:ANH Team +--------------------------------------------------------------------------------------- +Use of this source code is governed by the GPL v3 license that can be found +in the COPYING file or at http://www.gnu.org/licenses/gpl-3.0.html + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +--------------------------------------------------------------------------------------- +*/ + +#include "SwgProtocol/BurstRunEvents.h" + +using ::common::BaseEvent; +using ::common::ByteBuffer; +using ::common::EventCallback; +using ::common::EventType; + +namespace swg_protocol { + +const EventType BurstRunEndEvent::event_type_ = EventType("BurstRunEndEvent"); +const EventType BurstRunCooldownEndEvent::event_type_ = EventType("BurstRunCooldownEndEvent"); + +BurstRunEndEvent::BurstRunEndEvent(ByteBuffer& in) + : BaseEvent() { + deserialize(in); +} + +BurstRunEndEvent::BurstRunEndEvent(uint64_t subject_id, uint64_t delay_ms) + : BaseEvent(subject_id, delay_ms) {} + +BurstRunEndEvent::BurstRunEndEvent(uint64_t subject_id, uint64_t delay_ms, EventCallback callback) + : BaseEvent(subject_id, delay_ms, callback) {} + +BurstRunEndEvent::~BurstRunEndEvent() {} + +const EventType& BurstRunEndEvent::event_type() const { + return event_type_; +} + +void BurstRunEndEvent::onSerialize(ByteBuffer& out) const {} +void BurstRunEndEvent::onDeserialize(ByteBuffer& in) {} + +bool BurstRunEndEvent::onConsume(bool handled) const { + return true; +} + +BurstRunCooldownEndEvent::BurstRunCooldownEndEvent(ByteBuffer& in) { + deserialize(in); +} + +BurstRunCooldownEndEvent::BurstRunCooldownEndEvent(uint64_t subject_id, uint64_t delay_ms) + : BaseEvent(subject_id, delay_ms) {} + +BurstRunCooldownEndEvent::BurstRunCooldownEndEvent(uint64_t subject_id, uint64_t delay_ms, EventCallback callback) + : BaseEvent(subject_id, delay_ms, callback) {} + +BurstRunCooldownEndEvent::~BurstRunCooldownEndEvent() {} + +const EventType& BurstRunCooldownEndEvent::event_type() const { + return event_type_; +} + +void BurstRunCooldownEndEvent::onSerialize(ByteBuffer& out) const {} +void BurstRunCooldownEndEvent::onDeserialize(ByteBuffer& in) {} + +bool BurstRunCooldownEndEvent::onConsume(bool handled) const { + return true; +} + +} // namespace swg_protocol diff --git a/pool/shard007/C++/0094871_VoxelatedConstructionSpriteBehaviour.cpp b/pool/shard007/C++/0094871_VoxelatedConstructionSpriteBehaviour.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c08504f3bdc9028492a031504b45d2e8616f7ab4 --- /dev/null +++ b/pool/shard007/C++/0094871_VoxelatedConstructionSpriteBehaviour.cpp @@ -0,0 +1,92 @@ +#include "VoxelatedConstructionSpriteBehaviour.h" +#include "ISprite.h" +#include "IVoxelContainer.h" +#include "ISpriteVoxel.h" +#include "SpriteVoxel.h" +#include "ISpriteManager.h" + +VoxelatedConstructionSpriteBehaviour::VoxelatedConstructionSpriteBehaviour(bool xFirst, float buildInterval) : _x(0), _y(0), _z(0), _lastUpdate(0.0f), _done(false), _xFirst(xFirst), _buildInterval(buildInterval) +{ +} + + +VoxelatedConstructionSpriteBehaviour::~VoxelatedConstructionSpriteBehaviour() +{ +} + +void VoxelatedConstructionSpriteBehaviour::attach(ISpriteManager& spriteManager, const std::shared_ptr<ISprite>& sprite) +{ + bool requireRebuild = false; + + const std::shared_ptr<IVoxelContainer> voxelContainer = std::dynamic_pointer_cast<IVoxelContainer> (sprite); + voxelContainer->forEachVoxel([&requireRebuild](const std::shared_ptr<IVoxel>& voxel, GLuint, GLuint, GLuint) + { + const std::shared_ptr<ISpriteVoxel>& spriteVoxel = std::dynamic_pointer_cast<ISpriteVoxel>(voxel); + requireRebuild |= spriteVoxel->getIsActive(); + spriteVoxel->setIsActive(false); + }); +} + +void VoxelatedConstructionSpriteBehaviour::detach(ISpriteManager& spriteManager, const std::shared_ptr<ISprite>& sprite) +{ + +} + +bool VoxelatedConstructionSpriteBehaviour::tick(ISpriteManager& spriteManager, const std::shared_ptr<ISprite>& sprite, float timeDelta) +{ + const float _updateDelay = _buildInterval; + if (_done) + { + return true; + } + + std::shared_ptr<IVoxelContainer> voxelContainer = std::dynamic_pointer_cast<IVoxelContainer> (sprite); + bool requireRebuild = false; + _lastUpdate += timeDelta; + spriteSize size = sprite->getSize(); + std::shared_ptr<std::vector<std::shared_ptr<IVoxel>>> voxelsToUpdate = std::make_shared<std::vector<std::shared_ptr<IVoxel>>>(); + while(_lastUpdate > _updateDelay) + { + std::shared_ptr<IVoxel> underlyingVoxel = voxelContainer->getVoxel(_x, _y, _z); + std::shared_ptr<ISpriteVoxel> voxel = std::dynamic_pointer_cast<ISpriteVoxel>(underlyingVoxel); + if (voxel != nullptr) + { + voxel->setIsActive(true); + voxelsToUpdate->push_back(underlyingVoxel); + } + + unsigned *firstInc = _xFirst ? &_x : &_z; + unsigned firstMax = _xFirst ? size.width : size.depth; + unsigned *secondInc = _xFirst ? &_z : &_x; + unsigned secondMax = _xFirst ? size.depth : size.width; + + (*firstInc)++; + if ((*firstInc) >= firstMax) + { + (*firstInc) = 0; + (*secondInc)++; + if ((*secondInc) >= secondMax) + { + (*secondInc) = 0; + _y++; + if (_y >= size.height) + { + _done = true; + _lastUpdate = 0.0f; + } + } + } + + if (voxel != nullptr) + { + _lastUpdate -= _updateDelay; + } + } + + if (!voxelsToUpdate->empty()) + { + spriteManager.requestUpdate(spriteUpdateRequest(sprite, voxelsToUpdate, spriteUpdateRequestTypeEnum::cheap)); + } + + return _done; +} diff --git a/pool/shard007/C++/0094872_getpullrequestresponse.cpp b/pool/shard007/C++/0094872_getpullrequestresponse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1881ace113387f781128ddeb20cc3ccc2c0f2dfb --- /dev/null +++ b/pool/shard007/C++/0094872_getpullrequestresponse.cpp @@ -0,0 +1,484 @@ +/* + Copyright 2013-2021 Paul Colby + + This file is part of QtAws. + + QtAws is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + QtAws is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with the QtAws. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "getpullrequestresponse.h" +#include "getpullrequestresponse_p.h" + +#include <QDebug> +#include <QNetworkReply> +#include <QXmlStreamReader> + +namespace QtAws { +namespace CodeCommit { + +/*! + * \class QtAws::CodeCommit::GetPullRequestResponse + * \brief The GetPullRequestResponse class provides an interace for CodeCommit GetPullRequest responses. + * + * \inmodule QtAwsCodeCommit + * + * <fullname>AWS CodeCommit</fullname> + * + * This is the <i>AWS CodeCommit API Reference</i>. This reference provides descriptions of the operations and data types + * for AWS CodeCommit API along with usage + * + * examples> + * + * You can use the AWS CodeCommit API to work with the following + * + * objects> + * + * Repositories, by calling the + * + * following> <ul> <li> + * + * <a>BatchGetRepositories</a>, which returns information about one or more repositories associated with your AWS + * + * account> </li> <li> + * + * <a>CreateRepository</a>, which creates an AWS CodeCommit + * + * repository> </li> <li> + * + * <a>DeleteRepository</a>, which deletes an AWS CodeCommit + * + * repository> </li> <li> + * + * <a>GetRepository</a>, which returns information about a specified + * + * repository> </li> <li> + * + * <a>ListRepositories</a>, which lists all AWS CodeCommit repositories associated with your AWS + * + * account> </li> <li> + * + * <a>UpdateRepositoryDescription</a>, which sets or updates the description of the + * + * repository> </li> <li> + * + * <a>UpdateRepositoryName</a>, which changes the name of the repository. If you change the name of a repository, no other + * users of that repository can access it until you send them the new HTTPS or SSH URL to + * + * use> </li> </ul> + * + * Branches, by calling the + * + * following> <ul> <li> + * + * <a>CreateBranch</a>, which creates a branch in a specified + * + * repository> </li> <li> + * + * <a>DeleteBranch</a>, which deletes the specified branch in a repository unless it is the default + * + * branch> </li> <li> + * + * <a>GetBranch</a>, which returns information about a specified + * + * branch> </li> <li> + * + * <a>ListBranches</a>, which lists all branches for a specified + * + * repository> </li> <li> + * + * <a>UpdateDefaultBranch</a>, which changes the default branch for a + * + * repository> </li> </ul> + * + * Files, by calling the + * + * following> <ul> <li> + * + * <a>DeleteFile</a>, which deletes the content of a specified file from a specified + * + * branch> </li> <li> + * + * <a>GetBlob</a>, which returns the base-64 encoded content of an individual Git blob object in a + * + * repository> </li> <li> + * + * <a>GetFile</a>, which returns the base-64 encoded content of a specified + * + * file> </li> <li> + * + * <a>GetFolder</a>, which returns the contents of a specified folder or + * + * directory> </li> <li> + * + * <a>PutFile</a>, which adds or modifies a single file in a specified repository and + * + * branch> </li> </ul> + * + * Commits, by calling the + * + * following> <ul> <li> + * + * <a>BatchGetCommits</a>, which returns information about one or more commits in a + * + * repository> </li> <li> + * + * <a>CreateCommit</a>, which creates a commit for changes to a + * + * repository> </li> <li> + * + * <a>GetCommit</a>, which returns information about a commit, including commit messages and author and committer + * + * information> </li> <li> + * + * <a>GetDifferences</a>, which returns information about the differences in a valid commit specifier (such as a branch, + * tag, HEAD, commit ID, or other fully qualified + * + * reference)> </li> </ul> + * + * Merges, by calling the + * + * following> <ul> <li> + * + * <a>BatchDescribeMergeConflicts</a>, which returns information about conflicts in a merge between commits in a + * + * repository> </li> <li> + * + * <a>CreateUnreferencedMergeCommit</a>, which creates an unreferenced commit between two branches or commits for the + * purpose of comparing them and identifying any potential + * + * conflicts> </li> <li> + * + * <a>DescribeMergeConflicts</a>, which returns information about merge conflicts between the base, source, and destination + * versions of a file in a potential + * + * merge> </li> <li> + * + * <a>GetMergeCommit</a>, which returns information about the merge between a source and destination commit. + * + * </p </li> <li> + * + * <a>GetMergeConflicts</a>, which returns information about merge conflicts between the source and destination branch in a + * pull + * + * request> </li> <li> + * + * <a>GetMergeOptions</a>, which returns information about the available merge options between two branches or commit + * + * specifiers> </li> <li> + * + * <a>MergeBranchesByFastForward</a>, which merges two branches using the fast-forward merge + * + * option> </li> <li> + * + * <a>MergeBranchesBySquash</a>, which merges two branches using the squash merge + * + * option> </li> <li> + * + * <a>MergeBranchesByThreeWay</a>, which merges two branches using the three-way merge + * + * option> </li> </ul> + * + * Pull requests, by calling the + * + * following> <ul> <li> + * + * <a>CreatePullRequest</a>, which creates a pull request in a specified + * + * repository> </li> <li> + * + * <a>CreatePullRequestApprovalRule</a>, which creates an approval rule for a specified pull + * + * request> </li> <li> + * + * <a>DeletePullRequestApprovalRule</a>, which deletes an approval rule for a specified pull + * + * request> </li> <li> + * + * <a>DescribePullRequestEvents</a>, which returns information about one or more pull request + * + * events> </li> <li> + * + * <a>EvaluatePullRequestApprovalRules</a>, which evaluates whether a pull request has met all the conditions specified in + * its associated approval + * + * rules> </li> <li> + * + * <a>GetCommentsForPullRequest</a>, which returns information about comments on a specified pull + * + * request> </li> <li> + * + * <a>GetPullRequest</a>, which returns information about a specified pull + * + * request> </li> <li> + * + * <a>GetPullRequestApprovalStates</a>, which returns information about the approval states for a specified pull + * + * request> </li> <li> + * + * <a>GetPullRequestOverrideState</a>, which returns information about whether approval rules have been set aside + * (overriden) for a pull request, and if so, the Amazon Resource Name (ARN) of the user or identity that overrode the + * rules and their requirements for the pull + * + * request> </li> <li> + * + * <a>ListPullRequests</a>, which lists all pull requests for a + * + * repository> </li> <li> + * + * <a>MergePullRequestByFastForward</a>, which merges the source destination branch of a pull request into the specified + * destination branch for that pull request using the fast-forward merge + * + * option> </li> <li> + * + * <a>MergePullRequestBySquash</a>, which merges the source destination branch of a pull request into the specified + * destination branch for that pull request using the squash merge + * + * option> </li> <li> + * + * <a>MergePullRequestByThreeWay</a>. which merges the source destination branch of a pull request into the specified + * destination branch for that pull request using the three-way merge + * + * option> </li> <li> + * + * <a>OverridePullRequestApprovalRules</a>, which sets aside all approval rule requirements for a pull + * + * request> </li> <li> + * + * <a>PostCommentForPullRequest</a>, which posts a comment to a pull request at the specified line, file, or + * + * request> </li> <li> + * + * <a>UpdatePullRequestApprovalRuleContent</a>, which updates the structure of an approval rule for a pull + * + * request> </li> <li> + * + * <a>UpdatePullRequestApprovalState</a>, which updates the state of an approval on a pull + * + * request> </li> <li> + * + * <a>UpdatePullRequestDescription</a>, which updates the description of a pull + * + * request> </li> <li> + * + * <a>UpdatePullRequestStatus</a>, which updates the status of a pull + * + * request> </li> <li> + * + * <a>UpdatePullRequestTitle</a>, which updates the title of a pull + * + * request> </li> </ul> + * + * Approval rule templates, by calling the + * + * following> <ul> <li> + * + * <a>AssociateApprovalRuleTemplateWithRepository</a>, which associates a template with a specified repository. After the + * template is associated with a repository, AWS CodeCommit creates approval rules that match the template conditions on + * every pull request created in the specified + * + * repository> </li> <li> + * + * <a>BatchAssociateApprovalRuleTemplateWithRepositories</a>, which associates a template with one or more specified + * repositories. After the template is associated with a repository, AWS CodeCommit creates approval rules that match the + * template conditions on every pull request created in the specified + * + * repositories> </li> <li> + * + * <a>BatchDisassociateApprovalRuleTemplateFromRepositories</a>, which removes the association between a template and + * specified repositories so that approval rules based on the template are not automatically created when pull requests are + * created in those + * + * repositories> </li> <li> + * + * <a>CreateApprovalRuleTemplate</a>, which creates a template for approval rules that can then be associated with one or + * more repositories in your AWS + * + * account> </li> <li> + * + * <a>DeleteApprovalRuleTemplate</a>, which deletes the specified template. It does not remove approval rules on pull + * requests already created with the + * + * template> </li> <li> + * + * <a>DisassociateApprovalRuleTemplateFromRepository</a>, which removes the association between a template and a repository + * so that approval rules based on the template are not automatically created when pull requests are created in the + * specified + * + * repository> </li> <li> + * + * <a>GetApprovalRuleTemplate</a>, which returns information about an approval rule + * + * template> </li> <li> + * + * <a>ListApprovalRuleTemplates</a>, which lists all approval rule templates in the AWS Region in your AWS + * + * account> </li> <li> + * + * <a>ListAssociatedApprovalRuleTemplatesForRepository</a>, which lists all approval rule templates that are associated + * with a specified + * + * repository> </li> <li> + * + * <a>ListRepositoriesForApprovalRuleTemplate</a>, which lists all repositories associated with the specified approval rule + * + * template> </li> <li> + * + * <a>UpdateApprovalRuleTemplateDescription</a>, which updates the description of an approval rule + * + * template> </li> <li> + * + * <a>UpdateApprovalRuleTemplateName</a>, which updates the name of an approval rule + * + * template> </li> <li> + * + * <a>UpdateApprovalRuleTemplateContent</a>, which updates the content of an approval rule + * + * template> </li> </ul> + * + * Comments in a repository, by calling the + * + * following> <ul> <li> + * + * <a>DeleteCommentContent</a>, which deletes the content of a comment on a commit in a + * + * repository> </li> <li> + * + * <a>GetComment</a>, which returns information about a comment on a + * + * commit> </li> <li> + * + * <a>GetCommentReactions</a>, which returns information about emoji reactions to + * + * comments> </li> <li> + * + * <a>GetCommentsForComparedCommit</a>, which returns information about comments on the comparison between two commit + * specifiers in a + * + * repository> </li> <li> + * + * <a>PostCommentForComparedCommit</a>, which creates a comment on the comparison between two commit specifiers in a + * + * repository> </li> <li> + * + * <a>PostCommentReply</a>, which creates a reply to a + * + * comment> </li> <li> + * + * <a>PutCommentReaction</a>, which creates or updates an emoji reaction to a + * + * comment> </li> <li> + * + * <a>UpdateComment</a>, which updates the content of a comment on a commit in a + * + * repository> </li> </ul> + * + * Tags used to tag resources in AWS CodeCommit (not Git tags), by calling the + * + * following> <ul> <li> + * + * <a>ListTagsForResource</a>, which gets information about AWS tags for a specified Amazon Resource Name (ARN) in AWS + * + * CodeCommit> </li> <li> + * + * <a>TagResource</a>, which adds or updates tags for a resource in AWS + * + * CodeCommit> </li> <li> + * + * <a>UntagResource</a>, which removes tags for a resource in AWS + * + * CodeCommit> </li> </ul> + * + * Triggers, by calling the + * + * following> <ul> <li> + * + * <a>GetRepositoryTriggers</a>, which returns information about triggers configured for a + * + * repository> </li> <li> + * + * <a>PutRepositoryTriggers</a>, which replaces all triggers for a repository and can be used to create or delete + * + * triggers> </li> <li> + * + * <a>TestRepositoryTriggers</a>, which tests the functionality of a repository trigger by sending data to the trigger + * + * target> </li> </ul> + * + * For information about how to use AWS CodeCommit, see the <a + * href="https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html">AWS CodeCommit User + * + * \sa CodeCommitClient::getPullRequest + */ + +/*! + * Constructs a GetPullRequestResponse object for \a reply to \a request, with parent \a parent. + */ +GetPullRequestResponse::GetPullRequestResponse( + const GetPullRequestRequest &request, + QNetworkReply * const reply, + QObject * const parent) + : CodeCommitResponse(new GetPullRequestResponsePrivate(this), parent) +{ + setRequest(new GetPullRequestRequest(request)); + setReply(reply); +} + +/*! + * \reimp + */ +const GetPullRequestRequest * GetPullRequestResponse::request() const +{ + Q_D(const GetPullRequestResponse); + return static_cast<const GetPullRequestRequest *>(d->request); +} + +/*! + * \reimp + * Parses a successful CodeCommit GetPullRequest \a response. + */ +void GetPullRequestResponse::parseSuccess(QIODevice &response) +{ + //Q_D(GetPullRequestResponse); + QXmlStreamReader xml(&response); + /// @todo +} + +/*! + * \class QtAws::CodeCommit::GetPullRequestResponsePrivate + * \brief The GetPullRequestResponsePrivate class provides private implementation for GetPullRequestResponse. + * \internal + * + * \inmodule QtAwsCodeCommit + */ + +/*! + * Constructs a GetPullRequestResponsePrivate object with public implementation \a q. + */ +GetPullRequestResponsePrivate::GetPullRequestResponsePrivate( + GetPullRequestResponse * const q) : CodeCommitResponsePrivate(q) +{ + +} + +/*! + * Parses a CodeCommit GetPullRequest response element from \a xml. + */ +void GetPullRequestResponsePrivate::parseGetPullRequestResponse(QXmlStreamReader &xml) +{ + Q_ASSERT(xml.name() == QLatin1String("GetPullRequestResponse")); + Q_UNUSED(xml) ///< @todo +} + +} // namespace CodeCommit +} // namespace QtAws diff --git a/pool/shard007/C++/0094877_generic_hash_unittest.cc b/pool/shard007/C++/0094877_generic_hash_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..7c305a2bf5a37480c39248ea25f02aed5d358859 --- /dev/null +++ b/pool/shard007/C++/0094877_generic_hash_unittest.cc @@ -0,0 +1,115 @@ +// +// Aspia Project +// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru> +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. +// + +#include "base/crypto/generic_hash.h" + +#include <gtest/gtest.h> + +namespace base { + +TEST(GenericHashTest, Blake2b512) +{ + struct TestData + { + std::string_view data1; + std::string_view data2; + std::string_view expected; + } const kTestTable[] = + { + { + "535f08970d17ee878dae4d20444dac", + "fb1c50ac4803c1591b6cfb1420f561", + "9c66da0b7410b12e1b1daea576d49b924988304848184805f0716714646795c788452568892c2330cff4405aa1490752b9553136ee83578a20c78b436c066416" + }, + + { + "fb1c50ac4803c1591b6cfb1420f561", + "535f08970d17ee878dae4d20444dac", + "afc17e0ed2cfaa23ab62f55738b16a811da05a7c0f130e3b020bd633c38a8c28f2266d05fe363b14026a1f5dbcb5800345cb0f801a2fd1cc38bf48d33202e4da" + } + }; + + int count = 3; + + while (count-- >= 0) + { + for (size_t i = 0; i < std::size(kTestTable); ++i) + { + GenericHash hash(GenericHash::BLAKE2b512); + + hash.addData(fromHex(kTestTable[i].data1)); + hash.addData(fromHex(kTestTable[i].data2)); + + ByteArray expected = fromHex(kTestTable[i].expected); + ByteArray result = hash.result(); + + EXPECT_EQ(expected.size(), 64); + EXPECT_EQ(result.size(), 64); + EXPECT_EQ(result, expected); + + hash.reset(); + } + } +} + +TEST(GenericHashTest, Blake2s256) +{ + struct TestData + { + std::string_view data1; + std::string_view data2; + std::string_view expected; + } const kTestTable[] = + { + { + "535f08970d17ee878dae4d20444dac", + "fb1c50ac4803c1591b6cfb1420f561", + "ee7eb0e6fb24d445597f3e6f1e0cdd649c71f7cd5c9699e270d5dc69f2d6baa5" + }, + + { + "fb1c50ac4803c1591b6cfb1420f561", + "535f08970d17ee878dae4d20444dac", + "a180f6b02ceba827b430e88eeff0c3cb7f583ca99e6537970f30efb15a66c762" + } + }; + + int count = 3; + + while (count-- >= 0) + { + for (size_t i = 0; i < std::size(kTestTable); ++i) + { + GenericHash hash(GenericHash::BLAKE2s256); + + hash.addData(fromHex(kTestTable[i].data1)); + hash.addData(fromHex(kTestTable[i].data2)); + + ByteArray expected = fromHex(kTestTable[i].expected); + ByteArray result = hash.result(); + + EXPECT_EQ(expected.size(), 32); + EXPECT_EQ(result.size(), 32); + EXPECT_EQ(result, expected); + + hash.reset(); + } + } +} + +} // namespace base diff --git a/pool/shard007/C++/0094883_SyntaxHighlighter.cpp b/pool/shard007/C++/0094883_SyntaxHighlighter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..38c2871c089e235e6e36cdcf9e18b3406f84a683 --- /dev/null +++ b/pool/shard007/C++/0094883_SyntaxHighlighter.cpp @@ -0,0 +1,156 @@ +/*************************************************************************** + File : SyntaxHighlighter.cpp + Project : AlphaPlot +-------------------------------------------------------------------- + Copyright : (C) 2016 by Arun Narayanankutty + Email : n.arun.lifescience@gmail.com + Description : Highlight scripts & interpreter text + + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; under version 2 of the License. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the Free Software * + * Foundation, Inc., 51 Franklin Street, Fifth Floor, * + * Boston, MA 02110-1301 USA * + * * + ***************************************************************************/ + +#include "SyntaxHighlighter.h" + +SyntaxHighlighter::SyntaxHighlighter(QTextDocument *parent) + : QSyntaxHighlighter(parent) { + HighlightingRule rule; + + keywordFormat.setForeground(QColor(249, 38, 114)); + keywordFormat.setFontWeight(QFont::Normal); + + keywords << "break" + << "case" + << "catch" + << "continue" + << "debugger" + << "default" + << "delete" + << "do" + << "else" + << "finally" + << "for" + << "function" + << "if" + << "in" + << "instanceof" + << "new" + << "returm" + << "switch" + << "throw" + << "try" + << "typeof" + << "var" + << "while" + << "with"; + + uselessKeywords << "class" + << "const" + << "enum" + << "export" + << "extends" + << "import" + << "super"; + + foreach (const QString &pattern, keywords) { + rule.pattern = QRegExp("\\b" + pattern + "\\b"); + rule.format = keywordFormat; + highlightingRules.append(rule); + } + + classFormat.setForeground(Qt::darkMagenta); + rule.pattern = QRegExp("\\bMath\\b"); + rule.format = classFormat; + highlightingRules.append(rule); + + QTextCharFormat trueFalseFormat; + trueFalseFormat.setForeground(QColor(174, 129, 255)); + rule.pattern = QRegExp("\\b(true|false|this)\\b"); + rule.format = trueFalseFormat; + highlightingRules.append(rule); + + quotationFormat.setForeground(Qt::darkGreen); + rule.pattern = QRegExp("\".*\""); + rule.format = quotationFormat; + highlightingRules.append(rule); + + singleQuotationFormat.setForeground(Qt::darkGreen); + rule.pattern = QRegExp("'.*'"); + rule.format = singleQuotationFormat; + highlightingRules.append(rule); + + functionFormat.setFontItalic(true); + functionFormat.setForeground(QColor(204, 140, 91)); + + // Exclude keywords misinterpretation as functions + QString keywordExcludePatterns; + foreach (const QString &pattern, keywords) { + (pattern == keywords[0]) + ? keywordExcludePatterns.append(pattern) + : keywordExcludePatterns.append(QString("|%1").arg(pattern)); + } + + rule.pattern = QRegExp( + QString("\\b(?!(%1)+[\\s]*[/]?(?=\\())([A-Za-z0-9_]+[\\s]*[/]?(?=\\())") + .arg(keywordExcludePatterns)); + rule.format = functionFormat; + highlightingRules.append(rule); + + singleLineCommentFormat.setForeground(QColor(128, 128, 128)); + rule.pattern = QRegExp("//[^\n]*"); + rule.format = singleLineCommentFormat; + highlightingRules.append(rule); + + multiLineCommentFormat.setForeground(QColor(128, 128, 128)); + + commentStartExpression = QRegExp("/\\*"); + commentEndExpression = QRegExp("\\*/"); +} + +void SyntaxHighlighter::highlightBlock(const QString &text) { + foreach (const HighlightingRule &rule, highlightingRules) { + QRegExp expression(rule.pattern); + int index = expression.indexIn(text); + while (index >= 0) { + int length = expression.matchedLength(); + setFormat(index, length, rule.format); + index = expression.indexIn(text, index + length); + } + } + setCurrentBlockState(0); + + int startIndex = 0; + if (previousBlockState() != 1) + startIndex = commentStartExpression.indexIn(text); + + while (startIndex >= 0) { + int endIndex = commentEndExpression.indexIn(text, startIndex); + int commentLength; + if (endIndex == -1) { + setCurrentBlockState(1); + commentLength = text.length() - startIndex; + } else { + commentLength = + endIndex - startIndex + commentEndExpression.matchedLength(); + } + setFormat(startIndex, commentLength, multiLineCommentFormat); + startIndex = + commentStartExpression.indexIn(text, startIndex + commentLength); + } +} diff --git a/pool/shard007/C++/0094885_SkMaskCache.cpp b/pool/shard007/C++/0094885_SkMaskCache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f08f4d7ee02ec54f979874f56f256760080970fd --- /dev/null +++ b/pool/shard007/C++/0094885_SkMaskCache.cpp @@ -0,0 +1,185 @@ +/* + * Copyright 2014 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include "src/core/SkMaskCache.h" + +#define CHECK_LOCAL(localCache, localName, globalName, ...) \ + ((localCache) ? localCache->localName(__VA_ARGS__) : SkResourceCache::globalName(__VA_ARGS__)) + +struct MaskValue { + SkMask fMask; + SkCachedData* fData; +}; + +namespace { +static unsigned gRRectBlurKeyNamespaceLabel; + +struct RRectBlurKey : public SkResourceCache::Key { +public: + RRectBlurKey(SkScalar sigma, const SkRRect& rrect, SkBlurStyle style) + : fSigma(sigma) + , fStyle(style) + , fRRect(rrect) + { + this->init(&gRRectBlurKeyNamespaceLabel, 0, + sizeof(fSigma) + sizeof(fStyle) + sizeof(fRRect)); + } + + SkScalar fSigma; + int32_t fStyle; + SkRRect fRRect; +}; + +struct RRectBlurRec : public SkResourceCache::Rec { + RRectBlurRec(RRectBlurKey key, const SkMask& mask, SkCachedData* data) + : fKey(key) + { + fValue.fMask = mask; + fValue.fData = data; + fValue.fData->attachToCacheAndRef(); + } + ~RRectBlurRec() override { + fValue.fData->detachFromCacheAndUnref(); + } + + RRectBlurKey fKey; + MaskValue fValue; + + const Key& getKey() const override { return fKey; } + size_t bytesUsed() const override { return sizeof(*this) + fValue.fData->size(); } + const char* getCategory() const override { return "rrect-blur"; } + SkDiscardableMemory* diagnostic_only_getDiscardable() const override { + return fValue.fData->diagnostic_only_getDiscardable(); + } + + static bool Visitor(const SkResourceCache::Rec& baseRec, void* contextData) { + const RRectBlurRec& rec = static_cast<const RRectBlurRec&>(baseRec); + MaskValue* result = (MaskValue*)contextData; + + SkCachedData* tmpData = rec.fValue.fData; + tmpData->ref(); + if (nullptr == tmpData->data()) { + tmpData->unref(); + return false; + } + *result = rec.fValue; + return true; + } +}; +} // namespace + +SkCachedData* SkMaskCache::FindAndRef(SkScalar sigma, SkBlurStyle style, + const SkRRect& rrect, SkMask* mask, SkResourceCache* localCache) { + MaskValue result; + RRectBlurKey key(sigma, rrect, style); + if (!CHECK_LOCAL(localCache, find, Find, key, RRectBlurRec::Visitor, &result)) { + return nullptr; + } + + *mask = result.fMask; + mask->fImage = (uint8_t*)(result.fData->data()); + return result.fData; +} + +void SkMaskCache::Add(SkScalar sigma, SkBlurStyle style, + const SkRRect& rrect, const SkMask& mask, SkCachedData* data, + SkResourceCache* localCache) { + RRectBlurKey key(sigma, rrect, style); + return CHECK_LOCAL(localCache, add, Add, new RRectBlurRec(key, mask, data)); +} + +////////////////////////////////////////////////////////////////////////////////////////// + +namespace { +static unsigned gRectsBlurKeyNamespaceLabel; + +struct RectsBlurKey : public SkResourceCache::Key { +public: + RectsBlurKey(SkScalar sigma, SkBlurStyle style, const SkRect rects[], int count) + : fSigma(sigma) + , fStyle(style) + { + SkASSERT(1 == count || 2 == count); + SkIRect ir; + rects[0].roundOut(&ir); + fSizes[0] = SkSize{rects[0].width(), rects[0].height()}; + if (2 == count) { + fSizes[1] = SkSize{rects[1].width(), rects[1].height()}; + fSizes[2] = SkSize{rects[0].x() - rects[1].x(), rects[0].y() - rects[1].y()}; + } else { + fSizes[1] = SkSize{0, 0}; + fSizes[2] = SkSize{0, 0}; + } + fSizes[3] = SkSize{rects[0].x() - ir.x(), rects[0].y() - ir.y()}; + + this->init(&gRectsBlurKeyNamespaceLabel, 0, + sizeof(fSigma) + sizeof(fStyle) + sizeof(fSizes)); + } + + SkScalar fSigma; + int32_t fStyle; + SkSize fSizes[4]; +}; + +struct RectsBlurRec : public SkResourceCache::Rec { + RectsBlurRec(RectsBlurKey key, const SkMask& mask, SkCachedData* data) + : fKey(key) + { + fValue.fMask = mask; + fValue.fData = data; + fValue.fData->attachToCacheAndRef(); + } + ~RectsBlurRec() override { + fValue.fData->detachFromCacheAndUnref(); + } + + RectsBlurKey fKey; + MaskValue fValue; + + const Key& getKey() const override { return fKey; } + size_t bytesUsed() const override { return sizeof(*this) + fValue.fData->size(); } + const char* getCategory() const override { return "rects-blur"; } + SkDiscardableMemory* diagnostic_only_getDiscardable() const override { + return fValue.fData->diagnostic_only_getDiscardable(); + } + + static bool Visitor(const SkResourceCache::Rec& baseRec, void* contextData) { + const RectsBlurRec& rec = static_cast<const RectsBlurRec&>(baseRec); + MaskValue* result = static_cast<MaskValue*>(contextData); + + SkCachedData* tmpData = rec.fValue.fData; + tmpData->ref(); + if (nullptr == tmpData->data()) { + tmpData->unref(); + return false; + } + *result = rec.fValue; + return true; + } +}; +} // namespace + +SkCachedData* SkMaskCache::FindAndRef(SkScalar sigma, SkBlurStyle style, + const SkRect rects[], int count, SkMask* mask, + SkResourceCache* localCache) { + MaskValue result; + RectsBlurKey key(sigma, style, rects, count); + if (!CHECK_LOCAL(localCache, find, Find, key, RectsBlurRec::Visitor, &result)) { + return nullptr; + } + + *mask = result.fMask; + mask->fImage = (uint8_t*)(result.fData->data()); + return result.fData; +} + +void SkMaskCache::Add(SkScalar sigma, SkBlurStyle style, + const SkRect rects[], int count, const SkMask& mask, SkCachedData* data, + SkResourceCache* localCache) { + RectsBlurKey key(sigma, style, rects, count); + return CHECK_LOCAL(localCache, add, Add, new RectsBlurRec(key, mask, data)); +} diff --git a/pool/shard007/C++/0094887_DolphinDevice.cpp b/pool/shard007/C++/0094887_DolphinDevice.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c215d7f8046f87a5d60515a8052549eda5947f6e --- /dev/null +++ b/pool/shard007/C++/0094887_DolphinDevice.cpp @@ -0,0 +1,151 @@ +// Copyright 2019 Dolphin Emulator Project +// Licensed under GPLv2+ +// Refer to the license.txt file included. + +#include <algorithm> +#include <cstring> + +#include "Common/Logging/Log.h" +#include "Common/Timer.h" +#include "Common/scmrev.h" +#include "Core/BootManager.h" +#include "Core/ConfigManager.h" +#include "Core/Core.h" +#include "Core/HW/Memmap.h" +#include "Core/IOS/DolphinDevice.h" + +namespace IOS::HLE::Device +{ +namespace +{ +enum +{ + IOCTL_DOLPHIN_GET_SYSTEM_TIME = 0x01, + IOCTL_DOLPHIN_GET_VERSION = 0x02, + IOCTL_DOLPHIN_GET_SPEED_LIMIT = 0x03, + IOCTL_DOLPHIN_SET_SPEED_LIMIT = 0x04, + IOCTL_DOLPHIN_GET_CPU_SPEED = 0x05, + +}; + +IPCCommandResult GetSystemTime(const IOCtlVRequest& request) +{ + if (!request.HasNumberOfValidVectors(0, 1)) + { + return DolphinDevice::GetDefaultReply(IPC_EINVAL); + } + + if (request.io_vectors[0].size != 4) + { + return DolphinDevice::GetDefaultReply(IPC_EINVAL); + } + + const u32 milliseconds = Common::Timer::GetTimeMs(); + + Memory::Write_U32(milliseconds, request.io_vectors[0].address); + return DolphinDevice::GetDefaultReply(IPC_SUCCESS); +} + +IPCCommandResult GetVersion(const IOCtlVRequest& request) +{ + if (!request.HasNumberOfValidVectors(0, 1)) + { + return DolphinDevice::GetDefaultReply(IPC_EINVAL); + } + + const auto length = std::min(size_t(request.io_vectors[0].size), std::strlen(SCM_DESC_STR)); + + Memory::Memset(request.io_vectors[0].address, 0, request.io_vectors[0].size); + Memory::CopyToEmu(request.io_vectors[0].address, SCM_DESC_STR, length); + + return DolphinDevice::GetDefaultReply(IPC_SUCCESS); +} + +IPCCommandResult GetCPUSpeed(const IOCtlVRequest& request) +{ + if (!request.HasNumberOfValidVectors(0, 1)) + { + return DolphinDevice::GetDefaultReply(IPC_EINVAL); + } + + if (request.io_vectors[0].size != 4) + { + return DolphinDevice::GetDefaultReply(IPC_EINVAL); + } + + const SConfig& config = SConfig::GetInstance(); + const float oc = config.m_OCEnable ? config.m_OCFactor : 1.0f; + + const u32 core_clock = u32(float(SystemTimers::GetTicksPerSecond()) * oc); + + Memory::Write_U32(core_clock, request.io_vectors[0].address); + + return DolphinDevice::GetDefaultReply(IPC_SUCCESS); +} + +IPCCommandResult GetSpeedLimit(const IOCtlVRequest& request) +{ + // get current speed limit + if (!request.HasNumberOfValidVectors(0, 1)) + { + return DolphinDevice::GetDefaultReply(IPC_EINVAL); + } + + if (request.io_vectors[0].size != 4) + { + return DolphinDevice::GetDefaultReply(IPC_EINVAL); + } + + const SConfig& config = SConfig::GetInstance(); + const u32 speed_percent = config.m_EmulationSpeed * 100; + Memory::Write_U32(speed_percent, request.io_vectors[0].address); + + return DolphinDevice::GetDefaultReply(IPC_SUCCESS); +} + +IPCCommandResult SetSpeedLimit(const IOCtlVRequest& request) +{ + // set current speed limit + if (!request.HasNumberOfValidVectors(1, 0)) + { + return DolphinDevice::GetDefaultReply(IPC_EINVAL); + } + + if (request.in_vectors[0].size != 4) + { + return DolphinDevice::GetDefaultReply(IPC_EINVAL); + } + + const float speed = float(Memory::Read_U32(request.in_vectors[0].address)) / 100.0f; + SConfig::GetInstance().m_EmulationSpeed = speed; + BootManager::SetEmulationSpeedReset(true); + + return DolphinDevice::GetDefaultReply(IPC_SUCCESS); +} + +} // namespace + +IPCCommandResult DolphinDevice::IOCtlV(const IOCtlVRequest& request) +{ + if (Core::WantsDeterminism()) + { + return DolphinDevice::GetDefaultReply(IPC_EACCES); + } + + switch (request.request) + { + case IOCTL_DOLPHIN_GET_SYSTEM_TIME: + return GetSystemTime(request); + case IOCTL_DOLPHIN_GET_VERSION: + return GetVersion(request); + case IOCTL_DOLPHIN_GET_SPEED_LIMIT: + return GetSpeedLimit(request); + case IOCTL_DOLPHIN_SET_SPEED_LIMIT: + return SetSpeedLimit(request); + case IOCTL_DOLPHIN_GET_CPU_SPEED: + return GetCPUSpeed(request); + default: + return GetDefaultReply(IPC_EINVAL); + } +} +} // namespace IOS::HLE::Device diff --git a/pool/shard007/C++/0094888_DemoModuleB.cpp b/pool/shard007/C++/0094888_DemoModuleB.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b8f7c0f0277b67e405093dd26d3fee3f9c6376fc --- /dev/null +++ b/pool/shard007/C++/0094888_DemoModuleB.cpp @@ -0,0 +1,55 @@ +/** + * @file src/modules/demo/DemoModuleB.cpp + * @date feb. 2016 + * @author PhRG - opticalp.fr + */ + +/* + Copyright (c) 2016 Ph. Renaud-Goud / Opticalp + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + +#include "DemoModuleB.h" +#include "Poco/NumberFormatter.h" + +size_t DemoModuleB::refCount = 0; + +DemoModuleB::DemoModuleB(ModuleFactory* parent, std::string customName): + Module(parent, customName) +{ + // poco_information(logger(),"Creating a new demo module B"); + + if (refCount) + setInternalName("DemoModuleB" + Poco::NumberFormatter::format(refCount)); + else + setInternalName("DemoModuleB"); + + setCustomName(customName); + setLogger("module." + name()); + + // ports + setOutPortCount(outPortCnt); + addOutPort("outPortA", "demo port that transmits nothing", DataItem::typeInteger, outPortA); + + notifyCreation(); + + // if nothing failed + refCount++; +} diff --git a/pool/shard007/C++/0094890_importtemplateserializer.cpp b/pool/shard007/C++/0094890_importtemplateserializer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8333faf61d8154bea8da9b0f5fe1ef45a0a910b2 --- /dev/null +++ b/pool/shard007/C++/0094890_importtemplateserializer.cpp @@ -0,0 +1,215 @@ +#include "importtemplateserializer.h" + +#include "QXmlStreamWriter" + +#include "../Model/recordtableimporttemplate.h" +#include "../../../IO/xmlreader.h" + +using namespace Tome; + +const QString ImportTemplateSerializer::AttributeColumnName = "ColumnName"; +const QString ImportTemplateSerializer::AttributeFieldId = "FieldId"; +const QString ImportTemplateSerializer::AttributeKey = "Key"; +const QString ImportTemplateSerializer::AttributeValue = "Value"; +const QString ImportTemplateSerializer::AttributeVersion = "Version"; + +const QString ImportTemplateSerializer::ElementColumnMap = "ColumnMap"; +const QString ImportTemplateSerializer::ElementDisplayNameColumn = "DisplayNameColumn"; +const QString ImportTemplateSerializer::ElementEditorIconFieldIdColumn = "EditorIconFieldIdColumn"; +const QString ImportTemplateSerializer::ElementId = "Id"; +const QString ImportTemplateSerializer::ElementIdColumn = "IdColumn"; +const QString ImportTemplateSerializer::ElementIgnoredIds = "IgnoredIds"; +const QString ImportTemplateSerializer::ElementMapping = "Mapping"; +const QString ImportTemplateSerializer::ElementName = "Name"; +const QString ImportTemplateSerializer::ElementParameter = "Parameter"; +const QString ImportTemplateSerializer::ElementParameters = "Parameters"; +const QString ImportTemplateSerializer::ElementReplaceWith = "ReplaceWith"; +const QString ImportTemplateSerializer::ElementRootRecordId = "RootRecordId"; +const QString ImportTemplateSerializer::ElementSourceType = "SourceType"; +const QString ImportTemplateSerializer::ElementString = "String"; +const QString ImportTemplateSerializer::ElementStringReplacementMap = "StringReplacementMap"; +const QString ImportTemplateSerializer::ElementTemplate = "Template"; + +const int ImportTemplateSerializer::Version = 1; + + +void ImportTemplateSerializer::serialize(QIODevice& device, const RecordTableImportTemplate& importTemplate) const +{ + // Open device stream. + QXmlStreamWriter writer(&device); + writer.setAutoFormatting(true); + + // Begin document. + writer.writeStartDocument(); + { + writer.writeStartElement(ElementTemplate); + { + // Write version. + writer.writeAttribute(AttributeVersion, QString::number(Version)); + + // Write name, type, id column and root record. + writer.writeTextElement(ElementName, importTemplate.name); + writer.writeTextElement(ElementSourceType, TableType::toString(importTemplate.sourceType)); + writer.writeTextElement(ElementIdColumn, importTemplate.idColumn); + writer.writeTextElement(ElementDisplayNameColumn, importTemplate.displayNameColumn); + writer.writeTextElement(ElementEditorIconFieldIdColumn, importTemplate.editorIconFieldIdColumn); + writer.writeTextElement(ElementRootRecordId, importTemplate.rootRecordId); + + // Write column map. + writer.writeStartElement(ElementColumnMap); + { + for (QMap<QString, QString>::const_iterator itColumnMap = importTemplate.columnMap.cbegin(); + itColumnMap != importTemplate.columnMap.cend(); + ++itColumnMap) + { + writer.writeStartElement(ElementMapping); + writer.writeAttribute(AttributeColumnName, itColumnMap.key()); + writer.writeAttribute(AttributeFieldId, itColumnMap.value()); + writer.writeEndElement(); + } + } + writer.writeEndElement(); + + // Write string replacement map. + writer.writeStartElement(ElementStringReplacementMap); + { + for (auto itStringReplacementMap = importTemplate.stringReplacementMap.cbegin(); + itStringReplacementMap != importTemplate.stringReplacementMap.cend(); + ++itStringReplacementMap) + { + writer.writeStartElement(ElementMapping); + writer.writeTextElement(ElementString, itStringReplacementMap.key()); + writer.writeTextElement(ElementReplaceWith, itStringReplacementMap.value()); + writer.writeEndElement(); + } + } + writer.writeEndElement(); + + // Write ignore list. + writer.writeStartElement(ElementIgnoredIds); + { + for (int i = 0; i < importTemplate.ignoredIds.size(); ++i) + { + writer.writeTextElement(ElementId, importTemplate.ignoredIds[i]); + } + } + writer.writeEndElement(); + + // Write parameters. + writer.writeStartElement(ElementParameters); + { + for (QMap<QString, QString>::const_iterator itParameters = importTemplate.parameters.cbegin(); + itParameters != importTemplate.parameters.cend(); + ++itParameters) + { + writer.writeStartElement(ElementParameter); + writer.writeAttribute(AttributeKey, itParameters.key()); + writer.writeAttribute(AttributeValue, itParameters.value()); + writer.writeEndElement(); + } + } + writer.writeEndElement(); + } + writer.writeEndElement(); + } + writer.writeEndDocument(); +} + +void ImportTemplateSerializer::deserialize(QIODevice& device, RecordTableImportTemplate& importTemplate) const +{ + // Open device stream. + XmlReader reader(&device); + + // Validate import template file. + reader.validate(":/Source/Tome/Features/Import/Model/TomeImportTemplate.xsd", + QObject::tr("Invalid import template file: %1 (line %2, column %3)")); + + // Begin document. + reader.readStartDocument(); + { + // Read record import template. + reader.readStartElement(ElementTemplate); + { + // Read name, type, id column and root record. + importTemplate.name = reader.readTextElement(ElementName); + importTemplate.sourceType = TableType::fromString(reader.readTextElement(ElementSourceType)); + importTemplate.idColumn = reader.readTextElement(ElementIdColumn); + + if (reader.isAtElement(ElementDisplayNameColumn)) + { + importTemplate.displayNameColumn = reader.readTextElement(ElementDisplayNameColumn); + } + + if (reader.isAtElement(ElementEditorIconFieldIdColumn)) + { + importTemplate.editorIconFieldIdColumn = reader.readTextElement(ElementEditorIconFieldIdColumn); + } + + importTemplate.rootRecordId = reader.readTextElement(ElementRootRecordId); + + // Read column map. + reader.readStartElement(ElementColumnMap); + { + while (reader.isAtElement(ElementMapping)) + { + QString columnMapKey = reader.readAttribute(AttributeColumnName); + QString columnMapValue = reader.readAttribute(AttributeFieldId); + + importTemplate.columnMap.insert(columnMapKey, columnMapValue); + + // Advance reader. + reader.readEmptyElement(ElementMapping); + } + } + reader.readEndElement(); + + // Read string replacement map. + if (reader.isAtElement(ElementStringReplacementMap)) + { + reader.readStartElement(ElementStringReplacementMap); + { + while (reader.isAtElement(ElementMapping)) + { + reader.readStartElement(ElementMapping); + { + QString stringReplacementKey = reader.readTextElement(ElementString); + QString stringReplacementValue = reader.readTextElement(ElementReplaceWith); + + importTemplate.stringReplacementMap.insert(stringReplacementKey, stringReplacementValue); + } + reader.readEndElement(); + } + } + reader.readEndElement(); + } + + // Read ignore list. + reader.readStartElement(ElementIgnoredIds); + { + while (reader.isAtElement(ElementId)) + { + importTemplate.ignoredIds << reader.readTextElement(ElementId); + } + } + reader.readEndElement(); + + // Read parameters + reader.readStartElement(ElementParameters); + { + while (reader.isAtElement(ElementParameter)) + { + QString parameterKey = reader.readAttribute(AttributeKey); + QString parameterValue = reader.readAttribute(AttributeValue); + + importTemplate.parameters.insert(parameterKey, parameterValue); + + // Advance reader. + reader.readEmptyElement(ElementParameter); + } + } + reader.readEndElement(); + } + reader.readEndElement(); + } + reader.readEndDocument(); +} diff --git a/pool/shard007/C++/0094891_ImageWidget.cpp b/pool/shard007/C++/0094891_ImageWidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8d8fe5b4050e0091f5d436e9a4363b9095044ca0 --- /dev/null +++ b/pool/shard007/C++/0094891_ImageWidget.cpp @@ -0,0 +1,109 @@ +/* + * Copyright (C) 2018 Shawn Rutledge <s@ecloud.org> + * This file is part of Phototonic Image Viewer. + * + * Phototonic is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Phototonic is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Phototonic. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "ImageWidget.h" +#include <QDebug> +#include <QPainter> +#include <QPaintEvent> + +ImageWidget::ImageWidget(QWidget *parent) : QWidget(parent) +{ +} + +bool ImageWidget::empty() +{ + return m_image.isNull(); +} + +QImage ImageWidget::image() +{ + return m_image; +} + +void ImageWidget::setImage(const QImage &i) +{ + m_image = i; + m_rotation = 0; + update(); +} + +void ImageWidget::setRotation(qreal r) +{ + m_rotation = r; + update(); +} + +QPoint ImageWidget::mapToImage(QPoint p) +{ + QPoint upperLeft; + QPoint center(width() / 2, height() / 2); + if (width() > m_image.width()) + upperLeft.setX(center.x() - m_image.width() / 2); + if (height() > m_image.height()) + upperLeft.setY(center.y() - m_image.height() / 2); + return QPoint(p.x() - upperLeft.x(), p.y() - upperLeft.y()); +} + +QSize ImageWidget::imageSize() const +{ + return m_image.size(); +} + +QSize ImageWidget::sizeHint() const +{ + return m_image.size(); +} + +void ImageWidget::paintEvent(QPaintEvent *ev) +{ + float scale = qMax(float(width()) / m_image.width(), float(height()) / m_image.height()); + + QPainter painter(this); + + if (qFuzzyIsNull(m_rotation)) { + const float sx = qMax(-x() / scale, 0.f); + const float sy = qMax(-y() / scale, 0.f); + const float sw = qMin<float>(width() / scale, m_image.width()); + const float sh = qMin<float>(height() / scale, m_image.height()); + + QRectF sourceRect(sx, sy, sw, sh); + QRectF targetRect = rect(); + targetRect &= ev->rect(); + sourceRect &= QRectF(ev->rect().x() / scale, ev->rect().y() / scale, ev->rect().width() / scale, ev->rect().height() / scale); + + if (sourceRect.width() * sourceRect.height() < 500 * 500) { + painter.drawImage(targetRect.topLeft(), m_image.copy(sourceRect.toRect()).scaled(targetRect.toRect().size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation)); + + } else { + painter.drawImage(targetRect, m_image, sourceRect); + } + + return; + } + painter.scale(scale, scale); + QPoint center(width() / 2, height() / 2); + painter.translate(center); + painter.rotate(m_rotation); + painter.translate(center * -1); + QPoint upperLeft; + if (width() > m_image.width() * scale) + upperLeft.setX(center.x() - scale*m_image.width() / 2); + if (height() > m_image.height() * scale) + upperLeft.setY(center.y() - scale*m_image.height() / 2); + painter.drawImage(upperLeft, m_image); +} diff --git a/pool/shard007/C++/0094894_png_stream_wrappers.cpp b/pool/shard007/C++/0094894_png_stream_wrappers.cpp new file mode 100644 index 0000000000000000000000000000000000000000..94d5dc1dabf151a3da4cc53373d05a8f093149be --- /dev/null +++ b/pool/shard007/C++/0094894_png_stream_wrappers.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include <algorithm> +#include <iterator> + +#include <jni.h> +#include <png.h> + +#include "exceptions.h" +#include "java_globals.h" +#include "png_stream_wrappers.h" + +namespace facebook { +namespace imagepipeline { +namespace png { + +void pngNoOpFlush(png_structp png_ptr) { +} + +void pngWriteToJavaOutputStream( + png_structp png_ptr, + png_bytep data, + png_size_t length) { + PngOutputStreamWrapper* os_wrapper = + reinterpret_cast<PngOutputStreamWrapper*>(png_get_io_ptr(png_ptr)); + os_wrapper->write(png_ptr, data, length); +} + +PngOutputStreamWrapper::PngOutputStreamWrapper( + JNIEnv* env, + jobject os, + const int bufferSize) + : env_(env), os_(os), bufferSize_(bufferSize) { + buffer_ = env_->NewByteArray(bufferSize_); + RETURN_IF_EXCEPTION_PENDING; +} + +void PngOutputStreamWrapper::write( + png_structp png_ptr, + png_bytep data, + png_size_t length) { + while (length > 0) { + const int portion_length = std::min<int>(bufferSize_, length); + env_->SetByteArrayRegion( + buffer_, + 0, + reinterpret_cast<jsize>(portion_length), + reinterpret_cast<jbyte*>(data)); + if (env_->ExceptionCheck()) { + png_error(png_ptr, "Error when copying data to java array."); + } + env_->CallVoidMethod( + os_, + midOutputStreamWriteWithBounds, + buffer_, + 0, + reinterpret_cast<jint>(portion_length)); + if (env_->ExceptionCheck()) { + png_error(png_ptr, "Error when writing data to OutputStream."); + } + std::advance(data, portion_length); + length -= portion_length; + } +} + +} } } diff --git a/pool/shard007/C++/0094897_jsmokeapp.cpp b/pool/shard007/C++/0094897_jsmokeapp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..facef225ebb3c1175953e43ba41ad4e57db088a1 --- /dev/null +++ b/pool/shard007/C++/0094897_jsmokeapp.cpp @@ -0,0 +1,39 @@ +/**************************************************************************** +** +** Copyright (C) 2007-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the QtScript project on Trolltech Labs. +** +** This file may be used under the terms of the GNU General Public +** License version 2.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of +** this file. Please review the following information to ensure GNU +** General Public Licensing requirements will be met: +** http://www.trolltech.com/products/qt/opensource.html +** +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://www.trolltech.com/products/qt/licensing.html or contact the +** sales department at sales@trolltech.com. +** +** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +** +****************************************************************************/ + +#include <QtCore/QStringList> +#include <QtGui/QApplication> +#include <QtScript/QScriptEngine> + +extern QScriptEngine * initializeEngine(); +extern int run(QScriptEngine * engine, const QString& fileName); + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + QScriptEngine * engine = initializeEngine(); + engine->importExtension("jsmoke.qtcore"); + engine->importExtension("jsmoke.qtgui"); + run(engine, QString::fromLatin1(argv[1])); + return app.exec(); +} \ No newline at end of file diff --git a/pool/shard007/C++/0094899_AttachmentsProperty.cpp b/pool/shard007/C++/0094899_AttachmentsProperty.cpp new file mode 100644 index 0000000000000000000000000000000000000000..64f53d802f130d6d3771eee1a4f74aa2481b4416 --- /dev/null +++ b/pool/shard007/C++/0094899_AttachmentsProperty.cpp @@ -0,0 +1,219 @@ +#include <memory> + +/* + Copyright (C) 2018 Erik Ogenvik + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include "AttachmentsProperty.h" +#include "BaseWorld.h" +#include "ModeDataProperty.h" +#include "common/operations/Update.h" +#include "common/Inheritance.h" +#include "rules/LocatedEntity.h" +#include "rules/entityfilter/ProviderFactory.h" +#include <Atlas/Objects/Operation.h> + +AttachmentsProperty::AttachmentsProperty(uint32_t flags) + : PropertyBase(flags) +{ + +} + +void AttachmentsProperty::install(LocatedEntity& entity, const std::string& name) +{ + entity.installDelegate(Atlas::Objects::Operation::WIELD_NO, name); +} + +void AttachmentsProperty::remove(LocatedEntity& entity, const std::string& name) +{ + entity.removeDelegate(Atlas::Objects::Operation::WIELD_NO, name); +} + +HandlerResult AttachmentsProperty::operation(LocatedEntity& entity, const Operation& op, OpVector& res) +{ + if (!op->getArgs().empty()) { + auto& arg = op->getArgs().front(); + //Check if it's this attach point that's being affected + Atlas::Message::Element attachment_name; + if (arg->copyAttr("attachment", attachment_name) == 0 && attachment_name.isString()) { + auto attachmentI = m_data.find(attachment_name.String()); + + if (attachmentI != m_data.end()) { + std::string entity_id; + if (!arg->isDefaultId()) { + entity_id = arg->getId(); + } + + //Check if something already is attached, and detach it if so + + std::string attached_prop_name = std::string("attached_") + attachment_name.String(); + + Ref<LocatedEntity> existing_entity; + + auto attachedProp = entity.getPropertyClass<SoftProperty>(attached_prop_name); + if (attachedProp) { + existing_entity = extractEntityRef(attachedProp->data()); + } + + //If we're attaching an entity which is already attached at the same attachment just bail now. + if (existing_entity) { + if (entity_id == existing_entity->getId()) { + //Entity is already attached, do nothing + return OPERATION_BLOCKED; + } + } + + auto resetExistingEntityPlantedOn = [&]() { + if (existing_entity) { + auto existing_entity_mode_data_prop = existing_entity->modPropertyClassFixed<ModeDataProperty>(); + if (existing_entity_mode_data_prop) { + existing_entity_mode_data_prop->clearData(); + existing_entity->applyProperty(*existing_entity_mode_data_prop); + existing_entity->enqueueUpdateOp(); + } + } + }; + + if (entity_id.empty()) { + //Unwielding + + entity.setAttr(attached_prop_name, {}); + + //Check if there was another entity attached to the attachment, and if so reset it's attachment. + resetExistingEntityPlantedOn(); + + entity.enqueueUpdateOp(); + + } else { + + auto new_entity = BaseWorld::instance().getEntity(entity_id); + if (new_entity) { + auto& attachment = attachmentI->second; + + //Check that the attached entity matches the constraint filter + if (attachment.filter) { + EntityFilter::QueryContext queryContext{entity, &entity, new_entity.get()}; + std::vector<std::string> errors; + queryContext.report_error_fn = [&](const std::string& error) { errors.push_back(error); }; + queryContext.entity_lookup_fn = [](const std::string& id) { return BaseWorld::instance().getEntity(id); }; + queryContext.type_lookup_fn = [](const std::string& id) { return Inheritance::instance().getType(id); }; + if (!attachment.filter->match(queryContext)) { + if (errors.empty()) { + entity.clientError(op, String::compose("Attached entity failed the constraint '%1'.", attachment.contraint), res, entity.getId()); + } else { + entity.clientError(op, errors.front(), res, entity.getId()); + } + return OPERATION_BLOCKED; + } + } + //Check if the entity already is attached, and if so abort. The client needs to first send a detach/unwield op in this case. + auto& modeDataProp = new_entity->requirePropertyClassFixed<ModeDataProperty>(); + if (modeDataProp.getMode() == ModeProperty::Mode::Planted) { + auto& plantedOnData = modeDataProp.getPlantedOnData(); + //Check if the entity is attached to ourselves; if so we can just detach it from ourselves. + //Otherwise we need to abort, since we don't allow ourselves to detach it from another entity. + if (plantedOnData.entityId && plantedOnData.entityId == entity.getIntId()) { + if (plantedOnData.attachment) { + //We need to reset the old attached value for the attached entity + auto old_attached_prop_name = std::string("attached_") + *plantedOnData.attachment; + auto oldAttachedProp = entity.modPropertyClass<SoftProperty>(old_attached_prop_name); + if (oldAttachedProp) { + oldAttachedProp->data() = Atlas::Message::Element(); + entity.applyProperty(old_attached_prop_name, *oldAttachedProp); + } + } + } else { + entity.clientError(op, "The entity is already attached to another entity.", res, entity.getId()); + return OPERATION_BLOCKED; + } + } + + modeDataProp.setPlantedData(ModeDataProperty::PlantedOnData{entity.getIntId(), attachment_name.String()}); + + new_entity->applyProperty(modeDataProp); + new_entity->enqueueUpdateOp(); + + entity.setAttrValue(attached_prop_name, Atlas::Message::MapType{{"$eid", new_entity->getId()}}); + + //Check if there was another entity attached to the attachment, and if so reset it's attachment. + resetExistingEntityPlantedOn(); + + entity.enqueueUpdateOp(); + + } else { + entity.clientError(op, "Could not find wielded entity.", res, entity.getId()); + } + } + return OPERATION_BLOCKED; + } + } + } + return OPERATION_IGNORED; +} + +AttachmentsProperty* AttachmentsProperty::copy() const +{ + //Don't copy values. + return new AttachmentsProperty(); +} + +int AttachmentsProperty::get(Atlas::Message::Element& val) const +{ + Atlas::Message::MapType map; + for (auto& entry : m_data) { + map.emplace(entry.first, entry.second.contraint); + } + val = std::move(map); + return 0; +} + +void AttachmentsProperty::set(const Atlas::Message::Element& val) +{ + m_data.clear(); + if (val.isMap()) { + for (auto& entry : val.Map()) { + if (entry.second.isString() && !entry.second.String().empty()) { + try { + EntityFilter::ProviderFactory factory{}; + Attachment attachment{ + entry.second.String(), + std::make_unique<EntityFilter::Filter>(entry.second.String(), factory) + }; + m_data.emplace(entry.first, std::move(attachment)); + } catch (const std::invalid_argument& e) { + log(WARNING, String::compose( + "Error when creating entity filter for attachment with constraint '%1'.: \n%2", + entry.second.String(), + e.what()) + ); + } + } + } + } + +} + +Ref<LocatedEntity> AttachmentsProperty::extractEntityRef(const Atlas::Message::Element& val) +{ + if (val.isMap()) { + auto I = val.Map().find("$eid"); + if (I != val.Map().end() && I->second.isString()) { + return BaseWorld::instance().getEntity(I->second.String()); + } + } + return Ref<LocatedEntity>(); +} diff --git a/pool/shard007/C++/0094900_square_osc.cpp b/pool/shard007/C++/0094900_square_osc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d5b997fde969823b36b096449e0b44389b51a52a --- /dev/null +++ b/pool/shard007/C++/0094900_square_osc.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2015-2016 Immo Software + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o 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. + * + * o 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. + */ + +#include "square_osc.h" +#include "arm_math.h" +#include <string.h> +#include <assert.h> + +using namespace slab; + +//------------------------------------------------------------------------------ +// Code +//------------------------------------------------------------------------------ + +void SquareGenerator::init() +{ + m_halfPhaseWidth = m_sampleRate / m_freq / 2.0f; + + m_env.set_sample_rate(get_sample_rate()); + m_env.set_curve_type(ASREnvelope::kAttack, AudioRamp::kLinear); + m_env.set_curve_type(ASREnvelope::kRelease, AudioRamp::kLinear); + m_env.set_peak(1.0f); +} + +void SquareGenerator::process(float * samples, uint32_t count) +{ + // Check for a trigger. + Sequencer::Event triggerEvent = m_seq->get_next_event(count); + int32_t triggerSample = triggerEvent.m_timestamp; + if (triggerEvent.m_event == Sequencer::kNoteStopEvent) + { + m_env.set_release_offset(triggerSample); + triggerSample = -1; + } + bool needsRestartOnZeroCrossing = false; + float previous = m_previous; + float * sample = samples; + int i; + for (i = 0; i < count; ++i) + { + // Detect trigger point. + if (triggerSample == i) + { + needsRestartOnZeroCrossing = true; + } + + float f = 1.0f; + if (m_phase > m_halfPhaseWidth) + { + f = -1.0f; + } + float v = f * m_env.next(); + *sample++ = v; + + // After triggered, restart on a zero crossing to prevent popping. + bool zeroCrossing = ((previous >= 0.0f && v <= 0.0f) || (previous <= 0.0f && v >= 0.0f)); + if (needsRestartOnZeroCrossing && zeroCrossing) + { + m_env.trigger(); + m_phase = 0.0f; + needsRestartOnZeroCrossing = false; + } + + m_phase += 1.0f; + if (m_phase >= m_halfPhaseWidth * 2.0f) + { + m_phase = 0.0f; + } + + previous = v; + } + + m_previous = previous; +} + +//------------------------------------------------------------------------------ +// EOF +//------------------------------------------------------------------------------ diff --git a/pool/shard007/C++/0094901_compile_only_service.cc b/pool/shard007/C++/0094901_compile_only_service.cc new file mode 100644 index 0000000000000000000000000000000000000000..8c76e912011cb4fb78d0b4dd3b971604fd59234f --- /dev/null +++ b/pool/shard007/C++/0094901_compile_only_service.cc @@ -0,0 +1,121 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "tensorflow/compiler/xla/service/compile_only_service.h" + +#include <string> +#include <utility> +#include <vector> + +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/xla/debug_options_flags.h" +#include "tensorflow/compiler/xla/service/backend.h" +#include "tensorflow/compiler/xla/service/computation_layout.h" +#include "tensorflow/compiler/xla/service/dump.h" +#include "tensorflow/compiler/xla/service/platform_util.h" +#include "tensorflow/compiler/xla/status_macros.h" +#include "tensorflow/compiler/xla/types.h" +#include "tensorflow/compiler/xla/util.h" +#include "tensorflow/core/lib/gtl/cleanup.h" +#include "tensorflow/core/lib/io/path.h" +#include "tensorflow/core/platform/host_info.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/stream_executor_no_cuda.h" + +namespace xla { + +/* static */ StatusOr<std::unique_ptr<CompileOnlyService>> +CompileOnlyService::NewService(se::Platform* platform) { + ServiceOptions default_options; + default_options.set_platform(platform); + return NewService(default_options); +} + +/* static */ StatusOr<std::unique_ptr<CompileOnlyService>> +CompileOnlyService::NewService(const ServiceOptions& options) { + se::Platform* platform = options.platform(); + if (platform == nullptr) { + TF_ASSIGN_OR_RETURN(platform, PlatformUtil::GetDefaultPlatform()); + } + + TF_ASSIGN_OR_RETURN(auto compiler, Compiler::GetForPlatform(platform)); + + std::unique_ptr<CompileOnlyService> service( + new CompileOnlyService(options, compiler)); + return std::move(service); +} + +CompileOnlyService::CompileOnlyService(const ServiceOptions& options, + Compiler* compiler) + : Service(options, /*execute_backend=*/nullptr), compiler_(compiler) {} + +StatusOr<std::vector<std::unique_ptr<AotCompilationResult>>> +CompileOnlyService::CompileAheadOfTime( + const absl::Span<const AotXlaComputationInstance> computations, + const AotCompilationOptions& options, + std::unique_ptr<AotCompilationMetadata>* metadata) { + std::vector<std::unique_ptr<HloModule>> hlo_modules; + + const DebugOptions& debug_options = options.debug_options(); + ExecutionOptions execution_options; + *execution_options.mutable_debug_options() = debug_options; + // Capture replica_count, num_cores, and device_assignment in ExecutionOptions + // to later save in a proto dump. + if (options.replica_count() > 0) { + execution_options.set_num_replicas(options.replica_count()); + if (options.has_static_device_assignment()) { + CHECK_EQ(options.replica_count(), + options.static_device_assignment().replica_count()); + } + } + if (options.num_cores() > 0) { + execution_options.set_num_partitions(options.num_cores()); + if (options.has_static_device_assignment()) { + CHECK_EQ(options.num_cores(), + options.static_device_assignment().computation_count()); + } + } + if (options.has_static_device_assignment()) { + TF_RETURN_IF_ERROR(options.static_device_assignment().Serialize( + execution_options.mutable_device_assignment())); + } + for (const AotXlaComputationInstance& instance : computations) { + TF_RET_CHECK(instance.computation.has_host_program_shape()); + *execution_options.mutable_shape_with_output_layout() = + instance.result_layout->ToProto(); + + TF_ASSIGN_OR_RETURN( + std::unique_ptr<HloModuleConfig> module_config, + CreateModuleConfig( + ProgramShape(instance.computation.host_program_shape()), + instance.argument_layouts, &execution_options, &options)); + + TF_ASSIGN_OR_RETURN( + std::unique_ptr<HloModule> hlo_module, + HloModule::CreateFromProto(instance.computation, *module_config)); + DumpHloModuleIfEnabled(*hlo_module, "before_optimizations"); + hlo_modules.push_back(std::move(hlo_module)); + } + + execution_options.clear_shape_with_output_layout(); + DumpExecutionOptions(execution_options, debug_options); + + return compiler_->CompileAheadOfTime( + absl::make_unique<HloModuleGroup>(hlo_modules[0]->name(), + absl::MakeSpan(hlo_modules)), + options, metadata); +} + +} // namespace xla diff --git a/pool/shard007/C++/0094902_PackedSyncPtrTest.cpp b/pool/shard007/C++/0094902_PackedSyncPtrTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f926d6ff287c1bba11ade4c2b9201271628be923 --- /dev/null +++ b/pool/shard007/C++/0094902_PackedSyncPtrTest.cpp @@ -0,0 +1,137 @@ +/* + * Copyright 2014 Facebook, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include <folly/PackedSyncPtr.h> + +#include <cinttypes> +#include <gtest/gtest.h> +#include <thread> +#include <unordered_map> +#include <utility> + +using folly::PackedSyncPtr; + +namespace { + +// Compile time check for packability. This requires that +// PackedSyncPtr is a POD struct on gcc. +FOLLY_PACK_PUSH +struct ignore { PackedSyncPtr<int> foo; char c; } FOLLY_PACK_ATTR; +FOLLY_PACK_POP +static_assert(sizeof(ignore) == 9, "PackedSyncPtr wasn't packable"); + +} + +TEST(PackedSyncPtr, Basic) { + PackedSyncPtr<std::pair<int,int>> sp; + sp.init(new std::pair<int,int>[2]); + EXPECT_EQ(sizeof(sp), 8); + sp->first = 5; + EXPECT_EQ(sp[0].first, 5); + sp[1].second = 7; + EXPECT_EQ(sp[1].second, 7); + sp.lock(); + EXPECT_EQ(sp[1].second, 7); + sp[0].first = 9; + EXPECT_EQ(sp->first, 9); + sp.unlock(); + EXPECT_EQ((sp.get() + 1)->second, 7); + + sp.lock(); + EXPECT_EQ(sp.extra(), 0); + sp.setExtra(0x13); + EXPECT_EQ(sp.extra(), 0x13); + EXPECT_EQ((sp.get() + 1)->second, 7); + delete[] sp.get(); + auto newP = new std::pair<int,int>(); + sp.set(newP); + EXPECT_EQ(sp.extra(), 0x13); + EXPECT_EQ(sp.get(), newP); + sp.unlock(); + delete sp.get(); +} + +// Here we use the PackedSyncPtr to lock the whole SyncVec (base, *base, and sz) +template<typename T> +struct SyncVec { + PackedSyncPtr<T> base; + SyncVec() { base.init(); } + ~SyncVec() { free(base.get()); } + void push_back(const T& t) { + base.set((T*) realloc(base.get(), + (base.extra() + 1) * sizeof(T))); + base[base.extra()] = t; + base.setExtra(base.extra() + 1); + } + void lock() { + base.lock(); + } + void unlock() { + base.unlock(); + } + + T* begin() const { return base.get(); } + T* end() const { return base.get() + base.extra(); } +}; +typedef SyncVec<intptr_t> VecT; +typedef std::unordered_map<int64_t, VecT> Map; +const int mapCap = 1317; +const int nthrs = 297; +static Map map(mapCap); + +// Each app thread inserts it's ID into every vec in map +// map is read only, so doesn't need any additional locking +void appThread(intptr_t id) { + for (auto& kv : map) { + kv.second.lock(); + kv.second.push_back(id); + kv.second.unlock(); + } +} + +TEST(PackedSyncPtr, Application) { + for (int64_t i = 0; i < mapCap / 2; ++i) { + map.insert(std::make_pair(i, VecT())); + } + std::vector<std::thread> thrs; + for (intptr_t i = 0; i < nthrs; i++) { + thrs.push_back(std::thread(appThread, i)); + } + for (auto& t : thrs) { + t.join(); + } + + for (auto& kv : map) { + // Make sure every thread successfully inserted it's ID into every vec + std::set<intptr_t> idsFound; + for (auto& elem : kv.second) { + EXPECT_TRUE(idsFound.insert(elem).second); // check for dups + } + EXPECT_EQ(idsFound.size(), nthrs); // check they are all there + } +} + +TEST(PackedSyncPtr, extraData) { + PackedSyncPtr<int> p; + p.init(); + int* unaligned = reinterpret_cast<int*>(0xf003); + p.lock(); + p.set(unaligned); + uintptr_t* bytes = reinterpret_cast<uintptr_t*>(&p); + LOG(INFO) << "Bytes integer is: 0x" << std::hex << *bytes; + EXPECT_EQ(p.get(), unaligned); + p.unlock(); +} diff --git a/pool/shard007/C++/0094905_c_locale.cc b/pool/shard007/C++/0094905_c_locale.cc new file mode 100644 index 0000000000000000000000000000000000000000..262681b8983169b4b8c1970980dcb89c3a2e3ec3 --- /dev/null +++ b/pool/shard007/C++/0094905_c_locale.cc @@ -0,0 +1,107 @@ +// Wrapper for underlying C-language localization -*- C++ -*- + +// Copyright (C) 2001, 2002, 2009, 2010 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// Under Section 7 of GPL version 3, you are granted additional +// permissions described in the GCC Runtime Library Exception, version +// 3.1, as published by the Free Software Foundation. + +// You should have received a copy of the GNU General Public License and +// a copy of the GCC Runtime Library Exception along with this program; +// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see +// <http://www.gnu.org/licenses/>. + +// +// ISO C++ 14882: 22.8 Standard locale categories. +// + +// Written by Benjamin Kosnik <bkoz@redhat.com> + +#include <locale> + +namespace std +{ + void + locale::facet::_S_create_c_locale(__c_locale&, const char*, __c_locale*) + { } + + void + locale::facet::_S_destroy_c_locale(__c_locale&) + { } + + __c_locale + locale::facet::_S_clone_c_locale(__c_locale&) throw() + { return __c_locale(); } + + template<> + void + numpunct<char>::_M_initialize_numpunct(__c_locale) + { + // "C" locale + _M_decimal_point = '.'; + _M_thousands_sep = ','; + _M_grouping = ""; + _M_truename = "true"; + _M_falsename = "false"; + } + +#ifdef _GLIBCXX_USE_WCHAR_T + template<> + void + numpunct<wchar_t>::_M_initialize_numpunct(__c_locale) + { + // "C" locale + _M_decimal_point = L'.'; + _M_thousands_sep = L','; + _M_grouping = ""; + _M_truename = L"true"; + _M_falsename = L"false"; + } +#endif + + template<> + void + moneypunct<char>::_M_initialize_moneypunct(__c_locale) + { + // "C" locale + _M_decimal_point = '.'; + _M_thousands_sep = ','; + _M_grouping = ""; + _M_curr_symbol = string_type(); + _M_positive_sign = string_type(); + _M_negative_sign = string_type(); + _M_frac_digits = 0; + _M_pos_format = money_base::_S_default_pattern; + _M_neg_format = money_base::_S_default_pattern; + } + +#ifdef _GLIBCXX_USE_WCHAR_T + template<> + void + moneypunct<wchar_t>::_M_initialize_moneypunct(__c_locale) + { + // "C" locale + _M_decimal_point = L'.'; + _M_thousands_sep = L','; + _M_grouping = ""; + _M_curr_symbol = string_type(); + _M_positive_sign = string_type(); + _M_negative_sign = string_type(); + _M_frac_digits = 0; + _M_pos_format = money_base::_S_default_pattern; + _M_neg_format = money_base::_S_default_pattern; + } +#endif +} // namespace std + diff --git a/pool/shard007/C++/0094906_settings_test_util.cc b/pool/shard007/C++/0094906_settings_test_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..951ea118a55a6ac8cad18f5c37ab8cafc3e1dda3 --- /dev/null +++ b/pool/shard007/C++/0094906_settings_test_util.cc @@ -0,0 +1,154 @@ +// Copyright (c) 2012 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 "chrome/browser/extensions/settings/settings_test_util.h" + +#include "base/file_path.h" +#include "chrome/common/extensions/extension.h" +#include "chrome/browser/extensions/settings/settings_frontend.h" + +namespace extensions { + +namespace settings_test_util { + +// Intended as a StorageCallback from GetStorage. +static void AssignStorage(ValueStore** dst, ValueStore* src) { + *dst = src; +} + +ValueStore* GetStorage( + const std::string& extension_id, + settings_namespace::Namespace settings_namespace, + SettingsFrontend* frontend) { + ValueStore* storage = NULL; + frontend->RunWithStorage( + extension_id, + settings_namespace, + base::Bind(&AssignStorage, &storage)); + MessageLoop::current()->RunAllPending(); + return storage; +} + +ValueStore* GetStorage( + const std::string& extension_id, SettingsFrontend* frontend) { + return GetStorage(extension_id, settings_namespace::SYNC, frontend); +} + +// MockExtensionService + +MockExtensionService::MockExtensionService() {} + +MockExtensionService::~MockExtensionService() {} + +const Extension* MockExtensionService::GetExtensionById( + const std::string& id, bool include_disabled) const { + std::map<std::string, scoped_refptr<Extension> >::const_iterator + maybe_extension = extensions_.find(id); + return maybe_extension == extensions_.end() ? + NULL : maybe_extension->second.get(); +} + +void MockExtensionService::AddExtensionWithId( + const std::string& id, Extension::Type type) { + std::set<std::string> empty_permissions; + AddExtensionWithIdAndPermissions(id, type, empty_permissions); +} + +void MockExtensionService::AddExtensionWithIdAndPermissions( + const std::string& id, + Extension::Type type, + const std::set<std::string>& permissions_set) { + DictionaryValue manifest; + manifest.SetString("name", std::string("Test extension ") + id); + manifest.SetString("version", "1.0"); + + scoped_ptr<ListValue> permissions(new ListValue()); + for (std::set<std::string>::const_iterator it = permissions_set.begin(); + it != permissions_set.end(); ++it) { + permissions->Append(Value::CreateStringValue(*it)); + } + manifest.Set("permissions", permissions.release()); + + switch (type) { + case Extension::TYPE_EXTENSION: + break; + + case Extension::TYPE_PACKAGED_APP: { + DictionaryValue* app = new DictionaryValue(); + DictionaryValue* app_launch = new DictionaryValue(); + app_launch->SetString("local_path", "fake.html"); + app->Set("launch", app_launch); + manifest.Set("app", app); + break; + } + + default: + NOTREACHED(); + } + + std::string error; + scoped_refptr<Extension> extension(Extension::Create( + FilePath(), + Extension::INTERNAL, + manifest, + Extension::NO_FLAGS, + id, + &error)); + DCHECK(extension.get()); + DCHECK(error.empty()); + extensions_[id] = extension; + + for (std::set<std::string>::const_iterator it = permissions_set.begin(); + it != permissions_set.end(); ++it) { + DCHECK(extension->HasAPIPermission(*it)); + } +} + +// MockProfile + +MockProfile::MockProfile(const FilePath& file_path) + : TestingProfile(file_path) { + event_router_.reset(new EventRouter(this)); +} + +MockProfile::~MockProfile() {} + +MockExtensionService* MockProfile::GetMockExtensionService() { + return &extension_service_; +} + +ExtensionService* MockProfile::GetExtensionService() { + ExtensionServiceInterface* as_interface = + static_cast<ExtensionServiceInterface*>(&extension_service_); + return static_cast<ExtensionService*>(as_interface); +} + +EventRouter* MockProfile::GetExtensionEventRouter() { + return event_router_.get(); +} + +// ScopedSettingsFactory + +ScopedSettingsStorageFactory::ScopedSettingsStorageFactory() {} + +ScopedSettingsStorageFactory::ScopedSettingsStorageFactory( + const scoped_refptr<SettingsStorageFactory>& delegate) + : delegate_(delegate) {} + +ScopedSettingsStorageFactory::~ScopedSettingsStorageFactory() {} + +void ScopedSettingsStorageFactory::Reset( + const scoped_refptr<SettingsStorageFactory>& delegate) { + delegate_ = delegate; +} + +ValueStore* ScopedSettingsStorageFactory::Create( + const FilePath& base_path, const std::string& extension_id) { + DCHECK(delegate_.get()); + return delegate_->Create(base_path, extension_id); +} + +} // namespace settings_test_util + +} // namespace extensions diff --git a/pool/shard007/C++/0094907_Test.cpp b/pool/shard007/C++/0094907_Test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..756eadc9415385c2a8adbe347137ea56259665aa --- /dev/null +++ b/pool/shard007/C++/0094907_Test.cpp @@ -0,0 +1,152 @@ +#include "cute.h" +#include "ide_listener.h" +#include "xml_listener.h" +#include "cute_runner.h" +#include "../indexableSet.h" + + +void itHasDefaultConstructor() { + indexableSet<std::string> a; + ASSERT_EQUAL(0, a.size()); +} +void itHasRangeConstructor() { + std::set<std::string> const a { "foo", "bar", "baz" }; + indexableSet<std::string> b(a.begin(), a.end()); + ASSERT_EQUAL(3, b.size()); +} +void itHasCopyConstructor() { + indexableSet<std::string> a; + a.insert("foo"); + indexableSet<std::string> b(a); + ASSERT_EQUAL(1, b.size()); +} +void itHasMoveConstructor() { + indexableSet<std::string> a; + a.insert("foo"); + indexableSet<std::string> b(std::move(a)); + ASSERT_EQUAL(1, b.size()); +} +void itHasInitializerListConstructor() { + indexableSet<std::string> a { "foo", "bar" }; + ASSERT_EQUAL(2, a.size()); +} +void itCanInsert() { + indexableSet<std::string> a; + a.insert("foo"); + ASSERT_EQUAL(1, a.size()); +} +void itActsAsSetWhenInserting() { + indexableSet<std::string> a; + a.insert("bar"); + a.insert("bar"); + ASSERT_EQUAL(1, a.size()); +} +void itAccessesInSortedOrder() { + indexableSet<int> a { 1, 5, 2 }; + auto it = a.begin(); + ASSERT_EQUAL(1, *it++); + ASSERT_EQUAL(2, *it++); + ASSERT_EQUAL(5, *it++); +} +void itCanAccessWithPositiveIndex() { + indexableSet<std::string> a { "bar", "baz", "foo", "quu" }; + ASSERT_EQUAL("bar", a[0]); + ASSERT_EQUAL("baz", a[1]); + ASSERT_EQUAL("foo", a[2]); + ASSERT_EQUAL("quu", a[3]); +} +void itCanAccessWithNegativeIndex() { + indexableSet<std::string> a { "bar", "baz", "foo", "quu" }; + ASSERT_EQUAL("bar", a[0]); + ASSERT_EQUAL("quu", a[-1]); + ASSERT_EQUAL("foo", a[-2]); + ASSERT_EQUAL(a[0], a[-a.size()]); +} + +void itHasFront() { + indexableSet<std::string> a { "foo", "bar" }; + ASSERT_EQUAL("bar", a.front()); +} + +void itHasMutableFront() { + indexableSet<std::string> a { "a", "b" }; + a.front() = "c"; +} + +void itHasMutableFrontAndCanBreakSet() { + indexableSet<std::string> a { "a", "b" }; + a.front() = "c"; + ASSERT_EQUAL("c", a.front()); +} + +void itHasBack() { + indexableSet<std::string> a { "foo", "bar" }; + ASSERT_EQUAL("foo", a.back()); +} + +void itHasAt() { + indexableSet<std::string> a { "foo", "bar" }; + ASSERT_EQUAL("bar", a.at(0)); +} + +void itThrowsExceptionWhenIndexOutOfBound() { + indexableSet<std::string> a { "foo", "bar" }; + ASSERT_THROWS(a[2], std::out_of_range); + ASSERT_THROWS(a[-3], std::out_of_range); +} + +void itThrowsExceptionWhenAccessingFrontOrBackOfEmptySet() { + indexableSet<std::string> a {}; + ASSERT_THROWS(a.front(), std::out_of_range); + ASSERT_THROWS(a.back(), std::out_of_range); +} + +void itThrowsExceptionWhenAccessingIndexMinusOneOnEmptySet() { + indexableSet<std::string> a {}; + ASSERT_THROWS(a[-1], std::out_of_range); +} + +void itCanUseCustomCompareFunctor() { + struct caselessCompare { + bool operator()(std::string const& lhs, std::string const& rhs) const { + return std::lexicographical_compare( + lhs.begin(), lhs.end(), rhs.begin(), rhs.end(), + [](char l, char r){ return std::tolower(l) < std::tolower(r); + }); + } + }; + + indexableSet<std::string, caselessCompare> const a { "foo", "FOO"}; + ASSERT_EQUAL(1, a.size()); +} + +void runAllTests(int argc, char const *argv[]){ + cute::suite s; + s.push_back(CUTE(itHasDefaultConstructor)); + s.push_back(CUTE(itHasRangeConstructor)); + s.push_back(CUTE(itHasCopyConstructor)); + s.push_back(CUTE(itHasMoveConstructor)); + s.push_back(CUTE(itHasInitializerListConstructor)); + s.push_back(CUTE(itCanInsert)); + s.push_back(CUTE(itActsAsSetWhenInserting)); + s.push_back(CUTE(itCanAccessWithPositiveIndex)); + s.push_back(CUTE(itCanAccessWithNegativeIndex)); + s.push_back(CUTE(itAccessesInSortedOrder)); + s.push_back(CUTE(itHasFront)); + s.push_back(CUTE(itHasBack)); + s.push_back(CUTE(itThrowsExceptionWhenIndexOutOfBound)); + s.push_back(CUTE(itThrowsExceptionWhenAccessingFrontOrBackOfEmptySet)); + s.push_back(CUTE(itCanUseCustomCompareFunctor)); + s.push_back(CUTE(itHasMutableFront)); + s.push_back(CUTE(itHasMutableFrontAndCanBreakSet)); + s.push_back(CUTE(itThrowsExceptionWhenAccessingIndexMinusOneOnEmptySet)); + s.push_back(CUTE(itHasAt)); + cute::xml_file_opener xmlfile(argc,argv); + cute::xml_listener<cute::ide_listener<> > lis(xmlfile.out); + cute::makeRunner(lis,argc,argv)(s, "AllTests"); +} + +int main(int argc, char const *argv[]){ + runAllTests(argc,argv); + return 0; +} diff --git a/pool/shard007/C++/0094911_TestCaseSandbox.cpp b/pool/shard007/C++/0094911_TestCaseSandbox.cpp new file mode 100644 index 0000000000000000000000000000000000000000..61e68f452c5aabde4bc9c063a2dcc721cd3fcf2f --- /dev/null +++ b/pool/shard007/C++/0094911_TestCaseSandbox.cpp @@ -0,0 +1,174 @@ + +#include <sys/types.h> +#include <sys/socket.h> + +#include <testngpp/comm/ExceptionKeywords.h> + +#include <testngpp/comm/PipeReadableChannel.h> + +#include <testngpp/internal/Error.h> +#include <testngpp/internal/TestCaseInfoReader.h> +#include <testngpp/internal/TestCase.h> + +#include <testngpp/listener/TestCaseResultCollector.h> + +#include <testngpp/runner/EOFError.h> +#include <testngpp/runner/TestCaseRunner.h> +#include <testngpp/runner/Sandbox.h> +#include <testngpp/runner/EnvironmentCleaner.h> +#include <testngpp/runner/TestCaseSandboxHandler.h> +#include <testngpp/runner/TestCaseSandboxResultDecoder.h> +#include <testngpp/runner/TestCaseSandbox.h> + + + +TESTNGPP_NS_START + +//////////////////////////////////////////////////////// +struct TestCaseSandboxImpl +{ + TestCaseSandboxImpl() + : testcase(0), sandbox(0), decoder(0), finished(false) + {} + + SandboxId getSandboxId() const + { return sandbox->getSandboxId(); } + + ChannelId getChannelId() const + { + return sandbox->getChannelId(); + } + + void handle() TESTNGPP_THROW(EOFError, Error); + + ~TestCaseSandboxImpl() + { + if(sandbox != 0) + delete sandbox; + + if(decoder != 0) + delete decoder; + } + + bool hasSucceeded() const + { return !decoder->hasError(); } + + const TestCase* testcase; // X + Sandbox* sandbox; // Y + TestCaseSandboxResultDecoder* decoder; // Y + bool finished; +}; + +//////////////////////////////////////////////////////// +void TestCaseSandboxImpl::handle() TESTNGPP_THROW(EOFError, Error) +{ + if(sandbox->isDead()) + { + return; + } + + __TESTNGPP_TRY + { + bool result = decoder->decode(); + if(result && !finished) + { + finished = true; + decoder->flush(false); + } + } + __TESTNGPP_CATCH(EOFError&) + { + if(!finished) + { + decoder->flush(true); + } + + sandbox->die(); + + finished = true; + } + __TESTNGPP_END_TRY +} + +//////////////////////////////////////////////////////// +TestCaseSandbox::TestCaseSandbox() + : This(new TestCaseSandboxImpl()) +{} + +//////////////////////////////////////////////////////// +TestCaseSandbox::~TestCaseSandbox() +{ + delete This; +} + +//////////////////////////////////////////////////////// +ChannelId TestCaseSandbox::getChannelId() const +{ + return This->getChannelId(); +} + +//////////////////////////////////////////////////////// +bool TestCaseSandbox::hasSucceeded() const +{ + return This->hasSucceeded(); +} + +const TestCase* +TestCaseSandbox::getTestCase() const +{ + return This->testcase; +} + +//////////////////////////////////////////////////////// +void +TestCaseSandbox::handle() TESTNGPP_THROW(EOFError, Error) +{ + This->handle(); +} + +//////////////////////////////////////////////////////// +bool +TestCaseSandbox::isDead() const +{ + return This->sandbox->isDead(); +} +//////////////////////////////////////////////////////// +void +TestCaseSandbox::cleanup() +{ + This->sandbox->cleanup(); +} +//////////////////////////////////////////////////////// +TestCaseSandbox* +TestCaseSandbox:: +createInstance + ( EnvironmentCleaner* cleaner + , const TestCase* testcase + , TestCaseRunner* runner + , TestCaseResultCollector* collector + , bool shouldReport) +{ + TestCaseSandboxHandler handler(testcase, runner); + Sandbox* sandbox = Sandbox::createInstance(cleaner, &handler); + if(sandbox == 0) + { + throw Error("system error: cannot create object"); + } + + TestCaseSandbox* tcSandbox = new TestCaseSandbox(); + + tcSandbox->This->decoder = \ + new TestCaseSandboxResultDecoder + ( new PipeReadableChannel(sandbox->getChannelId()) + , testcase + , collector + , shouldReport); + + tcSandbox->This->testcase = testcase; + tcSandbox->This->sandbox = sandbox; + + return tcSandbox; +} + +TESTNGPP_NS_END + diff --git a/pool/shard007/C++/0094914_QuerySelect.cpp b/pool/shard007/C++/0094914_QuerySelect.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4fd04887c84a9d77e3fbd709bcc8963ec583f526 --- /dev/null +++ b/pool/shard007/C++/0094914_QuerySelect.cpp @@ -0,0 +1,117 @@ +#include "Database.h" +#include "QuerySelect.h" + +namespace roxlu { + +QuerySelect::QuerySelect(Database& db) + :Query(db) + ,select_fields("*") + ,where_clause("") + ,order_clause("") + ,limit_clause("") +{ +} + +QuerySelect::QuerySelect(Database& db, const string& selectFields) + :Query(db) + ,select_fields(selectFields) + ,where_clause("") + ,order_clause("") + ,limit_clause("") +{ + +} + +QuerySelect::QuerySelect(const QuerySelect& other) + :Query(other.db) +{ + *this = other; +} + +QuerySelect& QuerySelect::operator=(const QuerySelect& other) { + if(this == &other) { + return *this; + } + printf("Copying QuerySelect\n"); + select_fields = other.select_fields; + from_table = other.from_table; + join_clause = other.join_clause; + where_clause = other.where_clause; + order_clause = other.order_clause; + limit_clause = other.limit_clause; + field_values = other.field_values; + return *this; +} + +QuerySelect::~QuerySelect() { +} + +QuerySelect& QuerySelect::from(const string& table) { + from_table = table; + return *this; +} + +QuerySelect& QuerySelect::join(const string& joinClause) { + join_clause = joinClause; + return *this; +} + +QuerySelect& QuerySelect::where(const string& whereClause) { + where_clause = whereClause; + return *this; +} + +QuerySelect& QuerySelect::order(const string& orderClause) { + order_clause = orderClause; + return *this; +} + +QuerySelect& QuerySelect::limit(const string& limitClause) { + limit_clause = limitClause; + return *this; +} + + +string QuerySelect::toString() { + string sql = ""; + sql.append("select "); + sql.append(select_fields); + sql.append(" from "); + sql.append(from_table); + + if(join_clause.length()) { + sql.append(" inner join "); + sql.append(join_clause); + sql.append(" "); + } + + if(where_clause.length()) { + sql.append(" where "); + sql.append(where_clause); + sql.append(" "); + } + + if(order_clause.length()) { + sql.append(" order by "); + sql.append(order_clause); + } + + if(limit_clause.length()) { + sql.append(" limit "); + sql.append(limit_clause); + } + + //printf("SQL: %s\n" , sql.c_str()); + return sql; + +} + +bool QuerySelect::execute(QueryResult& result) { + string sql = toString(); + if(!sql.length()) { + return false; + } + return result.execute(sql, field_values, Database::QUERY_SELECT); +} + +} // roxlu \ No newline at end of file diff --git a/pool/shard007/C++/0094916_background_renderer.cc b/pool/shard007/C++/0094916_background_renderer.cc new file mode 100644 index 0000000000000000000000000000000000000000..c701dbd9010f6d003fe30e892ae508ac097c8460 --- /dev/null +++ b/pool/shard007/C++/0094916_background_renderer.cc @@ -0,0 +1,113 @@ +/* + * Copyright 2017 Google Inc. 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. + */ + +// This modules handles drawing the passthrough camera image into the OpenGL +// scene. + +#include <type_traits> + +#include "platform_tools/android/apps/arcore/src/main/cpp/background_renderer.h" + +namespace hello_ar { + namespace { +// Positions of the quad vertices in clip space (X, Y, Z). + const GLfloat kVertices[] = { + -1.0f, -1.0f, 0.0f, +1.0f, -1.0f, 0.0f, + -1.0f, +1.0f, 0.0f, +1.0f, +1.0f, 0.0f, + }; + +// UVs of the quad vertices (S, T) + const GLfloat kUvs[] = { + 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, + }; + + constexpr char kVertexShader[] = R"( + attribute vec4 vertex; + attribute vec2 textureCoords; + varying vec2 v_textureCoords; + void main() { + v_textureCoords = textureCoords; + gl_Position = vertex; + })"; + + constexpr char kFragmentShader[] = R"( + #extension GL_OES_EGL_image_external : require + precision mediump float; + uniform samplerExternalOES texture; + varying vec2 v_textureCoords; + void main() { + gl_FragColor = texture2D(texture, v_textureCoords); + })"; + + } // namespace + + void BackgroundRenderer::InitializeGlContent() { + shader_program_ = util::CreateProgram(kVertexShader, kFragmentShader); + + if (!shader_program_) { + LOGE("Could not create program."); + } + + glGenTextures(1, &texture_id_); + glBindTexture(GL_TEXTURE_EXTERNAL_OES, texture_id_); + glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + uniform_texture_ = glGetUniformLocation(shader_program_, "texture"); + attribute_vertices_ = glGetAttribLocation(shader_program_, "vertex"); + attribute_uvs_ = glGetAttribLocation(shader_program_, "textureCoords"); + } + + void BackgroundRenderer::Draw(const ArSession *session, const ArFrame *frame) { + static_assert(std::extent<decltype(kUvs)>::value == kNumVertices * 2, + "Incorrect kUvs length"); + static_assert(std::extent<decltype(kVertices)>::value == kNumVertices * 3, + "Incorrect kVertices length"); + + // If display rotation changed (also includes view size change), we need to + // re-query the uv coordinates for the on-screen portion of the camera image. + int32_t geometry_changed = 0; + ArFrame_getDisplayGeometryChanged(session, frame, &geometry_changed); + if (geometry_changed != 0 || !uvs_initialized_) { + ArFrame_transformDisplayUvCoords(session, frame, kNumVertices * 2, kUvs, + transformed_uvs_); + uvs_initialized_ = true; + } + glUseProgram(shader_program_); + glDepthMask(GL_FALSE); + + glUniform1i(uniform_texture_, 1); + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_EXTERNAL_OES, texture_id_); + + glEnableVertexAttribArray(attribute_vertices_); + glVertexAttribPointer(attribute_vertices_, 3, GL_FLOAT, GL_FALSE, 0, + kVertices); + + glEnableVertexAttribArray(attribute_uvs_); + glVertexAttribPointer(attribute_uvs_, 2, GL_FLOAT, GL_FALSE, 0, + transformed_uvs_); + + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + + glUseProgram(0); + glDepthMask(GL_TRUE); + util::CheckGlError("BackgroundRenderer::Draw() error"); + } + + GLuint BackgroundRenderer::GetTextureId() const { return texture_id_; } + +} // namespace hello_ar diff --git a/pool/shard007/C++/0094918_cbodometry.cpp b/pool/shard007/C++/0094918_cbodometry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ab9f7894ece0fddd9b5fb540eae0e17bf89884f8 --- /dev/null +++ b/pool/shard007/C++/0094918_cbodometry.cpp @@ -0,0 +1,60 @@ +/*************************************************************************** + * Project: RAPI * + * Author: Jens Wawerla (jwawerla@sfu.ca) * + * $Id: $ + *************************************************************************** + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + **************************************************************************/ +#include "cbodometry.h" +#include "utilities.h" + +namespace Rapi { + +//----------------------------------------------------------------------------- +CCBOdometry::CCBOdometry(CCBDriver* driver, std::string devName) + : COdometry( devName ) +{ + mCBDriver = driver; +} +//----------------------------------------------------------------------------- +CCBOdometry::~CCBOdometry() +{ +} +//----------------------------------------------------------------------------- +void CCBOdometry::updateData( const double dt ) +{ + //double angle; + + mAngle = D2R ( mCBDriver->mCreateSensorPackage.angle ); + mDistance = ( float ) ( mCBDriver->mCreateSensorPackage.distance / 1e3 ); + + mPose.mYaw = normalizeAngle ( mPose.mYaw + mAngle ); + mPose.mX += mDistance * cos ( mPose.mYaw ); + mPose.mY += mDistance * sin ( mPose.mYaw ); + +// // Coordinate system tranformation +// angle = mCoordinateSystemOffset.mYaw; +// mPose.mX = mLocalPose.mX * cos( angle ) + mLocalPose.mY * sin( angle ) +// + mCoordinateSystemOffset.mX; +// mPose.mY = -mLocalPose.mX * sin( angle ) + mLocalPose.mY * cos( angle ) +// + mCoordinateSystemOffset.mY; +// mPose.mYaw = normalizeAngle( mLocalPose.mYaw - angle ); + // update time stamp of this measurement + mTimeStamp = timeStamp(); +} +//----------------------------------------------------------------------------- + +} // namespace diff --git a/pool/shard007/C++/0094920_BloomShader.cpp b/pool/shard007/C++/0094920_BloomShader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b57a3d1bb5ae08a2678b4251ae926b4c1762e15a --- /dev/null +++ b/pool/shard007/C++/0094920_BloomShader.cpp @@ -0,0 +1,30 @@ +// +// BloomShader.cpp +// GLModelViewer +// +// Created by Mattias Bergström on 2014-03-20. +// Copyright (c) 2014 Mattias Bergström. All rights reserved. +// + +#include "BloomShader.h" +#include "ShaderLoader.h" +#include "glm/gtc/matrix_inverse.hpp" + +void BloomShader::init() { + this->direction = BlurDirection::HORIZONTAL; + ShaderLoader& loader = ShaderLoader::getInstance(); + + this->programId = loader.loadShaderProgram("passthrough.vs", "bloom_shader.fs"); + + setupBufferBindings(); +} + +void BloomShader::setUniforms(glm::mat4 proj, glm::mat4 view, glm::mat4 model) { + Shader::setUniforms(proj, view, model); + + GLint textureSamplerId = glGetUniformLocation(this->programId, "texture_sampler"); + GLint directionId = glGetUniformLocation(this->programId, "direction"); + + glUniform1i(textureSamplerId, 0); + glUniform1i(directionId, direction); +} \ No newline at end of file diff --git a/pool/shard007/C++/0094923_Author.cpp b/pool/shard007/C++/0094923_Author.cpp new file mode 100644 index 0000000000000000000000000000000000000000..834ca9f933d9e83ae63c3abf5d0da1e8954944b6 --- /dev/null +++ b/pool/shard007/C++/0094923_Author.cpp @@ -0,0 +1,65 @@ +//Author class implementation +//Author: Nishanth Koganti +//Date: 2013/09/20 + +#include <iostream> +#include "Author.h" + +using namespace std; + +//Class Constructor +Author::Author(const std::string & name, const std::string & email, char gender): name(name) +{ + setEmail(email); + setGender(gender); +} + +//Class Setters +void Author::setEmail(const string & email) +{ + size_t atIndex = email.find('@'); + if(atIndex != string::npos && atIndex != 0 && atIndex != email.length()-1) + { + this->email = email; + } + else + { + cout << "Invalid email! Setting to empty string" << endl; + this->email = ""; + } +} + +void Author::setGender(char gender) +{ + if(gender == 'm' || gender == 'f') + { + this->gender = gender; + } + else + { + cout << "Invalid gender! Setting to 'u' (unknown)" << endl; + this->gender = 'u'; + } +} + +//Class Getters +string Author::getName() const +{ + return name; +} + +string Author::getEmail() const +{ + return email; +} + +char Author::getGender() const +{ + return gender; +} + +//Class Functions +void Author::print() const +{ + cout << name << " (" << gender << ") at " << email << endl; +} diff --git a/pool/shard007/C++/0094928_ImageSprite.cpp b/pool/shard007/C++/0094928_ImageSprite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ef56b48db119ddccb5a47b6b0ec86b548d94222a --- /dev/null +++ b/pool/shard007/C++/0094928_ImageSprite.cpp @@ -0,0 +1,120 @@ +/* + Copyright (c) 2015 chenbingfeng (iichenbf#gmail.com) + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + +#include "ImageSprite.h" +#include "Director.h" +#include <iostream> + +NS_L2D_BEGIN + +SPImageSprite ImageSprite::create(const std::string &fileName, int width, int height) +{ + if (!_staticInited) initStatic(); + return SPImageSprite(new ImageSprite(fileName, width, height)); +} + +ImageSprite::ImageSprite(const std::string& fileName, int width, int height): +_fileName(fileName), _width(width),_height(height){/*empty*/} + +void ImageSprite::load() +{ + if (_loaded) LOG("ImageSprite", _fileName, "already loaded."); + assert(!_loaded); + _loaded = true; + auto image = cppgl::Image::create(_fileName); + image->load(); + _texture = cppgl::Texture::create(image); + _texture->setWrapping(cppgl::Wrapping::Repeat, cppgl::Wrapping::Repeat); + _texture->setFilters(cppgl::Filter::Linear, cppgl::Filter::Linear); +} + +void ImageSprite::draw(SPRenderer renderer) +{ + auto context = renderer->getContext(); + context->useProgram(_program); + // setUniform must after useProgram + _program->setUniform(_program->getUniform("view"), Director::getInstance().getView()); + _program->setUniform(_program->getUniform("proj"), Director::getInstance().getProj()); + _program->setUniform(_program->getUniform("model"), getModel()); + context->bindTexture(_texture, 0); + context->drawArrays(*_vao, cppgl::Primitive::Triangles, 0, 6); +} + +//static area +bool ImageSprite::_staticInited = false; + +void ImageSprite::initStatic() +{ + _staticInited = true; + const char* vertexSource = + "#version 150\n" + "\n" + "in vec2 position;\n" + "in vec2 texcoord;\n" + "out vec2 Texcoord;\n" + "\n" + "uniform mat4 model;\n" + "uniform mat4 view;\n" + "uniform mat4 proj;\n" + "\n" + "void main()\n" + "{\n" + " Texcoord = vec2(texcoord.x, -texcoord.y);\n" + " gl_Position = proj * view * model * vec4(position, 0.0, 1.0);\n" + "}\n"; + + const char* fragmentSource = + "#version 150\n" + "\n" + "in vec2 Texcoord;\n" + "\n" + "out vec4 outColor;\n" + "uniform sampler2D tex;\n" + "\n" + "void main()\n" + "{\n" + " outColor = texture(tex, Texcoord);\n" + "}\n"; + + auto vert = cppgl::Shader::create(cppgl::ShaderType::Vertex, vertexSource); + auto frag = cppgl::Shader::create(cppgl::ShaderType::Fragment, fragmentSource); + _program = cppgl::Program::create(vert, frag); + + float vertices[] = { + -0.5f, -0.5f, 0.0f, 0.0f, + -0.5f, 0.5f, 0.0f, 1.0f, + 0.5f, 0.5f, 1.0f, 1.0f, + 0.5f, 0.5f, 1.0f, 1.0f, + 0.5f, -0.5f, 1.0f, 0.0f, + -0.5f, -0.5f, 0.0f, 0.0f + }; + _vbo = cppgl::VertexBuffer::create(vertices, sizeof(vertices), cppgl::BufferUsage::StaticDraw); + _vao = cppgl::VertexArray::create(); + _vao->bindAttribute(_program->getAttribute("position"), *_vbo, cppgl::Type::Float, 2, 4*sizeof(float), NULL); + _vao->bindAttribute(_program->getAttribute("texcoord"), *_vbo, cppgl::Type::Float, 2, 4*sizeof(float), 2*sizeof(float)); +} + +cppgl::SPVertexArray ImageSprite::_vao; +cppgl::SPVertexBuffer ImageSprite::_vbo; +cppgl::SPProgram ImageSprite::_program; + +NS_L2D_END diff --git a/pool/shard007/C++/0094930_PlotWndPropLog.cpp b/pool/shard007/C++/0094930_PlotWndPropLog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a37c0fb63cc419ec9f6500bb1453fccae94ea775 --- /dev/null +++ b/pool/shard007/C++/0094930_PlotWndPropLog.cpp @@ -0,0 +1,73 @@ +#include "stdafx.h" +#include "PlotWndPropLog.h" +#include "SeriesLog.h" +#include "HelperFunc.h" +#include "LogPlotWndProperty.h" + +/*********************************** + +Log Plot Wnd + +************************************/ + +char * PlotWndPropLog::GetText(size_t index) +{ + if (this->seriesInPlotWndProp.size() == 0) + return false; + + auto seriesLog = dynamic_cast<LogSeriesProp *>(this->seriesInPlotWndProp[0]); + ASSERT(seriesLog); + size_t size = seriesLog->DataSize(); + return seriesLog->GetData(size - 1 - index); +} + + +HRESULT PlotWndPropLog::CreateElementPlot(IXMLDOMDocument *pDom, IXMLDOMElement *pe) +{ + HRESULT hr=S_OK; + IXMLDOMElement *pSeries=NULL; + IXMLDOMElement *psub=NULL; + CreateAndAddElementNode(pDom, L"WndName", L"\n\t\t", pe, &psub); + psub->put_text((_bstr_t)this->GetName()); + CreateAndAddElementNode(pDom, L"WndNameIsSet", L"\n\t\t", pe, &psub); + psub->put_text((_bstr_t)this->nameIsSet); + //psub->Release(); + //no release + CreateAndAddElementNode(pDom, L"WndType", L"\n\t\t", pe, &psub); + psub->put_text(_bstr_t(typeid(*this).name())); + CreateAndAddElementNode(pDom, L"WndFrameCount", L"\n\t\t", pe, &psub); + psub->put_text((_bstr_t)this->frameCount); + + CreateAndAddElementNode(pDom, L"WndRectTLX", L"\n\t\t", pe, &psub); + psub->put_text((_bstr_t)this->rect.TopLeft().x); + + CreateAndAddElementNode(pDom, L"WndRectTLY", L"\n\t\t", pe, &psub); + psub->put_text((_bstr_t)this->rect.TopLeft().y); + + CreateAndAddElementNode(pDom, L"WndRectBRX", L"\n\t\t", pe, &psub); + psub->put_text((_bstr_t)this->rect.BottomRight().x); + + CreateAndAddElementNode(pDom, L"WndRectBRY", L"\n\t\t", pe, &psub); + psub->put_text((_bstr_t)this->rect.BottomRight().y); + + std::vector<SeriesProp *>::iterator iterSeries; + for (iterSeries = this->seriesInPlotWndProp.begin(); + iterSeries !=this->seriesInPlotWndProp.end(); + iterSeries++) + { + CreateAndAddElementNode(pDom, L"Series", L"\n\t\t", pe, &pSeries); + (*iterSeries)->CreateElementSeries(pDom,pSeries); + pSeries->Release(); + } + + return hr; +} + +BaseProperty * PlotWndPropLog::GetPropertyPage() +{ + BaseProperty * property = new LogPlotWndProperty; + property->SetTarget(this); + return property; +} + + diff --git a/pool/shard007/C++/0094934_kiosk_app_update_service_browsertest.cc b/pool/shard007/C++/0094934_kiosk_app_update_service_browsertest.cc new file mode 100644 index 0000000000000000000000000000000000000000..f37386dbcdb7f80a47b8c6a9eb8da243d612e013 --- /dev/null +++ b/pool/shard007/C++/0094934_kiosk_app_update_service_browsertest.cc @@ -0,0 +1,118 @@ +// Copyright 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 <string> + +#include "base/basictypes.h" +#include "base/command_line.h" +#include "base/compiler_specific.h" +#include "base/file_util.h" +#include "base/files/file_path.h" +#include "base/files/scoped_temp_dir.h" +#include "base/memory/scoped_ptr.h" +#include "base/path_service.h" +#include "base/prefs/pref_service.h" +#include "base/strings/string_number_conversions.h" +#include "base/test/scoped_path_override.h" +#include "base/threading/sequenced_worker_pool.h" +#include "base/time/time.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/browser_process_platform_part.h" +#include "chrome/browser/chromeos/app_mode/kiosk_app_update_service.h" +#include "chrome/browser/chromeos/system/automatic_reboot_manager.h" +#include "chrome/browser/extensions/extension_test_message_listener.h" +#include "chrome/browser/extensions/platform_app_browsertest_util.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/common/chrome_switches.h" +#include "chrome/common/extensions/extension.h" +#include "chrome/common/pref_names.h" +#include "chromeos/chromeos_paths.h" +#include "chromeos/dbus/update_engine_client.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/test/test_utils.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace chromeos { + +class KioskAppUpdateServiceTest : public extensions::PlatformAppBrowserTest { + public: + KioskAppUpdateServiceTest() : app_(NULL), update_service_(NULL) {} + virtual ~KioskAppUpdateServiceTest() {} + + // extensions::PlatformAppBrowserTest overrides: + virtual void SetUpOnMainThread() OVERRIDE { + extensions::PlatformAppBrowserTest::SetUpOnMainThread(); + + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + const base::FilePath& temp_dir = temp_dir_.path(); + + const base::TimeDelta uptime = base::TimeDelta::FromHours(1); + const std::string uptime_seconds = + base::DoubleToString(uptime.InSecondsF()); + const base::FilePath uptime_file = temp_dir.Append("uptime"); + ASSERT_EQ(static_cast<int>(uptime_seconds.size()), + file_util::WriteFile( + uptime_file, uptime_seconds.c_str(), uptime_seconds.size())); + uptime_file_override_.reset( + new base::ScopedPathOverride(chromeos::FILE_UPTIME, uptime_file)); + + app_ = LoadExtension( + test_data_dir_.AppendASCII("api_test/runtime/on_restart_required")); + + // Fake app mode command line. + CommandLine* command = CommandLine::ForCurrentProcess(); + command->AppendSwitch(switches::kForceAppMode); + command->AppendSwitchASCII(switches::kAppId, app_->id()); + + update_service_ = KioskAppUpdateServiceFactory::GetForProfile(profile()); + update_service_->set_app_id(app_->id()); + + content::BrowserThread::GetBlockingPool()->FlushForTesting(); + content::RunAllPendingInMessageLoop(); + } + + void FireAppUpdateAvailable() { + update_service_->OnAppUpdateAvailable(app_->id()); + } + + void FireUpdatedNeedReboot() { + UpdateEngineClient::Status status; + status.status = UpdateEngineClient::UPDATE_STATUS_UPDATED_NEED_REBOOT; + g_browser_process->platform_part()->automatic_reboot_manager()-> + UpdateStatusChanged(status); + } + + private: + base::ScopedTempDir temp_dir_; + scoped_ptr<base::ScopedPathOverride> uptime_file_override_; + const extensions::Extension* app_; // Not owned. + KioskAppUpdateService* update_service_; // Not owned. + + DISALLOW_COPY_AND_ASSIGN(KioskAppUpdateServiceTest); +}; + +IN_PROC_BROWSER_TEST_F(KioskAppUpdateServiceTest, AppUpdate) { + FireAppUpdateAvailable(); + + ExtensionTestMessageListener listener("app_update", false); + listener.WaitUntilSatisfied(); +} + +IN_PROC_BROWSER_TEST_F(KioskAppUpdateServiceTest, OsUpdate) { + g_browser_process->local_state()->SetBoolean(prefs::kRebootAfterUpdate, true); + FireUpdatedNeedReboot(); + + ExtensionTestMessageListener listener("os_update", false); + listener.WaitUntilSatisfied(); +} + +IN_PROC_BROWSER_TEST_F(KioskAppUpdateServiceTest, Periodic) { + g_browser_process->local_state()->SetInteger( + prefs::kUptimeLimit, base::TimeDelta::FromMinutes(30).InSeconds()); + + ExtensionTestMessageListener listener("periodic", false); + listener.WaitUntilSatisfied(); +} + +} // namespace chromeos diff --git a/pool/shard007/C++/0094938_daysimulator_test.cpp b/pool/shard007/C++/0094938_daysimulator_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6770fb3e8b2ee4cdd2315c0916806fbb41e31a15 --- /dev/null +++ b/pool/shard007/C++/0094938_daysimulator_test.cpp @@ -0,0 +1,94 @@ +#include "daysimulator.h" + +#include <gtest/gtest.h> +#include <QDebug> +#include <QSignalSpy> +#include <memory> + + +class DaySimulatorTest : public testing::Test { + //public: +protected: + virtual void SetUp() { + day_ = std::make_shared<DaySimulator>(); + qRegisterMetaType<DaySimulator::Daytime>("Daytime"); + } + + virtual void TearDown() { + day_.reset(); + } + std::shared_ptr<DaySimulator> day_; + +}; + +TEST_F(DaySimulatorTest, can_get_and_set_daytime) { + QSignalSpy spy(day_.get(), SIGNAL(daytimeChanged(Daytime))); + day_->setDaytime(DaySimulator::NIGHT); + EXPECT_EQ(spy.count(),1); + EXPECT_EQ(day_->getDaytime(),DaySimulator::NIGHT); +} + +TEST_F(DaySimulatorTest, valid_day_and_night_periods) { + //Test default values of 60s day, 5 random + for(int i=0;i<24;i++) + EXPECT_GE(day_->getEventStart(i),24); + for(int i=35;i<60;i++) + EXPECT_EQ(day_->getEventEnd(i),60); +} + +TEST_F(DaySimulatorTest, uneven_day_with_borderline_big_random) { + //Test corner case, 11 will always be night + day_->setCycle(11); + day_->setRandomTime(5); + day_->setTiming(0.5); + //Test first 100 days to make sure the algorithm works right + for(int i=0;i<100;i++) + EXPECT_LE(day_->getEventStart(i*11),10+11*i); +} + +//test random truncated when it may lap under cycle start time +TEST_F(DaySimulatorTest, random_truncated_to_be_in_cycle_time) { + day_->setCycle(3); + day_->setRandomTime(50); + //Test first 100 days to make sure the algorithm works right + for(int i=0;i<100;i++){ + EXPECT_LE(day_->getEventStart(i*3),2+3*i); + EXPECT_GE(day_->getEventStart(i*3),3*i); + EXPECT_LE(day_->getEventEnd(i*3),(2+3*i)+1); + } +} + + +TEST_F(DaySimulatorTest, day_only_has_one_daytime_boundary) { + //Make sure the day/night time doesn't switch back and forth in between one single day + //aka. there's a clear boundary between day and night + for(int i=0; i<50; i++) + EXPECT_EQ(day_->getEventEnd(i*60), 60+i*60); +} + +//as we cannot test the timeout signal directly, check if rain changed +//when it was set up to should have changed on timer signal +TEST_F(DaySimulatorTest, can_get_and_set_timer_and_it_will_trigger) { + QSignalSpy spy(day_.get(), SIGNAL(daytimeChanged(Daytime))); + std::shared_ptr<QTimer> timer = std::make_shared<QTimer>(); + timer->stop(); + timer->setInterval(1); + timer->setSingleShot(true); + day_->setTimer(timer); + day_->setRandomTime(0); + day_->setTiming(0); + timer->start(); + usleep(1000); + QCoreApplication::processEvents(); + EXPECT_EQ(spy.count(),1); + EXPECT_EQ(day_->getDaytime(),DaySimulator::NIGHT); + //check for switch back to day + spy.clear(); + day_->setTiming(1); + timer->start(); + usleep(1000); + QCoreApplication::processEvents(); + EXPECT_EQ(spy.count(),1); + EXPECT_EQ(day_->getDaytime(),DaySimulator::DAY); +} + diff --git a/pool/shard007/C++/0094940_Source.cpp b/pool/shard007/C++/0094940_Source.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3d712e65c539e48afa0e98221d917ce2ebc1fbac --- /dev/null +++ b/pool/shard007/C++/0094940_Source.cpp @@ -0,0 +1,204 @@ +/* + * Copyright 2012, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "bcc/Source.h" + +#include <new> + +#include <llvm/Bitcode/ReaderWriter.h> +#include <llvm/LLVMContext.h> +#include <llvm/Linker.h> +#include <llvm/Module.h> +#include <llvm/Support/MemoryBuffer.h> +#include <llvm/Support/system_error.h> + +#include "bcc/BCCContext.h" +#include "bcc/Support/Log.h" + +#include "BCCContextImpl.h" + +namespace { + +// Helper function to load the bitcode. This uses "bitcode lazy load" feature to +// reduce the startup time. On success, return the LLVM module object created +// and take the ownership of input memory buffer (i.e., pInput). On error, +// return NULL and will NOT take the ownership of pInput. +static inline llvm::Module *helper_load_bitcode(llvm::LLVMContext &pContext, + llvm::MemoryBuffer *pInput) { + std::string error; + llvm::Module *module = llvm::getLazyBitcodeModule(pInput, pContext, &error); + + if (module == NULL) { + ALOGE("Unable to parse the given bitcode file `%s'! (%s)", + pInput->getBufferIdentifier(), error.c_str()); + } + + return module; +} + +} // end anonymous namespace + +namespace bcc { + +Source *Source::CreateFromBuffer(BCCContext &pContext, + const char *pName, + const char *pBitcode, + size_t pBitcodeSize) { + llvm::StringRef input_data(pBitcode, pBitcodeSize); + llvm::MemoryBuffer *input_memory = + llvm::MemoryBuffer::getMemBuffer(input_data, "", false); + + if (input_memory == NULL) { + ALOGE("Unable to load bitcode `%s' from buffer!", pName); + return NULL; + } + + llvm::Module *module = helper_load_bitcode(pContext.mImpl->mLLVMContext, + input_memory); + if (module == NULL) { + delete input_memory; + return NULL; + } + + Source *result = CreateFromModule(pContext, *module, /* pNoDelete */false); + if (result == NULL) { + delete module; + } + + return result; +} + +Source *Source::CreateFromFile(BCCContext &pContext, const std::string &pPath) { + llvm::OwningPtr<llvm::MemoryBuffer> input_data; + + llvm::error_code ec = llvm::MemoryBuffer::getFile(pPath, input_data); + if (ec != llvm::error_code::success()) { + ALOGE("Failed to load bitcode from path %s! (%s)", pPath.c_str(), + ec.message().c_str()); + return NULL; + } + + llvm::MemoryBuffer *input_memory = input_data.take(); + llvm::Module *module = helper_load_bitcode(pContext.mImpl->mLLVMContext, + input_memory); + if (module == NULL) { + delete input_memory; + return NULL; + } + + Source *result = CreateFromModule(pContext, *module, /* pNoDelete */false); + if (result == NULL) { + delete module; + } + + return result; +} + +Source *Source::CreateFromFd(BCCContext &pContext, int pFd) { + llvm::OwningPtr<llvm::MemoryBuffer> input_data; + + llvm::error_code ec = + llvm::MemoryBuffer::getOpenFile(pFd, /* Filename */"", input_data); + + if (ec != llvm::error_code::success()) { + ALOGE("Failed to load bitcode from file descriptor %d! (%s)", + pFd, ec.message().c_str()); + return NULL; + } + + llvm::MemoryBuffer *input_memory = input_data.take(); + llvm::Module *module = helper_load_bitcode(pContext.mImpl->mLLVMContext, + input_memory); + if (module == NULL) { + delete input_memory; + return NULL; + } + + Source *result = CreateFromModule(pContext, *module, /* pNoDelete */false); + if (result == NULL) { + delete module; + } + + return result; +} + +Source *Source::CreateFromModule(BCCContext &pContext, llvm::Module &pModule, + bool pNoDelete) { + Source *result = new (std::nothrow) Source(pContext, pModule, pNoDelete); + if (result == NULL) { + ALOGE("Out of memory during Source object allocation for `%s'!", + pModule.getModuleIdentifier().c_str()); + } + return result; +} + +Source::Source(BCCContext &pContext, llvm::Module &pModule, bool pNoDelete) + : mContext(pContext), mModule(&pModule), mNoDelete(pNoDelete) { + pContext.addSource(*this); +} + +Source::~Source() { + mContext.removeSource(*this); + if (!mNoDelete) + delete mModule; +} + +bool Source::merge(Source &pSource, bool pPreserveSource) { + std::string error; + llvm::Linker::LinkerMode mode = + ((pPreserveSource) ? llvm::Linker::PreserveSource : + llvm::Linker::DestroySource); + + if (llvm::Linker::LinkModules(mModule, &pSource.getModule(), + mode, &error) != 0) { + ALOGE("Failed to link source `%s' with `%s' (%s)!", + getIdentifier().c_str(), + pSource.getIdentifier().c_str(), + error.c_str()); + return false; + } + + if (!pPreserveSource) { + pSource.mNoDelete = true; + delete &pSource; + } + + return true; +} + +Source *Source::CreateEmpty(BCCContext &pContext, const std::string &pName) { + // Create an empty module + llvm::Module *module = + new (std::nothrow) llvm::Module(pName, pContext.mImpl->mLLVMContext); + + if (module == NULL) { + ALOGE("Out of memory when creating empty LLVM module `%s'!", pName.c_str()); + return NULL; + } + + Source *result = CreateFromModule(pContext, *module, /* pNoDelete */false); + if (result == NULL) { + delete module; + } + + return result; +} + +const std::string &Source::getIdentifier() const { + return mModule->getModuleIdentifier(); +} + +} // namespace bcc diff --git a/pool/shard007/C++/0094942_AVRManager.cpp b/pool/shard007/C++/0094942_AVRManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..164c8b6a7036b3a85eccd547d80e480b10c47d68 --- /dev/null +++ b/pool/shard007/C++/0094942_AVRManager.cpp @@ -0,0 +1,105 @@ +/****************************************************************************** + ** Copyright (c) 2006-2017, Calaos. All Rights Reserved. + ** + ** This file is part of Calaos. + ** + ** Calaos is free software; you can redistribute it and/or modify + ** it under the terms of the GNU General Public License as published by + ** the Free Software Foundation; either version 3 of the License, or + ** (at your option) any later version. + ** + ** Calaos is distributed in the hope that it will be useful, + ** but WITHOUT ANY WARRANTY; without even the implied warranty of + ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + ** GNU General Public License for more details. + ** + ** You should have received a copy of the GNU General Public License + ** along with Foobar; if not, write to the Free Software + ** Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + ** + ******************************************************************************/ +#include "AVRManager.h" +#include "AVRPioneer.h" +#include "AVRDenon.h" +#include "AVROnkyo.h" +#include "AVRMarantz.h" +#include "AVRYamaha.h" + +using namespace Calaos; + +AVRManager::AVRManager() +{ +} + +AVRManager::~AVRManager() +{ + for (unsigned int i = 0;i < avrs.size();i++) + delete avrs[i]; + + avrs.clear(); +} + +AVRManager &AVRManager::Instance() +{ + static AVRManager inst; + + return inst; +} + +AVReceiver *AVRManager::Create(Params &p) +{ + AVReceiver *receiver = getReceiver(p["host"]); + if (!receiver) + { + if (p["model"] == "pioneer") + receiver = new AVRPioneer(p); + else if (p["model"] == "denon") + receiver = new AVRDenon(p); + else if (p["model"] == "onkyo") + receiver = new AVROnkyo(p); + else if (p["model"] == "marantz") + receiver = new AVRMarantz(p); + else if (p["model"] == "yamaha") + receiver = new AVRYamaha(p); + else + { + cInfoDom("output") << "AVRManager(): Unknown A/V Receiver model " << p["model"]; + return NULL; + } + avrs.push_back(receiver); + } + + receiver->ref_count++; + + return receiver; +} + +void AVRManager::Delete(AVReceiver *obj) +{ + bool found = false; + for (unsigned int i = 0;i < avrs.size() && !found;i++) + { + if (avrs[i] == obj) + { + obj->ref_count--; + found = true; + } + } + + if (obj->ref_count <= 0) + { + avrs.erase(std::remove(avrs.begin(), avrs.end(), obj), avrs.end()); + delete obj; + } +} + +AVReceiver *AVRManager::getReceiver(string host) +{ + for (unsigned int i = 0;i < avrs.size();i++) + { + if (avrs[i]->host == host) + return avrs[i]; + } + + return NULL; +} diff --git a/pool/shard007/C++/0094943_viewmanager.cpp b/pool/shard007/C++/0094943_viewmanager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1ae7c0d772c0736b97ca1e027a12824ec463c09 --- /dev/null +++ b/pool/shard007/C++/0094943_viewmanager.cpp @@ -0,0 +1,56 @@ +/********* +* +* In the name of the Father, and of the Son, and of the Holy Spirit. +* +* This file is part of BibleTime's source code, http://www.bibletime.info/. +* +* Copyright 1999-2016 by the BibleTime developers. +* The BibleTime source code is licensed under the GNU General Public License +* version 2.0. +* +**********/ + +#include "viewmanager.h" + +#include "qtquick2applicationviewer.h" + +#include "btstyle.h" +#include "util/directory.h" +#include <cmath> +#include <QGuiApplication> +#include <QJsonValue> +#include <QQuickItem> +#include <QQmlProperty> +#include <QQmlContext> +#include <QUrl> +#include <QDebug> + +namespace btm { + +ViewManager::ViewManager() + : viewer_(new QtQuick2ApplicationViewer()) { + BtStyle style; + style.setStyle(BtStyle::darkTheme); + initialize_string_list_chooser_model(); + initialize_main_qml(); +} + +void ViewManager::initialize_string_list_chooser_model() { + QQmlContext* ctx = viewer_->rootContext(); + QStringList list = QStringList(); + ctx->setContextProperty("gridChooserModel",list); +} + +void ViewManager::initialize_main_qml() { + viewer_->setMainQmlFile(util::directory::getQmlDir().filePath("main.qml")); +} + +void ViewManager::show() { + viewer_->showExpanded(); +} + +QtQuick2ApplicationViewer* ViewManager::getViewer() const { + return viewer_; +} + +} // end namespace diff --git a/pool/shard007/C++/0094947_visual-simulator-impl.cc b/pool/shard007/C++/0094947_visual-simulator-impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..e3fe07736087394efbea65be8a1eded92508aa18 --- /dev/null +++ b/pool/shard007/C++/0094947_visual-simulator-impl.cc @@ -0,0 +1,217 @@ +/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2010 Gustavo Carneiro + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation; + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * Author: Gustavo Carneiro <gjcarneiro@gmail.com> <gjc@inescporto.pt> + */ +#include <Python.h> +#include "visual-simulator-impl.h" +#include "ns3/default-simulator-impl.h" +#include "ns3/log.h" + +NS_LOG_COMPONENT_DEFINE ("VisualSimulatorImpl"); + +namespace ns3 { + + + +NS_OBJECT_ENSURE_REGISTERED (VisualSimulatorImpl); + +namespace +{ +ObjectFactory +GetDefaultSimulatorImplFactory () +{ + ObjectFactory factory; + factory.SetTypeId (DefaultSimulatorImpl::GetTypeId ()); + return factory; +} +} + + +TypeId +VisualSimulatorImpl::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::VisualSimulatorImpl") + .SetParent<SimulatorImpl> () + .AddConstructor<VisualSimulatorImpl> () + .AddAttribute ("SimulatorImplFactory", + "Factory for the underlying simulator implementation used by the visualizer.", + ObjectFactoryValue (GetDefaultSimulatorImplFactory ()), + MakeObjectFactoryAccessor (&VisualSimulatorImpl::m_simulatorImplFactory), + MakeObjectFactoryChecker ()) + ; + return tid; +} + + +VisualSimulatorImpl::VisualSimulatorImpl () +{ +} + +VisualSimulatorImpl::~VisualSimulatorImpl () +{ +} + +void +VisualSimulatorImpl::DoDispose (void) +{ + if (m_simulator) + { + m_simulator->Dispose (); + m_simulator = NULL; + } + SimulatorImpl::DoDispose (); +} + +void +VisualSimulatorImpl::NotifyConstructionCompleted () +{ + m_simulator = m_simulatorImplFactory.Create<SimulatorImpl> (); +} + + +void +VisualSimulatorImpl::Destroy () +{ + m_simulator->Destroy (); +} + +void +VisualSimulatorImpl::SetScheduler (ObjectFactory schedulerFactory) +{ + m_simulator->SetScheduler (schedulerFactory); +} + +// System ID for non-distributed simulation is always zero +uint32_t +VisualSimulatorImpl::GetSystemId (void) const +{ + return m_simulator->GetSystemId (); +} + +bool +VisualSimulatorImpl::IsFinished (void) const +{ + return m_simulator->IsFinished (); +} + +void +VisualSimulatorImpl::Run (void) +{ + if (!Py_IsInitialized ()) + { + const char *argv[] = { "python", NULL}; + Py_Initialize (); + PySys_SetArgv (1, (char**) argv); + } + PyRun_SimpleString ( + "import visualizer\n" + "visualizer.start();\n" + ); +} + +void +VisualSimulatorImpl::Stop (void) +{ + m_simulator->Stop (); +} + +void +VisualSimulatorImpl::Stop (Time const &time) +{ + m_simulator->Stop (time); +} + +// +// Schedule an event for a _relative_ time in the future. +// +EventId +VisualSimulatorImpl::Schedule (Time const &time, EventImpl *event) +{ + return m_simulator->Schedule (time, event); +} + +void +VisualSimulatorImpl::ScheduleWithContext (uint32_t context, Time const &time, EventImpl *event) +{ + m_simulator->ScheduleWithContext (context, time, event); +} + +EventId +VisualSimulatorImpl::ScheduleNow (EventImpl *event) +{ + return m_simulator->ScheduleNow (event); +} + +EventId +VisualSimulatorImpl::ScheduleDestroy (EventImpl *event) +{ + return m_simulator->ScheduleDestroy (event); +} + +Time +VisualSimulatorImpl::Now (void) const +{ + return m_simulator->Now (); +} + +Time +VisualSimulatorImpl::GetDelayLeft (const EventId &id) const +{ + return m_simulator->GetDelayLeft (id); +} + +void +VisualSimulatorImpl::Remove (const EventId &id) +{ + m_simulator->Remove (id); +} + +void +VisualSimulatorImpl::Cancel (const EventId &id) +{ + m_simulator->Cancel (id); +} + +bool +VisualSimulatorImpl::IsExpired (const EventId &ev) const +{ + return m_simulator->IsExpired (ev); +} + +Time +VisualSimulatorImpl::GetMaximumSimulationTime (void) const +{ + return m_simulator->GetMaximumSimulationTime (); +} + +uint32_t +VisualSimulatorImpl::GetContext (void) const +{ + return m_simulator->GetContext (); +} + +void +VisualSimulatorImpl::RunRealSimulator (void) +{ + m_simulator->Run (); +} + + +} // namespace ns3 + + diff --git a/pool/shard007/C++/0094948_GridLayoutModule.cpp b/pool/shard007/C++/0094948_GridLayoutModule.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a46410ae606ca59e6a6c88baf6126a6e5954d283 --- /dev/null +++ b/pool/shard007/C++/0094948_GridLayoutModule.cpp @@ -0,0 +1,189 @@ +/* + * $Revision: 2549 $ + * + * last checkin: + * $Author: gutwenger $ + * $Date: 2012-07-04 23:09:19 +0200 (Wed, 04 Jul 2012) $ + ***************************************************************/ + +/** \file + * \brief Implements grid mapping mechanism of class GridLayoutModule + * + * \author Carsten Gutwenger + * + * \par License: + * This file is part of the Open Graph Drawing Framework (OGDF). + * + * \par + * Copyright (C)<br> + * See README.txt in the root directory of the OGDF installation for details. + * + * \par + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * Version 2 or 3 as published by the Free Software Foundation; + * see the file LICENSE.txt included in the packaging of this file + * for details. + * + * \par + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * \par + * You should have received a copy of the GNU General Public + * License along with this program; if not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * + * \see http://www.gnu.org/copyleft/gpl.html + ***************************************************************/ + + +#include <ogdf/module/GridLayoutModule.h> + + +namespace ogdf { + + +void GridLayoutModule::call(GraphAttributes &AG) +{ + const Graph &G = AG.constGraph(); + + // compute grid layout + GridLayout gridLayout(G); + doCall(G,gridLayout,m_gridBoundingBox); + + // transform grid layout to real layout + mapGridLayout(G,gridLayout,AG); +} + + +void GridLayoutModule::callGrid(const Graph &G, GridLayout &gridLayout) +{ + gridLayout.init(G); + doCall(G,gridLayout,m_gridBoundingBox); +} + + +void GridLayoutModule::mapGridLayout(const Graph &G, + GridLayout &gridLayout, + GraphAttributes &AG) +{ + double maxWidth = 0; // maximum width of columns and rows; + double yMax = 0; + + node v; + forall_nodes(v,G) { + if (AG.width (v) > maxWidth) maxWidth = AG.width (v); + if (AG.height(v) > maxWidth) maxWidth = AG.height(v); + if (gridLayout.y(v) > yMax) yMax = gridLayout.y(v); + } + + maxWidth += m_separation; + + // set position of nodes + forall_nodes(v,G) { + AG.x(v) = gridLayout.x(v) * maxWidth; + AG.y(v) = (yMax - gridLayout.y(v)) * maxWidth; + } + + // transform bend points of edges + edge e; + forall_edges(e,G) { + DPolyline &dpl = AG.bends(e); + dpl.clear(); + + IPolyline ipl = gridLayout.polyline(e); + ListConstIterator<IPoint> it; + for(it = ipl.begin(); it.valid(); ++it) { + const IPoint &ip = *it; + dpl.pushBack(DPoint(ip.m_x*maxWidth, (yMax-ip.m_y)*maxWidth)); + } + } +} + + +void PlanarGridLayoutModule::callFixEmbed(GraphAttributes &AG, adjEntry adjExternal) +{ + const Graph &G = AG.constGraph(); + + // compute grid layout + GridLayout gridLayout(G); + doCall(G,adjExternal,gridLayout,m_gridBoundingBox,true); + + // transform grid layout to real layout + mapGridLayout(G,gridLayout,AG); +} + + +void PlanarGridLayoutModule::callGridFixEmbed( + const Graph &G, + GridLayout &gridLayout, + adjEntry adjExternal) +{ + gridLayout.init(G); + doCall(G,adjExternal,gridLayout,m_gridBoundingBox,true); +} + + +void GridLayoutPlanRepModule::callGrid(PlanRep &PG, GridLayout &gridLayout) +{ + gridLayout.init(PG); + doCall(PG,0,gridLayout,m_gridBoundingBox,false); +} + +void GridLayoutPlanRepModule::callGridFixEmbed( + PlanRep &PG, + GridLayout &gridLayout, + adjEntry adjExternal) +{ + gridLayout.init(PG); + doCall(PG,adjExternal,gridLayout,m_gridBoundingBox,true); +} + +void GridLayoutPlanRepModule::doCall( + const Graph &G, + adjEntry adjExternal, + GridLayout &gridLayout, + IPoint &boundingBox, + bool fixEmbedding) +{ + // create temporary graph copy and grid layout + PlanRep PG(G); + PG.initCC(0); // currently only for a single component! + GridLayout glPG(PG); + + // determine adjacency entry on external face of PG (if required) + if(adjExternal != 0) { + edge eG = adjExternal->theEdge(); + edge ePG = PG.copy(eG); + adjExternal = (adjExternal == eG->adjSource()) ? ePG->adjSource() : ePG->adjTarget(); + } + + // call algorithm for copy + doCall(PG,adjExternal,glPG,boundingBox,fixEmbedding); + + // extract layout for original graph + node v; + forall_nodes(v,G) { + node vPG = PG.copy(v); + gridLayout.x(v) = glPG.x(vPG); + gridLayout.y(v) = glPG.y(vPG); + } + + edge e; + forall_edges(e,G) { + IPolyline &ipl = gridLayout.bends(e); + ipl.clear(); + + ListConstIterator<edge> it; + for(it = PG.chain(e).begin(); it.valid(); ++it) + ipl.conc(glPG.bends(*it)); + } +} + + +} // end namespace ogdf + diff --git a/pool/shard007/C++/0094952_GetStageResult.cpp b/pool/shard007/C++/0094952_GetStageResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8ee5633aba2bd543c89e81a1af785f98ff79d8fd --- /dev/null +++ b/pool/shard007/C++/0094952_GetStageResult.cpp @@ -0,0 +1,163 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include <aws/apigateway/model/GetStageResult.h> +#include <aws/core/utils/json/JsonSerializer.h> +#include <aws/core/AmazonWebServiceResult.h> +#include <aws/core/utils/StringUtils.h> +#include <aws/core/utils/UnreferencedParam.h> + +#include <utility> + +using namespace Aws::APIGateway::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +GetStageResult::GetStageResult() : + m_cacheClusterEnabled(false), + m_cacheClusterSize(CacheClusterSize::NOT_SET), + m_cacheClusterStatus(CacheClusterStatus::NOT_SET), + m_tracingEnabled(false) +{ +} + +GetStageResult::GetStageResult(const Aws::AmazonWebServiceResult<JsonValue>& result) : + m_cacheClusterEnabled(false), + m_cacheClusterSize(CacheClusterSize::NOT_SET), + m_cacheClusterStatus(CacheClusterStatus::NOT_SET), + m_tracingEnabled(false) +{ + *this = result; +} + +GetStageResult& GetStageResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) +{ + JsonView jsonValue = result.GetPayload().View(); + if(jsonValue.ValueExists("deploymentId")) + { + m_deploymentId = jsonValue.GetString("deploymentId"); + + } + + if(jsonValue.ValueExists("clientCertificateId")) + { + m_clientCertificateId = jsonValue.GetString("clientCertificateId"); + + } + + if(jsonValue.ValueExists("stageName")) + { + m_stageName = jsonValue.GetString("stageName"); + + } + + if(jsonValue.ValueExists("description")) + { + m_description = jsonValue.GetString("description"); + + } + + if(jsonValue.ValueExists("cacheClusterEnabled")) + { + m_cacheClusterEnabled = jsonValue.GetBool("cacheClusterEnabled"); + + } + + if(jsonValue.ValueExists("cacheClusterSize")) + { + m_cacheClusterSize = CacheClusterSizeMapper::GetCacheClusterSizeForName(jsonValue.GetString("cacheClusterSize")); + + } + + if(jsonValue.ValueExists("cacheClusterStatus")) + { + m_cacheClusterStatus = CacheClusterStatusMapper::GetCacheClusterStatusForName(jsonValue.GetString("cacheClusterStatus")); + + } + + if(jsonValue.ValueExists("methodSettings")) + { + Aws::Map<Aws::String, JsonView> methodSettingsJsonMap = jsonValue.GetObject("methodSettings").GetAllObjects(); + for(auto& methodSettingsItem : methodSettingsJsonMap) + { + m_methodSettings[methodSettingsItem.first] = methodSettingsItem.second.AsObject(); + } + } + + if(jsonValue.ValueExists("variables")) + { + Aws::Map<Aws::String, JsonView> variablesJsonMap = jsonValue.GetObject("variables").GetAllObjects(); + for(auto& variablesItem : variablesJsonMap) + { + m_variables[variablesItem.first] = variablesItem.second.AsString(); + } + } + + if(jsonValue.ValueExists("documentationVersion")) + { + m_documentationVersion = jsonValue.GetString("documentationVersion"); + + } + + if(jsonValue.ValueExists("accessLogSettings")) + { + m_accessLogSettings = jsonValue.GetObject("accessLogSettings"); + + } + + if(jsonValue.ValueExists("canarySettings")) + { + m_canarySettings = jsonValue.GetObject("canarySettings"); + + } + + if(jsonValue.ValueExists("tracingEnabled")) + { + m_tracingEnabled = jsonValue.GetBool("tracingEnabled"); + + } + + if(jsonValue.ValueExists("webAclArn")) + { + m_webAclArn = jsonValue.GetString("webAclArn"); + + } + + if(jsonValue.ValueExists("tags")) + { + Aws::Map<Aws::String, JsonView> tagsJsonMap = jsonValue.GetObject("tags").GetAllObjects(); + for(auto& tagsItem : tagsJsonMap) + { + m_tags[tagsItem.first] = tagsItem.second.AsString(); + } + } + + if(jsonValue.ValueExists("createdDate")) + { + m_createdDate = jsonValue.GetDouble("createdDate"); + + } + + if(jsonValue.ValueExists("lastUpdatedDate")) + { + m_lastUpdatedDate = jsonValue.GetDouble("lastUpdatedDate"); + + } + + + + return *this; +} diff --git a/pool/shard007/C++/0094957_webrtc_logging_message_filter.cc b/pool/shard007/C++/0094957_webrtc_logging_message_filter.cc new file mode 100644 index 0000000000000000000000000000000000000000..148e24571cf75bbafd242c353e8338835ebe8e8c --- /dev/null +++ b/pool/shard007/C++/0094957_webrtc_logging_message_filter.cc @@ -0,0 +1,93 @@ +// Copyright 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 "chrome/renderer/media/webrtc_logging_message_filter.h" + +#include "base/logging.h" +#include "base/message_loop/message_loop_proxy.h" +#include "chrome/common/media/webrtc_logging_messages.h" +#include "chrome/renderer/media/chrome_webrtc_log_message_delegate.h" +#include "ipc/ipc_logging.h" + +WebRtcLoggingMessageFilter::WebRtcLoggingMessageFilter( + const scoped_refptr<base::MessageLoopProxy>& io_message_loop) + : io_message_loop_(io_message_loop), + log_message_delegate_(NULL), + channel_(NULL) { + // May be null in a browsertest using MockRenderThread. + if (io_message_loop_) { + io_message_loop_->PostTask( + FROM_HERE, base::Bind( + &WebRtcLoggingMessageFilter::CreateLoggingHandler, + base::Unretained(this))); + } +} + +WebRtcLoggingMessageFilter::~WebRtcLoggingMessageFilter() { +} + +bool WebRtcLoggingMessageFilter::OnMessageReceived( + const IPC::Message& message) { + DCHECK(io_message_loop_->BelongsToCurrentThread()); + bool handled = true; + IPC_BEGIN_MESSAGE_MAP(WebRtcLoggingMessageFilter, message) + IPC_MESSAGE_HANDLER(WebRtcLoggingMsg_StartLogging, OnStartLogging) + IPC_MESSAGE_HANDLER(WebRtcLoggingMsg_StopLogging, OnStopLogging) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + return handled; +} + +void WebRtcLoggingMessageFilter::OnFilterAdded(IPC::Channel* channel) { + DCHECK(!io_message_loop_ || io_message_loop_->BelongsToCurrentThread()); + channel_ = channel; +} + +void WebRtcLoggingMessageFilter::OnFilterRemoved() { + DCHECK(!io_message_loop_ || io_message_loop_->BelongsToCurrentThread()); + channel_ = NULL; + log_message_delegate_->OnFilterRemoved(); +} + +void WebRtcLoggingMessageFilter::OnChannelClosing() { + DCHECK(!io_message_loop_ || io_message_loop_->BelongsToCurrentThread()); + channel_ = NULL; + log_message_delegate_->OnFilterRemoved(); +} + +void WebRtcLoggingMessageFilter::AddLogMessage(const std::string& message) { + DCHECK(io_message_loop_->BelongsToCurrentThread()); + Send(new WebRtcLoggingMsg_AddLogMessage(message)); +} + +void WebRtcLoggingMessageFilter::LoggingStopped() { + DCHECK(io_message_loop_->BelongsToCurrentThread()); + Send(new WebRtcLoggingMsg_LoggingStopped()); +} + +void WebRtcLoggingMessageFilter::CreateLoggingHandler() { + DCHECK(!io_message_loop_ || io_message_loop_->BelongsToCurrentThread()); + log_message_delegate_ = + new ChromeWebRtcLogMessageDelegate(io_message_loop_, this); +} + +void WebRtcLoggingMessageFilter::OnStartLogging() { + DCHECK(!io_message_loop_ || io_message_loop_->BelongsToCurrentThread()); + log_message_delegate_->OnStartLogging(); +} + +void WebRtcLoggingMessageFilter::OnStopLogging() { + DCHECK(io_message_loop_->BelongsToCurrentThread()); + log_message_delegate_->OnStopLogging(); +} + +void WebRtcLoggingMessageFilter::Send(IPC::Message* message) { + DCHECK(!io_message_loop_ || io_message_loop_->BelongsToCurrentThread()); + if (!channel_) { + DLOG(ERROR) << "IPC channel not available."; + delete message; + } else { + channel_->Send(message); + } +} diff --git a/pool/shard007/C++/0094958_DelayQueue.cpp b/pool/shard007/C++/0094958_DelayQueue.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d247476e510ea656ddc23668f4b8ab98f7bee4aa --- /dev/null +++ b/pool/shard007/C++/0094958_DelayQueue.cpp @@ -0,0 +1,224 @@ +/********** +This library is free software; you can redistribute it and/or modify it under +the terms of the GNU Lesser General Public License as published by the +Free Software Foundation; either version 2.1 of the License, or (at your +option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) + +This library is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for +more details. + +You should have received a copy of the GNU Lesser General Public License +along with this library; if not, write to the Free Software Foundation, Inc., +59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +**********/ +// Copyright (c) 1996-2000, Live Networks, Inc. All rights reserved +// Help by Carlo Bonamico to get working for Windows +// Delay queue +// Implementation + +#include "DelayQueue.hh" +#include "GroupsockHelper.hh" + +static const int MILLION = 1000000; + +///// Timeval ///// + +int Timeval::operator>=(const Timeval& arg2) const { + return seconds() > arg2.seconds() + || (seconds() == arg2.seconds() + && useconds() >= arg2.useconds()); +} + +void Timeval::operator+=(const DelayInterval& arg2) { + secs() += arg2.seconds(); usecs() += arg2.useconds(); + if (usecs() >= MILLION) { + usecs() -= MILLION; + ++secs(); + } +} + +void Timeval::operator-=(const DelayInterval& arg2) { + secs() -= arg2.seconds(); usecs() -= arg2.useconds(); + if (usecs() < 0) { + usecs() += MILLION; + --secs(); + } + if (secs() < 0) + secs() = usecs() = 0; +} + +DelayInterval operator-(const Timeval& arg1, const Timeval& arg2) { + time_base_seconds secs = arg1.seconds() - arg2.seconds(); + time_base_seconds usecs = arg1.useconds() - arg2.useconds(); + + if (usecs < 0) { + usecs += MILLION; + --secs; + } + if (secs < 0) + return DELAY_ZERO; + else + return DelayInterval(secs, usecs); +} + + +///// DelayInterval ///// + +DelayInterval operator*(short arg1, const DelayInterval& arg2) { + time_base_seconds result_seconds = arg1*arg2.seconds(); + time_base_seconds result_useconds = arg1*arg2.useconds(); + + time_base_seconds carry = result_useconds/MILLION; + result_useconds -= carry*MILLION; + result_seconds += carry; + + return DelayInterval(result_seconds, result_useconds); +} + +#ifndef INT_MAX +#define INT_MAX 0x7FFFFFFF +#endif +const DelayInterval DELAY_ZERO(0, 0); +const DelayInterval DELAY_SECOND(1, 0); +const DelayInterval ETERNITY(INT_MAX, MILLION-1); +// used internally to make the implementation work + + +///// DelayQueueEntry ///// + +long DelayQueueEntry::tokenCounter = 0; + +DelayQueueEntry::DelayQueueEntry(DelayInterval delay) + : fDeltaTimeRemaining(delay) { + fNext = fPrev = this; + fToken = ++tokenCounter; +} + +DelayQueueEntry::~DelayQueueEntry() { +} + +void DelayQueueEntry::handleTimeout() { + delete this; +} + + +///// DelayQueue ///// + +DelayQueue::DelayQueue() + : DelayQueueEntry(ETERNITY) { + fLastSyncTime = TimeNow(); +} + +DelayQueue::~DelayQueue() { + while (fNext != this) removeEntry(fNext); +} + +void DelayQueue::addEntry(DelayQueueEntry* newEntry) { + synchronize(); + + DelayQueueEntry* cur = head(); + while (newEntry->fDeltaTimeRemaining >= cur->fDeltaTimeRemaining) { + newEntry->fDeltaTimeRemaining -= cur->fDeltaTimeRemaining; + cur = cur->fNext; + } + + cur->fDeltaTimeRemaining -= newEntry->fDeltaTimeRemaining; + + // Add "newEntry" to the queue, just before "cur": + newEntry->fNext = cur; + newEntry->fPrev = cur->fPrev; + cur->fPrev = newEntry->fPrev->fNext = newEntry; +} + +void DelayQueue::updateEntry(DelayQueueEntry* entry, DelayInterval newDelay) { + if (entry == NULL) return; + + removeEntry(entry); + entry->fDeltaTimeRemaining = newDelay; + addEntry(entry); +} + +void DelayQueue::updateEntry(long tokenToFind, DelayInterval newDelay) { + DelayQueueEntry* entry = findEntryByToken(tokenToFind); + updateEntry(entry, newDelay); +} + +void DelayQueue::removeEntry(DelayQueueEntry* entry) { + if (entry == NULL || entry->fNext == NULL) return; + + entry->fNext->fDeltaTimeRemaining += entry->fDeltaTimeRemaining; + entry->fPrev->fNext = entry->fNext; + entry->fNext->fPrev = entry->fPrev; + entry->fNext = entry->fPrev = NULL; + // in case we should try to remove it again +} + +DelayQueueEntry* DelayQueue::removeEntry(long tokenToFind) { + DelayQueueEntry* entry = findEntryByToken(tokenToFind); + removeEntry(entry); + return entry; +} + +DelayInterval const& DelayQueue::timeToNextAlarm() { + if (head()->fDeltaTimeRemaining == DELAY_ZERO) return DELAY_ZERO; // a common case + + synchronize(); + return head()->fDeltaTimeRemaining; +} + +void DelayQueue::handleAlarm() { + if (head()->fDeltaTimeRemaining != DELAY_ZERO) synchronize(); + + if (head()->fDeltaTimeRemaining == DELAY_ZERO) { + // This event is due to be handled: + DelayQueueEntry* toRemove = head(); + removeEntry(toRemove); // do this first, in case handler accesses queue + + toRemove->handleTimeout(); + } +} + +DelayQueueEntry* DelayQueue::findEntryByToken(long tokenToFind) { + DelayQueueEntry* cur = head(); + while (cur != this) { + if (cur->token() == tokenToFind) return cur; + cur = cur->fNext; + } + + return NULL; +} + +void DelayQueue::synchronize() { + // First, figure out how much time has elapsed since the last sync: + EventTime timeNow = TimeNow(); + DelayInterval timeSinceLastSync = timeNow - fLastSyncTime; + fLastSyncTime = timeNow; + + // Then, adjust the delay queue for any entries whose time is up: + DelayQueueEntry* curEntry = head(); + while (timeSinceLastSync >= curEntry->fDeltaTimeRemaining) { + timeSinceLastSync -= curEntry->fDeltaTimeRemaining; + curEntry->fDeltaTimeRemaining = DELAY_ZERO; + curEntry = curEntry->fNext; + } + curEntry->fDeltaTimeRemaining -= timeSinceLastSync; +} + + +///// EventTime ///// + +EventTime TimeNow() { + struct timeval tvNow; + + gettimeofday(&tvNow, NULL); + + return EventTime(tvNow.tv_sec, tvNow.tv_usec); +} + +DelayInterval TimeRemainingUntil(const EventTime& futureEvent) { + return futureEvent - TimeNow(); +} + +const EventTime THE_END_OF_TIME(INT_MAX); diff --git a/pool/shard007/C++/0094959_material.cpp b/pool/shard007/C++/0094959_material.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3af7b813a3fc87e95110724177b6a74d73979796 --- /dev/null +++ b/pool/shard007/C++/0094959_material.cpp @@ -0,0 +1,222 @@ +/* + SugaR, a UCI chess playing engine derived from Stockfish + Copyright (C) 2004-2008 Tord Romstad (Glaurung author) + Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad + Copyright (C) 2015-2017 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad + + SugaR is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + SugaR is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include <algorithm> // For std::min +#include <cassert> +#include <cstring> // For std::memset + +#include "material.h" +#include "thread.h" + +using namespace std; + +namespace { + + // Polynomial material imbalance parameters + + constexpr int QuadraticOurs[][PIECE_TYPE_NB] = { + // OUR PIECES + // pair pawn knight bishop rook queen + {1667 }, // Bishop pair + { 40, 0 }, // Pawn + { 32, 255, -3 }, // Knight OUR PIECES + { 0, 104, 4, 0 }, // Bishop + { -26, -2, 47, 105, -149 }, // Rook + {-189, 24, 117, 133, -134, -10 } // Queen + }; + + constexpr int QuadraticTheirs[][PIECE_TYPE_NB] = { + // THEIR PIECES + // pair pawn knight bishop rook queen + { 0 }, // Bishop pair + { 36, 0 }, // Pawn + { 9, 63, 0 }, // Knight OUR PIECES + { 59, 65, 42, 0 }, // Bishop + { 46, 39, 24, -24, 0 }, // Rook + { 97, 100, -42, 137, 268, 0 } // Queen + }; + + // Endgame evaluation and scaling functions are accessed directly and not through + // the function maps because they correspond to more than one material hash key. + Endgame<KXK> EvaluateKXK[] = { Endgame<KXK>(WHITE), Endgame<KXK>(BLACK) }; + + Endgame<KBPsK> ScaleKBPsK[] = { Endgame<KBPsK>(WHITE), Endgame<KBPsK>(BLACK) }; + Endgame<KQKRPs> ScaleKQKRPs[] = { Endgame<KQKRPs>(WHITE), Endgame<KQKRPs>(BLACK) }; + Endgame<KPsK> ScaleKPsK[] = { Endgame<KPsK>(WHITE), Endgame<KPsK>(BLACK) }; + Endgame<KPKP> ScaleKPKP[] = { Endgame<KPKP>(WHITE), Endgame<KPKP>(BLACK) }; + + // Helper used to detect a given material distribution + bool is_KXK(const Position& pos, Color us) { + return !more_than_one(pos.pieces(~us)) + && pos.non_pawn_material(us) >= RookValueMg; + } + + bool is_KBPsK(const Position& pos, Color us) { + return pos.non_pawn_material(us) == BishopValueMg + && pos.count<BISHOP>(us) == 1 + && pos.count<PAWN >(us) >= 1; + } + + bool is_KQKRPs(const Position& pos, Color us) { + return !pos.count<PAWN>(us) + && pos.non_pawn_material(us) == QueenValueMg + && pos.count<QUEEN>(us) == 1 + && pos.count<ROOK>(~us) == 1 + && pos.count<PAWN>(~us) >= 1; + } + + /// imbalance() calculates the imbalance by comparing the piece count of each + /// piece type for both colors. + template<Color Us> + int imbalance(const int pieceCount[][PIECE_TYPE_NB]) { + + constexpr Color Them = (Us == WHITE ? BLACK : WHITE); + + int bonus = 0; + + // Second-degree polynomial material imbalance, by Tord Romstad + for (int pt1 = NO_PIECE_TYPE; pt1 <= QUEEN; ++pt1) + { + if (!pieceCount[Us][pt1]) + continue; + + int v = 0; + + for (int pt2 = NO_PIECE_TYPE; pt2 <= pt1; ++pt2) + v += QuadraticOurs[pt1][pt2] * pieceCount[Us][pt2] + + QuadraticTheirs[pt1][pt2] * pieceCount[Them][pt2]; + + bonus += pieceCount[Us][pt1] * v; + } + + return bonus; + } + +} // namespace + +namespace Material { + +/// Material::probe() looks up the current position's material configuration in +/// the material hash table. It returns a pointer to the Entry if the position +/// is found. Otherwise a new Entry is computed and stored there, so we don't +/// have to recompute all when the same material configuration occurs again. + +Entry* probe(const Position& pos) { + + Key key = pos.material_key(); + Entry* e = pos.this_thread()->materialTable[key]; + + if (e->key == key) + return e; + + std::memset(e, 0, sizeof(Entry)); + e->key = key; + e->factor[WHITE] = e->factor[BLACK] = (uint8_t)SCALE_FACTOR_NORMAL; + + Value npm_w = pos.non_pawn_material(WHITE); + Value npm_b = pos.non_pawn_material(BLACK); + Value npm = std::max(EndgameLimit, std::min(npm_w + npm_b, MidgameLimit)); + + // Map total non-pawn material into [PHASE_ENDGAME, PHASE_MIDGAME] + e->gamePhase = Phase(((npm - EndgameLimit) * PHASE_MIDGAME) / (MidgameLimit - EndgameLimit)); + + // Let's look if we have a specialized evaluation function for this particular + // material configuration. Firstly we look for a fixed configuration one, then + // for a generic one if the previous search failed. + if ((e->evaluationFunction = pos.this_thread()->endgames.probe<Value>(key)) != nullptr) + return e; + + for (Color c = WHITE; c <= BLACK; ++c) + if (is_KXK(pos, c)) + { + e->evaluationFunction = &EvaluateKXK[c]; + return e; + } + + // OK, we didn't find any special evaluation function for the current material + // configuration. Is there a suitable specialized scaling function? + EndgameBase<ScaleFactor>* sf; + + if ((sf = pos.this_thread()->endgames.probe<ScaleFactor>(key)) != nullptr) + { + e->scalingFunction[sf->strongSide] = sf; // Only strong color assigned + return e; + } + + // We didn't find any specialized scaling function, so fall back on generic + // ones that refer to more than one material distribution. Note that in this + // case we don't return after setting the function. + for (Color c = WHITE; c <= BLACK; ++c) + { + if (is_KBPsK(pos, c)) + e->scalingFunction[c] = &ScaleKBPsK[c]; + + else if (is_KQKRPs(pos, c)) + e->scalingFunction[c] = &ScaleKQKRPs[c]; + } + + if (npm_w + npm_b == VALUE_ZERO && pos.pieces(PAWN)) // Only pawns on the board + { + if (!pos.count<PAWN>(BLACK)) + { + assert(pos.count<PAWN>(WHITE) >= 2); + + e->scalingFunction[WHITE] = &ScaleKPsK[WHITE]; + } + else if (!pos.count<PAWN>(WHITE)) + { + assert(pos.count<PAWN>(BLACK) >= 2); + + e->scalingFunction[BLACK] = &ScaleKPsK[BLACK]; + } + else if (pos.count<PAWN>(WHITE) == 1 && pos.count<PAWN>(BLACK) == 1) + { + // This is a special case because we set scaling functions + // for both colors instead of only one. + e->scalingFunction[WHITE] = &ScaleKPKP[WHITE]; + e->scalingFunction[BLACK] = &ScaleKPKP[BLACK]; + } + } + + // Zero or just one pawn makes it difficult to win, even with a small material + // advantage. This catches some trivial draws like KK, KBK and KNK and gives a + // drawish scale factor for cases such as KRKBP and KmmKm (except for KBBKN). + if (!pos.count<PAWN>(WHITE) && npm_w - npm_b <= BishopValueMg) + e->factor[WHITE] = uint8_t(npm_w < RookValueMg ? SCALE_FACTOR_DRAW : + npm_b <= BishopValueMg ? 4 : 14); + + if (!pos.count<PAWN>(BLACK) && npm_b - npm_w <= BishopValueMg) + e->factor[BLACK] = uint8_t(npm_b < RookValueMg ? SCALE_FACTOR_DRAW : + npm_w <= BishopValueMg ? 4 : 14); + + // Evaluate the material imbalance. We use PIECE_TYPE_NONE as a place holder + // for the bishop pair "extended piece", which allows us to be more flexible + // in defining bishop pair bonuses. + const int pieceCount[COLOR_NB][PIECE_TYPE_NB] = { + { pos.count<BISHOP>(WHITE) > 1, pos.count<PAWN>(WHITE), pos.count<KNIGHT>(WHITE), + pos.count<BISHOP>(WHITE) , pos.count<ROOK>(WHITE), pos.count<QUEEN >(WHITE) }, + { pos.count<BISHOP>(BLACK) > 1, pos.count<PAWN>(BLACK), pos.count<KNIGHT>(BLACK), + pos.count<BISHOP>(BLACK) , pos.count<ROOK>(BLACK), pos.count<QUEEN >(BLACK) } }; + + e->value = int16_t((imbalance<WHITE>(pieceCount) - imbalance<BLACK>(pieceCount)) / 16); + return e; +} + +} // namespace Material diff --git a/pool/shard007/C++/0094961_main.cpp b/pool/shard007/C++/0094961_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..47f0cca92fb9edb50d81c76272a3323181c0e402 --- /dev/null +++ b/pool/shard007/C++/0094961_main.cpp @@ -0,0 +1,25 @@ +#include <iostream> +#include <numeric> +#include <vector> + +using namespace std; + +int main() { + int t, k; + const int n = 100000; + const int mod = 1000000007; + cin >> t >> k; + vector<int> dp(n + 1, 1); + dp[0] = 0; + dp[k] = 2; + for (int a = k; a < n; ++a) { + dp[a + 1] = (dp[a] + dp[a - k + 1]) % mod; + } + partial_sum(begin(dp), end(dp), begin(dp), + [](auto x, auto y) { return (x + y) % mod; }); + while (t-- > 0) { + int a, b; + cin >> a >> b; + cout << (mod + dp[b] - dp[a - 1]) % mod << '\n'; + } +} diff --git a/pool/shard007/C++/0094964_MultiplayerMenuWidget.cpp b/pool/shard007/C++/0094964_MultiplayerMenuWidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0580a825113ccee50f717adc4f8469705136f8d9 --- /dev/null +++ b/pool/shard007/C++/0094964_MultiplayerMenuWidget.cpp @@ -0,0 +1,124 @@ +#include "SeagullGame/SeagullGame.h" + +#include "SeagullGame/UI/MenuHUD.h" +#include "MultiplayerMenuWidget.h" +#include "SeagullGame/UI/GlobalMenuStyle.h" +#include "SeagullGame/UI/MenuStyles.h" + +void SMultiplayerMenuWidget::Construct(const FArguments& args) +{ + MenuHUD = args._MenuHUD; + + MenuStyle = &FMenuStyles::Get().GetWidgetStyle<FGlobalStyle>("GlobalMenuStyle"); + + this->MakeMapValues(); + MapValue = MapValues[1]; + MenuHUD->UserMultiMap = *MapValue; + + this->MakePlayerNumValues(); + // Set the initial Player number value + for (int32 i = 0; i < PlayerNumValues.Num(); i++) + { + if (*PlayerNumValues[i] == *MenuHUD->UserNumMultiPlayers) + { + PlayerNum = PlayerNumValues[i]; + break; + } + + } + + ChildSlot + [ + SNew(SOverlay) + + SOverlay::Slot() + .HAlign(HAlign_Center) + .VAlign(VAlign_Center) + [ + SNew(SVerticalBox) + + SVerticalBox::Slot().Padding(5.0f).AutoHeight() + [ + SAssignNew(this->MapButton, STextComboBox) + .OptionsSource(&MapValues) + .OnSelectionChanged(this, &SMultiplayerMenuWidget::OnSelectedMap) + .InitiallySelectedItem(MapValue) + .Cursor(EMouseCursor::Hand) + ] + + SVerticalBox::Slot().Padding(10.0f).AutoHeight() + [ + SAssignNew(this->PlayerNumButton, STextComboBox) + .OptionsSource(&PlayerNumValues) + .OnSelectionChanged(this, &SMultiplayerMenuWidget::OnSelectedPlayerNum) + .InitiallySelectedItem(PlayerNum) + .Cursor(EMouseCursor::Hand) + ] + + SVerticalBox::Slot().Padding(5.0f).FillHeight(4.0f) + [ + SNew(SButton) + .HAlign(HAlign_Center) + .VAlign(VAlign_Center) + .Text(FText::FromString("Play")) + .OnClicked(this, &SMultiplayerMenuWidget::PlayMultiClicked) + .ButtonStyle(&MenuStyle->MenuButtonStyle) + .TextStyle(&MenuStyle->MenuButtonTextStyle) + ] + + SVerticalBox::Slot().Padding(10.0f).FillHeight(4.0f) + [ + SNew(SButton) + .HAlign(HAlign_Center) + .VAlign(VAlign_Center) + .Text(FText::FromString("Back")) + .OnClicked(this, &SMultiplayerMenuWidget::BackClicked) + .ButtonStyle(&MenuStyle->MenuButtonStyle) + .TextStyle(&MenuStyle->MenuButtonTextStyle) + ] + ] + ]; +} + +FReply SMultiplayerMenuWidget::PlayMultiClicked() +{ + MenuHUD->OpenLoadingScreen(); + MenuHUD->PlayMultiPlayerClicked(); + + return FReply::Handled(); +} + +FReply SMultiplayerMenuWidget::BackClicked() +{ + MenuHUD->ExitMenu(); + + return FReply::Handled(); +} + +void SMultiplayerMenuWidget::OnSelectedMap(TSharedPtr<FString> Item, ESelectInfo::Type SelectInfo) +{ + MapValue = Item; + MenuHUD->UserMultiMap = *Item; + MapButton->SetSelectedItem(Item); + MapButton->RefreshOptions(); +} + +void SMultiplayerMenuWidget::OnSelectedPlayerNum(TSharedPtr<FString> Item, ESelectInfo::Type SelectInfo) +{ + PlayerNum = Item; + MenuHUD->UserNumMultiPlayers = *Item; + PlayerNumButton->SetSelectedItem(Item); + PlayerNumButton->RefreshOptions(); + + MenuHUD->PlayerNumClicked(); + MenuHUD->OnSaveSettings(); +} + +void SMultiplayerMenuWidget::MakeMapValues() +{ + MapValues.Add(MakeShareable(new FString("MultiplayerBoxDrop"))); + MapValues.Add(MakeShareable(new FString("MultiplayerDestruction"))); + MapValues.Add(MakeShareable(new FString("MultiplayerShootEmUp"))); +} + +void SMultiplayerMenuWidget::MakePlayerNumValues() +{ + PlayerNumValues.Add(MakeShareable(new FString("2 Players"))); + //PlayerNumValues.Add(MakeShareable(new FString("3 Players"))); + PlayerNumValues.Add(MakeShareable(new FString("4 Players"))); +} diff --git a/pool/shard007/C++/0094966_test_bilinearity.cpp b/pool/shard007/C++/0094966_test_bilinearity.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5f3f8f24b503558f00900b303e4de9d9b2ce816f --- /dev/null +++ b/pool/shard007/C++/0094966_test_bilinearity.cpp @@ -0,0 +1,136 @@ +/** + ***************************************************************************** + * @author This file is part of libff, developed by SCIPR Lab + * and contributors (see AUTHORS). + * @copyright MIT license (see LICENSE file) + *****************************************************************************/ +#include <libff/algebra/curves/edwards/edwards_pp.hpp> +#include <libff/common/profiling.hpp> +#ifdef CURVE_BN128 +#include <libff/algebra/curves/bn128/bn128_pp.hpp> +#endif +#include <libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp> +#include <libff/algebra/curves/mnt/mnt4/mnt4_pp.hpp> +#include <libff/algebra/curves/mnt/mnt6/mnt6_pp.hpp> + +using namespace libff; + +template<typename ppT> +void pairing_test() +{ + GT<ppT> GT_one = GT<ppT>::one(); + + printf("Running bilinearity tests:\n"); + G1<ppT> P = (Fr<ppT>::random_element()) * G1<ppT>::one(); + //G1<ppT> P = Fr<ppT>("2") * G1<ppT>::one(); + G2<ppT> Q = (Fr<ppT>::random_element()) * G2<ppT>::one(); + //G2<ppT> Q = Fr<ppT>("3") * G2<ppT>::one(); + + printf("P:\n"); + P.print(); + P.print_coordinates(); + printf("Q:\n"); + Q.print(); + Q.print_coordinates(); + printf("\n\n"); + + Fr<ppT> s = Fr<ppT>::random_element(); + //Fr<ppT> s = Fr<ppT>("2"); + G1<ppT> sP = s * P; + G2<ppT> sQ = s * Q; + + printf("Pairing bilinearity tests (three must match):\n"); + GT<ppT> ans1 = ppT::reduced_pairing(sP, Q); + GT<ppT> ans2 = ppT::reduced_pairing(P, sQ); + GT<ppT> ans3 = ppT::reduced_pairing(P, Q)^s; + ans1.print(); + ans2.print(); + ans3.print(); + assert(ans1 == ans2); + assert(ans2 == ans3); + + assert(ans1 != GT_one); + assert((ans1^Fr<ppT>::field_char()) == GT_one); + printf("\n\n"); +} + +template<typename ppT> +void double_miller_loop_test() +{ + const G1<ppT> P1 = (Fr<ppT>::random_element()) * G1<ppT>::one(); + const G1<ppT> P2 = (Fr<ppT>::random_element()) * G1<ppT>::one(); + const G2<ppT> Q1 = (Fr<ppT>::random_element()) * G2<ppT>::one(); + const G2<ppT> Q2 = (Fr<ppT>::random_element()) * G2<ppT>::one(); + + const G1_precomp<ppT> prec_P1 = ppT::precompute_G1(P1); + const G1_precomp<ppT> prec_P2 = ppT::precompute_G1(P2); + const G2_precomp<ppT> prec_Q1 = ppT::precompute_G2(Q1); + const G2_precomp<ppT> prec_Q2 = ppT::precompute_G2(Q2); + + const Fqk<ppT> ans_1 = ppT::miller_loop(prec_P1, prec_Q1); + const Fqk<ppT> ans_2 = ppT::miller_loop(prec_P2, prec_Q2); + const Fqk<ppT> ans_12 = ppT::double_miller_loop(prec_P1, prec_Q1, prec_P2, prec_Q2); + assert(ans_1 * ans_2 == ans_12); +} + +template<typename ppT> +void affine_pairing_test() +{ + GT<ppT> GT_one = GT<ppT>::one(); + + printf("Running bilinearity tests:\n"); + G1<ppT> P = (Fr<ppT>::random_element()) * G1<ppT>::one(); + G2<ppT> Q = (Fr<ppT>::random_element()) * G2<ppT>::one(); + + printf("P:\n"); + P.print(); + printf("Q:\n"); + Q.print(); + printf("\n\n"); + + Fr<ppT> s = Fr<ppT>::random_element(); + G1<ppT> sP = s * P; + G2<ppT> sQ = s * Q; + + printf("Pairing bilinearity tests (three must match):\n"); + GT<ppT> ans1 = ppT::affine_reduced_pairing(sP, Q); + GT<ppT> ans2 = ppT::affine_reduced_pairing(P, sQ); + GT<ppT> ans3 = ppT::affine_reduced_pairing(P, Q)^s; + ans1.print(); + ans2.print(); + ans3.print(); + assert(ans1 == ans2); + assert(ans2 == ans3); + + assert(ans1 != GT_one); + assert((ans1^Fr<ppT>::field_char()) == GT_one); + printf("\n\n"); +} + +int main(void) +{ + start_profiling(); + edwards_pp::init_public_params(); + pairing_test<edwards_pp>(); + double_miller_loop_test<edwards_pp>(); + + mnt6_pp::init_public_params(); + pairing_test<mnt6_pp>(); + double_miller_loop_test<mnt6_pp>(); + affine_pairing_test<mnt6_pp>(); + + mnt4_pp::init_public_params(); + pairing_test<mnt4_pp>(); + double_miller_loop_test<mnt4_pp>(); + affine_pairing_test<mnt4_pp>(); + + alt_bn128_pp::init_public_params(); + pairing_test<alt_bn128_pp>(); + double_miller_loop_test<alt_bn128_pp>(); + +#ifdef CURVE_BN128 // BN128 has fancy dependencies so it may be disabled + bn128_pp::init_public_params(); + pairing_test<bn128_pp>(); + double_miller_loop_test<bn128_pp>(); +#endif +} diff --git a/pool/shard007/C++/0094967_known_tiles.cpp b/pool/shard007/C++/0094967_known_tiles.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7368beb438e7a93d427ad6751097070752798311 --- /dev/null +++ b/pool/shard007/C++/0094967_known_tiles.cpp @@ -0,0 +1,34 @@ +#include "stdafx.h" +#include "known_tiles.h" + +template <class Archive> +void KnownTiles::serialize(Archive& ar, const unsigned int version) { + ar(known, border); +} + +SERIALIZABLE(KnownTiles); + +void KnownTiles::addTile(Position pos) { + known.set(pos, true); + border.erase(pos); + for (Position v : pos.neighbors4()) + if (!known.get(v)) + border.insert(v); +} + +const set<Position>& KnownTiles::getBorderTiles() const { + return border; +} + +bool KnownTiles::isKnown(Position pos) const { + return known.get(pos); +}; + +void KnownTiles::limitToModel(const WModel m) { + set<Position> copy; + for (Position p : border) + if (p.getModel() == m) + copy.insert(p); + border = copy; + known.limitToModel(m); +} diff --git a/pool/shard007/C++/0094974_filecnts.cpp b/pool/shard007/C++/0094974_filecnts.cpp new file mode 100644 index 0000000000000000000000000000000000000000..566dbdec3711c8b6e095c0f41c6fe6442f0562ee --- /dev/null +++ b/pool/shard007/C++/0094974_filecnts.cpp @@ -0,0 +1,127 @@ +/* + filecnts.cpp + + flexemu, an MC6809 emulator running FLEX + Copyright (C) 2020-2022 W. Schwotzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +*/ + +#include "filecnts.h" +#include <ostream> +#include <iomanip> +#include <string> +#include <sstream> + +std::ostream& operator<<(std::ostream& os, const st_t &st) +{ + auto previous_flags = os.flags(); + auto previous_fill = os.fill('0'); + + os << + std::hex << std::uppercase << + std::setw(2) << (Word)st.trk << "-" << + std::setw(2) << (Word)st.sec; + os.fill(previous_fill); + os.flags(previous_flags); + + return os; +} + +// Return the sector count on track 0 which has always single density (SD) +// except for a harddisk. +Word getTrack0SectorCount(int tracks, int sectors) +{ + if (tracks >= 255) + { + // This is a harddisk. Assuming same density for all tracks. + return static_cast<Word>(sectors); + } + + // Check for 8-inch disk. + if (tracks == 77) + { + if (sectors <= 26) + { + // This is a 8-inch single sided (SS) disk. + return 15U; + } + // This is a 8-inch double sided (DS) disk. + return 30U; + } + + // Assuming 5 1/4-inch or 3 1/2-inch disk. 34, 35, 40 or 80 tracks. + if (sectors <= 18) + { + // This is a single sided (SS) disk. + // This rule can be applied when creating a DSK container. + // When reading a DSK container both 10 or 20 sectors + // has to be supported. + return 10U; + } + // This is a double sided (DS) disk. + return 20U; +} + +// Return the number of sides. +Word getSides(int tracks, int sectors) +{ + if (tracks >= 255) + { + // There are no details available about how many sides a hard disk + // used by FLEX has => Return the default. + return 1U; + } + + // Check for 8-inch disk. + if (tracks == 77) + { + if (sectors <= 26) + { + // This is a 8-inch single sided (SS) disk. + return 1U; + } + // This is a 8-inch double sided (DS) disk if sector count is a + // multiple of 2. + return !(sectors % 2) ? 2 : 1; + } + + // Assuming 5 1/4-inch or 3 1/2-inch disk. 34, 35, 40 or 80 tracks. + if (sectors <= 18) + { + // This is a single sided (SS) disk. + // This rule can be applied when creating a FLX container. + // When reading a FLX container both single or double sided + // has to be supported. + return 1U; + } + // This is a double sided (DS) disk if sector count is a + // multiple of 2. + return !(sectors % 2) ? 2U : 1U; +} + +Word getBytesPerSector(int sizecode) +{ + return 128U << (sizecode & 0x03); +} + +size_t getFileSize(const s_flex_header &header) +{ + return sizeof(s_flex_header) + + ((header.sectors0 * header.sides0) + + ((header.tracks - 1) * (header.sectors * header.sides))) * + getBytesPerSector(header.sizecode); +} + diff --git a/pool/shard007/C++/0094975_AddingReverse.cpp b/pool/shard007/C++/0094975_AddingReverse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..32ed9562353940568016500ae750eb8e4df3fb80 --- /dev/null +++ b/pool/shard007/C++/0094975_AddingReverse.cpp @@ -0,0 +1,39 @@ +#include <stdio.h> +#include <algorithm> +#include <sstream> + +using namespace std; + +int n, a, b; + +int pow(int n, int x) { + int ans = n; + for(int i = 1; i <= x; i++) ans *= n; + return ans; +} + +int reverse(int x) { + string a = ""; + int ans = 0; + while(x > 0) { + a += (x % 10) + '0'; + x /= 10; + } + istringstream ss(a); + ss >> ans; + return ans; +} + +int main(void) { + scanf("%d", &n); + + while(n--) { + scanf("%d%d", &a, &b); + int aa = reverse(a); + int bb = reverse(b); + + printf("%d\n", reverse(aa+bb)); + } + + return 0; +} diff --git a/pool/shard007/C++/0094978_juce_android_RuntimePermissions.cpp b/pool/shard007/C++/0094978_juce_android_RuntimePermissions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..54d0be448a3891950de2e8c5bb44f0cc991b7086 --- /dev/null +++ b/pool/shard007/C++/0094978_juce_android_RuntimePermissions.cpp @@ -0,0 +1,88 @@ +/* + ============================================================================== + + This file is part of the JUCE library. + Copyright (c) 2017 - ROLI Ltd. + + JUCE is an open source library subject to commercial or open-source + licensing. + + The code included in this file is provided under the terms of the ISC license + http://www.isc.org/downloads/software-support-policy/isc-license. Permission + To use, copy, modify, and/or distribute this software for any purpose with or + without fee is hereby granted provided that the above copyright notice and + this permission notice appear in all copies. + + JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER + EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE + DISCLAIMED. + + ============================================================================== +*/ + +namespace juce +{ + +static void handleAndroidCallback (bool permissionWasGranted, RuntimePermissions::Callback* callbackPtr) +{ + if (callbackPtr == nullptr) + { + // got a nullptr passed in from java! this should never happen... + jassertfalse; + return; + } + + std::unique_ptr<RuntimePermissions::Callback> uptr (callbackPtr); + + if (RuntimePermissions::Callback callbackObj = *uptr) + callbackObj (permissionWasGranted); +} + +JUCE_JNI_CALLBACK (JUCE_ANDROID_ACTIVITY_CLASSNAME, + androidRuntimePermissionsCallback, + void, (JNIEnv* env, jobject, jboolean permissionsGranted, jlong callbackPtr)) +{ + setEnv (env); + handleAndroidCallback (permissionsGranted != 0, + reinterpret_cast<RuntimePermissions::Callback*> (callbackPtr)); +} + +void RuntimePermissions::request (PermissionID permission, Callback callback) +{ + if (! android.activity.callBooleanMethod (JuceAppActivity.isPermissionDeclaredInManifest, (jint) permission)) + { + // Error! If you want to be able to request this runtime permission, you + // also need to declare it in your app's manifest. You can do so via + // the Projucer. Otherwise this can't work. + jassertfalse; + + callback (false); + return; + } + + if (JUCE_ANDROID_API_VERSION < 23) + { + // There is no runtime permission system on API level below 23. As long as the + // permission is in the manifest (seems to be the case), we can simply ask Android + // if the app has the permission, and then directly call through to the callback. + callback (isGranted (permission)); + return; + } + + // we need to move the callback object to the heap so Java can keep track of the pointer + // and asynchronously pass it back to us (to be called and then deleted) + Callback* callbackPtr = new Callback (std::move (callback)); + android.activity.callVoidMethod (JuceAppActivity.requestRuntimePermission, permission, (jlong) callbackPtr); +} + +bool RuntimePermissions::isRequired (PermissionID /*permission*/) +{ + return JUCE_ANDROID_API_VERSION >= 23; +} + +bool RuntimePermissions::isGranted (PermissionID permission) +{ + return android.activity.callBooleanMethod (JuceAppActivity.isPermissionGranted, permission); +} + +} // namespace juce diff --git a/pool/shard007/C++/0094979_SettingsDateTimeMenuItem.cpp b/pool/shard007/C++/0094979_SettingsDateTimeMenuItem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d978475e3124c85287eff390d8b7a762bc2b7cbe --- /dev/null +++ b/pool/shard007/C++/0094979_SettingsDateTimeMenuItem.cpp @@ -0,0 +1,58 @@ +/************************************************************************* + +bq Cervantes e-book reader application +Copyright (C) 2011-2013 Mundoreader, S.L + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with the source code. If not, see <http://www.gnu.org/licenses/>. + +*************************************************************************/ + +#include "SettingsDateTimeMenuItem.h" +#include <QDebug> +#include <QPainter> + +SettingsDateTimeMenuItem::SettingsDateTimeMenuItem (QWidget* parent) : GestureWidget(parent){ + qDebug() << "--->" << Q_FUNC_INFO; + connect(this, SIGNAL(tap()), this, SLOT(handleTap())); + setupUi(this); +} + +SettingsDateTimeMenuItem::~SettingsDateTimeMenuItem (){ + qDebug() << "--->" << Q_FUNC_INFO; +} + +void SettingsDateTimeMenuItem::paint (TimeZone* _timeZone){ + qDebug() << "--->" << Q_FUNC_INFO; + timeZone = _timeZone; + + timeZoneCountriesLbl->setText(timeZone->description); + gtmLbl->setText(timeZone->timeZone); + if(timeZone->defaultTimeZone) + checkTimezoneLbl->show(); + else + checkTimezoneLbl->hide(); + +} + +void SettingsDateTimeMenuItem::handleTap ( ){ + qDebug() << "--->" << Q_FUNC_INFO; + emit setTimeZone(timeZone); +} + +void SettingsDateTimeMenuItem::paintEvent (QPaintEvent *){ + QStyleOption opt; + opt.init(this); + QPainter p(this); + style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); + } diff --git a/pool/shard007/C++/0094983_datafeeder.cpp b/pool/shard007/C++/0094983_datafeeder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1594d0d4e035571d4987ede0857b1ca270bb90cd --- /dev/null +++ b/pool/shard007/C++/0094983_datafeeder.cpp @@ -0,0 +1,63 @@ +#include <sstream> +#include <iostream> +#include <cstring> +#include "datafeeder.h" + +void DataFeeder::init() +{ + m_pLevel2Api->RegisterSpi(this); + m_pLevel2Api->RegisterFront(const_cast<char*>(this->front_address.c_str())); + // 使客户端开始与后台服务建立连接 + m_pLevel2Api->Init(); +} + +void DataFeeder::OnFrontConnected() +{ + CThostFtdcReqUserLoginField reqUserLogin; + memset(&reqUserLogin, 0, sizeof(reqUserLogin)); + strcpy(reqUserLogin.BrokerID, this->brokerID.c_str()); + strcpy(reqUserLogin.UserID, this->userID.c_str()); + strcpy(reqUserLogin.Password, this->passwd.c_str()); + m_pLevel2Api->ReqUserLogin(&reqUserLogin, 0); +} + +void DataFeeder::OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) +{ + std::cout << "OnRspUserLogin:\t" << "ErrorCode=[" << pRspInfo->ErrorID << "], ErrorMsg=[" << pRspInfo->ErrorMsg << "]" << std::endl; + if (pRspInfo->ErrorID != 0) + std::cout << "Error: Login Error!" << std::endl; +} + +void DataFeeder::subscrib_L2_market_data(std::string stockid) +{ + CThostFtdcSpecificSecurityField query; + memset(&query, 0, sizeof(query)); + std::string security_id = stockid.substr(2); + std::string exchange_id = this->ExchangeIDDict[ stockid.substr(0,2) ]; + strcpy(query.SecurityID, security_id.c_str()); + strcpy(query.ExchangeID, exchange_id.c_str()); + + m_pLevel2Api->SubscribeLevel2MarketData(&query, 1); +} + +void DataFeeder::OnRtnLevel2MarketData(CThostFtdcLevel2MarketDataField *pLevel2MarketData) +{ + std::ostringstream oss; + CThostFtdcLevel2MarketDataField *p = pLevel2MarketData; + std::string stockid = this->ExchangeIDDict_Reverse[p->ExchangeID] + p->SecurityID; + + oss << stockid << ',' << p->OpenPx << ',' << p->PreClosePx << ',' << p->LastPx << ',' << p->HighPx << ',' << p->LowPx << ',' + << p->TotalVolumeTrade << ',' << p->TotalValueTrade << ',' + << p->BidPx1 << ',' << p->BidOrderQty1 << ',' << p->BidPx2 << ',' << p->BidOrderQty2 << ',' << p->BidPx3 << ',' << p->BidOrderQty3 << ',' + << p->OfferPx1 << ',' << p->OfferOrderQty1 << ',' << p->OfferPx2 << ',' << p->OfferOrderQty2 << ',' << p->OfferPx3 << ',' << p->OfferOrderQty3 << ',' + << p->TradingDay << ',' << p->DataTimeStamp; + + stock_datas[stockid] = oss.str(); +// std::cout << stock_datas[stockid] << std::endl; +} + +std::string DataFeeder::get_L2_market_data(std::string stockid) +{ + return this->stock_datas[stockid]; +} + diff --git a/pool/shard007/C++/0094989_frame_handler.cc b/pool/shard007/C++/0094989_frame_handler.cc new file mode 100644 index 0000000000000000000000000000000000000000..d3fda63b3dd9cfb5564d8952e7e9e047a0b1b463 --- /dev/null +++ b/pool/shard007/C++/0094989_frame_handler.cc @@ -0,0 +1,218 @@ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/tsi/alts/frame_protector/frame_handler.h" + +#include <limits.h> +#include <stdint.h> +#include <string.h> + +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> + +#include "src/core/lib/gpr/useful.h" + +/* Use little endian to interpret a string of bytes as uint32_t. */ +static uint32_t load_32_le(const unsigned char* buffer) { + return (((uint32_t)buffer[3]) << 24) | (((uint32_t)buffer[2]) << 16) | + (((uint32_t)buffer[1]) << 8) | ((uint32_t)buffer[0]); +} + +/* Store uint32_t as a string of little endian bytes. */ +static void store_32_le(uint32_t value, unsigned char* buffer) { + buffer[3] = (unsigned char)(value >> 24) & 0xFF; + buffer[2] = (unsigned char)(value >> 16) & 0xFF; + buffer[1] = (unsigned char)(value >> 8) & 0xFF; + buffer[0] = (unsigned char)(value)&0xFF; +} + +/* Frame writer implementation. */ +alts_frame_writer* alts_create_frame_writer() { + alts_frame_writer* writer = + static_cast<alts_frame_writer*>(gpr_zalloc(sizeof(*writer))); + return writer; +} + +bool alts_reset_frame_writer(alts_frame_writer* writer, + const unsigned char* buffer, size_t length) { + if (buffer == nullptr) return false; + size_t max_input_size = SIZE_MAX - kFrameLengthFieldSize; + if (length > max_input_size) { + gpr_log(GPR_ERROR, "length must be at most %zu", max_input_size); + return false; + } + writer->input_buffer = buffer; + writer->input_size = length; + writer->input_bytes_written = 0; + writer->header_bytes_written = 0; + store_32_le( + static_cast<uint32_t>(writer->input_size + kFrameMessageTypeFieldSize), + writer->header_buffer); + store_32_le(kFrameMessageType, writer->header_buffer + kFrameLengthFieldSize); + return true; +} + +bool alts_write_frame_bytes(alts_frame_writer* writer, unsigned char* output, + size_t* bytes_size) { + if (bytes_size == nullptr || output == nullptr) return false; + if (alts_is_frame_writer_done(writer)) { + *bytes_size = 0; + return true; + } + size_t bytes_written = 0; + /* Write some header bytes, if needed. */ + if (writer->header_bytes_written != sizeof(writer->header_buffer)) { + size_t bytes_to_write = + GPR_MIN(*bytes_size, + sizeof(writer->header_buffer) - writer->header_bytes_written); + memcpy(output, writer->header_buffer + writer->header_bytes_written, + bytes_to_write); + bytes_written += bytes_to_write; + *bytes_size -= bytes_to_write; + writer->header_bytes_written += bytes_to_write; + output += bytes_to_write; + if (writer->header_bytes_written != sizeof(writer->header_buffer)) { + *bytes_size = bytes_written; + return true; + } + } + /* Write some non-header bytes. */ + size_t bytes_to_write = + GPR_MIN(writer->input_size - writer->input_bytes_written, *bytes_size); + memcpy(output, writer->input_buffer, bytes_to_write); + writer->input_buffer += bytes_to_write; + bytes_written += bytes_to_write; + writer->input_bytes_written += bytes_to_write; + *bytes_size = bytes_written; + return true; +} + +bool alts_is_frame_writer_done(alts_frame_writer* writer) { + return writer->input_buffer == nullptr || + writer->input_size == writer->input_bytes_written; +} + +size_t alts_get_num_writer_bytes_remaining(alts_frame_writer* writer) { + return (sizeof(writer->header_buffer) - writer->header_bytes_written) + + (writer->input_size - writer->input_bytes_written); +} + +void alts_destroy_frame_writer(alts_frame_writer* writer) { gpr_free(writer); } + +/* Frame reader implementation. */ +alts_frame_reader* alts_create_frame_reader() { + alts_frame_reader* reader = + static_cast<alts_frame_reader*>(gpr_zalloc(sizeof(*reader))); + return reader; +} + +bool alts_is_frame_reader_done(alts_frame_reader* reader) { + return reader->output_buffer == nullptr || + (reader->header_bytes_read == sizeof(reader->header_buffer) && + reader->bytes_remaining == 0); +} + +bool alts_has_read_frame_length(alts_frame_reader* reader) { + return sizeof(reader->header_buffer) == reader->header_bytes_read; +} + +size_t alts_get_reader_bytes_remaining(alts_frame_reader* reader) { + return alts_has_read_frame_length(reader) ? reader->bytes_remaining : 0; +} + +void alts_reset_reader_output_buffer(alts_frame_reader* reader, + unsigned char* buffer) { + reader->output_buffer = buffer; +} + +bool alts_reset_frame_reader(alts_frame_reader* reader, unsigned char* buffer) { + if (buffer == nullptr) return false; + reader->output_buffer = buffer; + reader->bytes_remaining = 0; + reader->header_bytes_read = 0; + reader->output_bytes_read = 0; + return true; +} + +bool alts_read_frame_bytes(alts_frame_reader* reader, + const unsigned char* bytes, size_t* bytes_size) { + if (bytes_size == nullptr) return false; + if (bytes == nullptr) { + *bytes_size = 0; + return false; + } + if (alts_is_frame_reader_done(reader)) { + *bytes_size = 0; + return true; + } + size_t bytes_processed = 0; + /* Process the header, if needed. */ + if (reader->header_bytes_read != sizeof(reader->header_buffer)) { + size_t bytes_to_write = GPR_MIN( + *bytes_size, sizeof(reader->header_buffer) - reader->header_bytes_read); + memcpy(reader->header_buffer + reader->header_bytes_read, bytes, + bytes_to_write); + reader->header_bytes_read += bytes_to_write; + bytes_processed += bytes_to_write; + bytes += bytes_to_write; + *bytes_size -= bytes_to_write; + if (reader->header_bytes_read != sizeof(reader->header_buffer)) { + *bytes_size = bytes_processed; + return true; + } + size_t frame_length = load_32_le(reader->header_buffer); + if (frame_length < kFrameMessageTypeFieldSize || + frame_length > kFrameMaxSize) { + gpr_log(GPR_ERROR, + "Bad frame length (should be at least %zu, and at most %zu)", + kFrameMessageTypeFieldSize, kFrameMaxSize); + *bytes_size = 0; + return false; + } + size_t message_type = + load_32_le(reader->header_buffer + kFrameLengthFieldSize); + if (message_type != kFrameMessageType) { + gpr_log(GPR_ERROR, "Unsupported message type %zu (should be %zu)", + message_type, kFrameMessageType); + *bytes_size = 0; + return false; + } + reader->bytes_remaining = frame_length - kFrameMessageTypeFieldSize; + } + /* Process the non-header bytes. */ + size_t bytes_to_write = GPR_MIN(*bytes_size, reader->bytes_remaining); + memcpy(reader->output_buffer, bytes, bytes_to_write); + reader->output_buffer += bytes_to_write; + bytes_processed += bytes_to_write; + reader->bytes_remaining -= bytes_to_write; + reader->output_bytes_read += bytes_to_write; + *bytes_size = bytes_processed; + return true; +} + +size_t alts_get_output_bytes_read(alts_frame_reader* reader) { + return reader->output_bytes_read; +} + +unsigned char* alts_get_output_buffer(alts_frame_reader* reader) { + return reader->output_buffer; +} + +void alts_destroy_frame_reader(alts_frame_reader* reader) { gpr_free(reader); } diff --git a/pool/shard007/C++/0095004_CombinationSum2.cpp b/pool/shard007/C++/0095004_CombinationSum2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1dcbad3b39c445ef32394f2408148924df7f8a57 --- /dev/null +++ b/pool/shard007/C++/0095004_CombinationSum2.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2012 Binson Zhang. + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @author Binson Zhang <bin183cs@gmail.com> + * @date 2012-12-28 + */ + +#include <iostream> +#include <vector> +#include <set> +#include <algorithm> +using namespace std; + +class Solution { +public: + typedef vector<int> Vec; + typedef vector<Vec> Vecs; + typedef vector<Vecs> VecsArr; + vector<vector<int> > combinationSum2(vector<int> &candidates, int target) { + VecsArr d(target + 1); + d[0].push_back(Vec()); + int top = 0; + for (size_t j = 0; j < candidates.size(); ++j) { + for (int i = top; i >= 0; --i) { + if (d[i].size() > 0) { + size_t k = i + candidates[j]; + if (k > target) continue; + for (size_t p = 0; p < d[i].size(); ++p) { + d[k].push_back(d[i][p]); + d[k].back().push_back(candidates[j]); + } + top = std::max(top, (int)k); + } + } + } + + Vecs res = d[target]; + Vecs uqres; + set<Vec> st; + for (size_t i = 0; i < res.size(); ++i) { + std::sort(res[i].begin(), res[i].end()); + if (st.count(res[i]) == 0) { + st.insert(res[i]); + uqres.push_back(res[i]); + } + } + return uqres; + } +}; + +#include "util.h" + +int main(int argc, char **argv) { + std::cout << "------" << argv[0] << "------" << std::endl; + + int target = 10; + int arr[] = {2, 3, 5, 7}; + int sz = sizeof(arr) / sizeof(arr[0]); + vector<int> vec(arr, arr + sz); + + std::cout << "Input:\n"; + Output(vec); + + Solution s; + vector<vector<int> > vecs = s.combinationSum2(vec, target); + + std::cout << "Output:\n"; + Output(vecs); + + return 0; +} diff --git a/pool/shard007/C++/0095006_KytheIndexerMain.cc b/pool/shard007/C++/0095006_KytheIndexerMain.cc new file mode 100644 index 0000000000000000000000000000000000000000..52f4e4950dcda9211786c7632736e52866a946b1 --- /dev/null +++ b/pool/shard007/C++/0095006_KytheIndexerMain.cc @@ -0,0 +1,89 @@ +/* + * Copyright 2014 Google Inc. 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. + */ + +// Allows the Kythe C++ indexer to be invoked from the command line. By default, +// this program reads a single C++ compilation unit from stdin and emits +// binary Kythe artifacts to stdout as a sequence of Entity protos. +// Command-line arguments may be passed to Clang as positional parameters. +// +// eg: indexer -i foo.cc -o foo.bin -- -DINDEXING +// indexer -i foo.cc | verifier foo.cc +// indexer some/index.kindex + +#include "gflags/gflags.h" +#include "google/protobuf/stubs/common.h" +#include "kythe/cxx/common/indexing/frontend.h" +#include "kythe/cxx/indexer/cxx/IndexerFrontendAction.h" + +DEFINE_bool(index_template_instantiations, true, + "Index template instantiations."); +DEFINE_bool(experimental_drop_instantiation_independent_data, false, + "Don't emit template nodes and edges found to be " + "instantiation-independent."); +DEFINE_bool(report_profiling_events, false, + "Write profiling events to standard error."); +DEFINE_bool(experimental_index_lite, false, + "Drop uncommonly-used data from the index."); + +namespace kythe { + +int main(int argc, char *argv[]) { + GOOGLE_PROTOBUF_VERIFY_VERSION; + google::InitGoogleLogging(argv[0]); + google::SetVersionString("0.1"); + google::SetUsageMessage( + IndexerContext::UsageMessage("the Kythe C++ indexer", "indexer")); + google::ParseCommandLineFlags(&argc, &argv, true); + std::vector<std::string> final_args(argv, argv + argc); + IndexerContext context(final_args, "stdin.cc"); + IndexerOptions options; + options.TemplateBehavior = FLAGS_index_template_instantiations + ? BehaviorOnTemplates::VisitInstantiations + : BehaviorOnTemplates::SkipInstantiations; + options.UnimplementedBehavior = context.ignore_unimplemented() + ? kythe::BehaviorOnUnimplemented::Continue + : kythe::BehaviorOnUnimplemented::Abort; + options.Verbosity = FLAGS_experimental_index_lite ? kythe::Verbosity::Lite + : kythe::Verbosity::Classic; + options.DropInstantiationIndependentData = + FLAGS_experimental_drop_instantiation_independent_data; + options.AllowFSAccess = context.allow_filesystem_access(); + options.EnableLossyClaiming = context.enable_lossy_claiming(); + options.EffectiveWorkingDirectory = context.working_directory(); + if (FLAGS_report_profiling_events) { + options.ReportProfileEvent = [](const char *counter, ProfilingEvent event) { + fprintf(stderr, "%s: %s\n", counter, + event == ProfilingEvent::Enter ? "enter" : "exit"); + }; + } + + kythe::MetadataSupports meta_supports; + meta_supports.push_back(llvm::make_unique<KytheMetadataSupport>()); + + std::string result = IndexCompilationUnit( + context.unit(), *context.virtual_files(), *context.claim_client(), + context.hash_cache(), *context.output(), options, &meta_supports); + + if (!result.empty()) { + fprintf(stderr, "Error: %s\n", result.c_str()); + } + + return !result.empty(); +} + +} // namespace kythe + +int main(int argc, char *argv[]) { return kythe::main(argc, argv); } diff --git a/pool/shard007/C++/0095008_2136.cpp b/pool/shard007/C++/0095008_2136.cpp new file mode 100644 index 0000000000000000000000000000000000000000..589f0ac1ccb370f5dcd737a5f9fba3b9e402f4e8 --- /dev/null +++ b/pool/shard007/C++/0095008_2136.cpp @@ -0,0 +1,49 @@ +#include <bits/stdc++.h> +using namespace std; + +string findFriend(queue<string> list) { + int max = 0; + string name = ""; + + while(!list.empty()){ + if(list.front().size() > max) { + max = list.front().size(); + name = list.front(); + } + list.pop(); + } + + return name; +} + +int main() { + string name, option, amigo; + queue<string> friends; + set<string> friendsList, unfriendsList; + set<string>::iterator i; + + while(cin >> name && name != "FIM") { + cin >> option; + + if(option == "YES"){ + friends.push(name); + friendsList.insert(name); + }else { + unfriendsList.insert(name); + } + } + + amigo = findFriend(friends); + + i = friendsList.begin(); + for( ; i != friendsList.end(); i++) + cout << (*i) << '\n'; + + i = unfriendsList.begin(); + for( ; i != unfriendsList.end(); i++) + cout << (*i) << '\n'; + + cout << "\nAmigo do Habay:\n" << amigo << '\n'; + + return 0; +} diff --git a/pool/shard007/C++/0095012_SpeechDriverFactory.cpp b/pool/shard007/C++/0095012_SpeechDriverFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cdb27bda4fa5189d9def8665dd2400c5e274cb6f --- /dev/null +++ b/pool/shard007/C++/0095012_SpeechDriverFactory.cpp @@ -0,0 +1,247 @@ +#include "SpeechDriverFactory.h" +#include "SpeechType.h" +#include "SpeechDriverInterface.h" +#include "SpeechDriverDummy.h" +#include "SpeechDriverLAD.h" +#include <DfoDefines.h> + +#include <utils/threads.h> + +#ifdef EVDO_DT_SUPPORT //evod modem speech driver +#include "SpeechDriverEVDO.h" +#endif + +#if defined (DSDA_SUPPORT) +#include "SpeechDriverDSDA.h" +#endif + +#define LOG_TAG "SpeechDriverFactory" + +namespace android +{ + +SpeechDriverFactory *SpeechDriverFactory::mSpeechDriverFactory = NULL; +SpeechDriverFactory *SpeechDriverFactory::GetInstance() +{ + static Mutex mGetInstanceLock; + Mutex::Autolock _l(mGetInstanceLock); + ALOGV("%s()", __FUNCTION__); + + if (mSpeechDriverFactory == NULL) + { + mSpeechDriverFactory = new SpeechDriverFactory(); + } + ASSERT(mSpeechDriverFactory != NULL); + return mSpeechDriverFactory; +} + +SpeechDriverFactory::SpeechDriverFactory() +{ + ALOGV("%s()", __FUNCTION__); + + mSpeechDriver1 = NULL; + mSpeechDriver2 = NULL; + mSpeechDriverExternal = NULL; + + if (MTK_ENABLE_MD1 == true) + { + mActiveModemIndex = MODEM_1; // default use modem 1 + } + else if (MTK_ENABLE_MD2 == true) + { + mActiveModemIndex = MODEM_2; // if modem 1 not enabled, default use modem 2 + } + else if (MTK_ENABLE_MD5 == true) // if modem 1 & 2 not enabled, default use LTE/DSDA case + { + mActiveModemIndex = MODEM_EXTERNAL; + } + else + { +#if defined(EVDO_DT_SUPPORT) + mActiveModemIndex = MODEM_EXTERNAL; // if modem evdo, default use modem external +#else + ALOGW("mActiveModemIndex default use modem 1 !!"); + mActiveModemIndex = MODEM_1; // default use modem 1 +#endif + } + + CreateSpeechDriverInstances(); + + ALOGD("-%s(), mActiveModemIndex = %d", __FUNCTION__, mActiveModemIndex); +} +status_t SpeechDriverFactory::CreateSpeechDriverInstances() +{ + /// Create mSpeechDriver for modem 1 + if (MTK_ENABLE_MD1 == true) + { + // for internal modem_1, always return LAD + ALOGD("Create SpeechDriverLAD for MODEM_1"); + mSpeechDriver1 = SpeechDriverLAD::GetInstance(MODEM_1); + } + else + { + ALOGW("Create SpeechDriverDummy for MODEM_1"); + mSpeechDriver1 = new SpeechDriverDummy(MODEM_1); + } + + + /// Create mSpeechDriver for modem 2 + if (MTK_ENABLE_MD2 == true) + { + // for modem_2, might use internal/external modem + ALOGD("Create SpeechDriverLAD for MODEM_2"); + mSpeechDriver2 = SpeechDriverLAD::GetInstance(MODEM_2); + } + else + { + ALOGW("Create SpeechDriverDummy for MODEM_2"); + mSpeechDriver2 = new SpeechDriverDummy(MODEM_2); + } + + + /// Create mSpeechDriver for modem external + if (MTK_ENABLE_MD5 == true) + { +#if defined (DSDA_SUPPORT) + ALOGD("Create SpeechDriverDSDA for MODEM_EXTERNAL"); + mSpeechDriverExternal = SpeechDriverDSDA::GetInstance(MODEM_EXTERNAL); +#else + ALOGD("Create SpeechDriverLAD for MODEM_EXTERNAL"); // for external modem LTE: use EEMCS + mSpeechDriverExternal = SpeechDriverLAD::GetInstance(MODEM_EXTERNAL); +#endif + } + else + { +#if defined (EVDO_DT_SUPPORT) // evdo modem speech driver + ALOGD("Create SpeechDriverEVDO for MODEM_EXTERNAL"); + mSpeechDriverExternal = SpeechDriverEVDO::GetInstance(MODEM_EXTERNAL); +#else + ALOGW("Create SpeechDriverDummy for MODEM_EXTERNAL"); + mSpeechDriverExternal = new SpeechDriverDummy(MODEM_EXTERNAL); +#endif + } + + return NO_ERROR; +} + +status_t SpeechDriverFactory::DestroySpeechDriverInstances() +{ + if (mSpeechDriver1 != NULL) + { + delete mSpeechDriver1; + mSpeechDriver1 = NULL; + } + + if (mSpeechDriver2 != NULL) + { + delete mSpeechDriver2; + mSpeechDriver2 = NULL; + } + + if (mSpeechDriverExternal != NULL) + { + delete mSpeechDriverExternal; + mSpeechDriverExternal = NULL; + } + return NO_ERROR; +} + +SpeechDriverFactory::~SpeechDriverFactory() +{ + DestroySpeechDriverInstances(); +} + +SpeechDriverInterface *SpeechDriverFactory::GetSpeechDriver() +{ + SpeechDriverInterface *pSpeechDriver = NULL; + ALOGD("%s(), mActiveModemIndex=%d", __FUNCTION__, mActiveModemIndex); + + switch (mActiveModemIndex) + { + case MODEM_1: + pSpeechDriver = mSpeechDriver1; + break; + case MODEM_2: + pSpeechDriver = mSpeechDriver2; + break; + case MODEM_EXTERNAL: + pSpeechDriver = mSpeechDriverExternal; + break; + default: + ALOGE("%s: no such modem index %d", __FUNCTION__, mActiveModemIndex); + break; + } + + ASSERT(pSpeechDriver != NULL); + return pSpeechDriver; +} + +/** + * NO GUARANTEE that the returned pointer is not NULL!! + * Be careful to use this function!! + */ +SpeechDriverInterface *SpeechDriverFactory::GetSpeechDriverByIndex(const modem_index_t modem_index) +{ + SpeechDriverInterface *pSpeechDriver = NULL; + ALOGD("%s(), modem_index=%d", __FUNCTION__, modem_index); + + switch (modem_index) + { + case MODEM_1: + pSpeechDriver = mSpeechDriver1; + break; + case MODEM_2: + pSpeechDriver = mSpeechDriver2; + break; + case MODEM_EXTERNAL: + pSpeechDriver = mSpeechDriverExternal; + break; + default: + ALOGE("%s: no such modem index %d", __FUNCTION__, modem_index); + break; + } + + return pSpeechDriver; +} + + +modem_index_t SpeechDriverFactory::GetActiveModemIndex() const +{ + ALOGD("%s(), active modem index = %d", __FUNCTION__, mActiveModemIndex); + return mActiveModemIndex; +} + +status_t SpeechDriverFactory::SetActiveModemIndex(const modem_index_t modem_index) +{ + ALOGD("%s(), old modem index = %d, new modem index = %d", __FUNCTION__, mActiveModemIndex, modem_index); + mActiveModemIndex = modem_index; + return NO_ERROR; +} + + +status_t SpeechDriverFactory::SetActiveModemIndexByAudioMode(const audio_mode_t audio_mode) +{ + status_t return_status = NO_ERROR; + + switch (audio_mode) + { + case AUDIO_MODE_IN_CALL: + return_status = SetActiveModemIndex(MODEM_1); + break; + case AUDIO_MODE_IN_CALL_2: + return_status = SetActiveModemIndex(MODEM_2); + break; + case AUDIO_MODE_IN_CALL_EXTERNAL: + return_status = SetActiveModemIndex(MODEM_EXTERNAL); + break; + default: + ALOGE("%s() mode(%d) is neither MODE_IN_CALL nor MODE_IN_CALL_2!!", __FUNCTION__, audio_mode); + return_status = INVALID_OPERATION; + break; + } + return return_status; +} + + +} // end of namespace android + diff --git a/pool/shard007/C++/0095013_opml.cpp b/pool/shard007/C++/0095013_opml.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0163ed5abe80ec99ed30c0d234956328c0d9f477 --- /dev/null +++ b/pool/shard007/C++/0095013_opml.cpp @@ -0,0 +1,168 @@ +/* + This file is part of Akregator. + + Copyright (C) 2008 Didier Hoarau <did.hoarau@gmail.com> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + As a special exception, permission is given to link this program + with any edition of Qt, and distribute the resulting executable, + without including the source code for Qt in the source distribution. +*/ + +#include "opml.h" + +#include <KConfigGroup> + +#include <kdebug.h> + +#include <QTimer> +#include <QDomDocument> + +namespace feedsync +{ + +Opml::Opml(const KConfigGroup& configgroup, QObject* parent) + : Aggregator( parent ), + _xmlDoc( 0 ), + _xmlFile( configgroup.readEntry("Filename") ), + _loaded( false ) +{ + kDebug(); +} + +Opml::~Opml() +{ + kDebug(); + delete _xmlDoc; +} + +SubscriptionList Opml::getSubscriptionList() const +{ + kDebug(); + return _subscriptionList; +} + +void Opml::load() +{ + kDebug(); + + // If not already done load the file + if ( !_loaded ) { + + } + + // Read the XML + delete _xmlDoc; + _xmlDoc = new QDomDocument("opml"); + if (!_xmlFile.open(QIODevice::ReadOnly)) { + kDebug() << "File Error"; + delete _xmlDoc; + _xmlDoc = 0; + return; + } + if (!_xmlDoc->setContent(&_xmlFile)) { + kDebug() << "File Error"; + _xmlFile.close(); + delete _xmlDoc; + _xmlDoc = 0; + return; + } + _xmlFile.close(); + QDomNodeList nodeList = _xmlDoc->elementsByTagName("outline"); + bool firstCat = true; + QString cat; + for (int i=0;i<nodeList.count();i++) { + QDomNode node = nodeList.at(i); + if (!node.attributes().namedItem("xmlUrl").isNull()) { + _subscriptionList.add(node.attributes().namedItem("xmlUrl").nodeValue(), + node.attributes().namedItem("title").nodeValue(), + cat); + firstCat = true; + } else { + if (firstCat) { + cat = ""; + firstCat = false; + } else { + cat += '/'; + } + cat += node.attributes().namedItem("text").nodeValue(); + } + } + + // Send the signal + QTimer::singleShot( 0, this, SLOT(sendSignalLoadDone()) ); +} + +void Opml::sendSignalLoadDone() +{ + emit loadDone(); +} + +void Opml::add(const SubscriptionList & list) +{ + if(!_xmlDoc) + return; + kDebug(); + QDomNode nodeList = _xmlDoc->documentElement().firstChild().nextSibling(); + + QString m_rss; + for (int i=0;i<list.count();i++) { + m_rss = list.getRss(i); + + // Create element + QDomElement m_element = _xmlDoc->createElement("outline"); + m_element.setAttribute(QString("title"),list.getName(i)); + m_element.setAttribute(QString("type"),QString("rss")); + m_element.setAttribute(QString("text"),list.getName(i)); + m_element.setAttribute(QString("xmlUrl"),m_rss); + + // append + nodeList.appendChild(m_element); + } + + // TODO Test save + QFile file; + QTextStream out; + file.setFileName("~/out.xml"); + if (!file.open(QIODevice::WriteOnly)) + return; + out.setDevice(&file); + _xmlDoc->save(out,2); + file.close(); + + // Send signal + emit addDone(); +} + +void Opml::update(const SubscriptionList & list) +{ + Q_UNUSED(list) + kDebug(); + + // Send signal + emit updateDone(); +} + +void Opml::remove(const SubscriptionList & list) +{ + Q_UNUSED(list) + kDebug(); + + // Send signal + emit removeDone(); +} + +} diff --git a/pool/shard007/C++/0095014_locate.cc b/pool/shard007/C++/0095014_locate.cc new file mode 100644 index 0000000000000000000000000000000000000000..0b3fb954b752f2762001ea58b8b44739a7b78178 --- /dev/null +++ b/pool/shard007/C++/0095014_locate.cc @@ -0,0 +1,164 @@ +/* + * locate.cc - Locate class + * AYM 2003-03-24 + */ + +/* +This file is copyright André Majorel 2003. + +This program is free software; you can redistribute it and/or modify it under +the terms of version 2 of the GNU General Public License as published by the +Free Software Foundation. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along with +this program; if not, write to the Free Software Foundation, Inc., 59 Temple +Place, Suite 330, Boston, MA 02111-1307, USA. +*/ + + +#include "yadex.h" + +#include <sys/types.h> +#include <sys/stat.h> + +#include "locate.h" +#include "macro.h" +#include "trace.h" + +#include "../compat/compat.h" + +/* + * Locate::Locate - ctor + * + * - search_path points to a NULL-terminated array of C + * strings (char *) constituting the search path. The + * paths may contains the following macros, which will be + * expanded on the fly : + * %v the version of Yadex + * ~ $HOME + * + * - name is the basename of the file to locate. It may + * include slashes. If it's absolute, the search path + * won't be used. + * + * - backwards is the direction in which the search path is + * walked. true is front-to-back, false is back-to-front. + */ +Locate::Locate(const char *const *search_path, const char *name, bool backw) { + this->search_path = search_path; + this->name = name; + this->backwards = backw; + absolute = is_absolute (name); + rewound = true; + + rewind (); +} + + +/* + * Locate::rewind - rewind the cursor + * + * Calling this method will cause the next call to + * get_next() to return the first match, as if get_next() + * had never been called. + */ +void +Locate::rewind () { + rewound = true; + + if (backwards) { + // Advance to the end of the list + for (cursor = search_path; *cursor != NULL; cursor++) + ; + } else { + cursor = search_path; + } +} + + +/* + * Locate::get_next - return the next match + * + * Returns a pointer to the pathname of the next match, or + * a null pointer if there are no more matches left. The + * returned pointer is valid until get_next() is called + * again or the Locate object is destroyed. + */ +const char * +Locate::get_next () { + if (absolute) { + if (!rewound) // Result has exactly one element + return NULL; + rewound = false; + if (strlen(name) > sizeof pathname - 1) { + warn("%s: file name too long\n", name); + return NULL; + } + strlcpy (pathname, name, sizeof(pathname)); + return pathname; + } + + const char *home = getenv ("HOME"); + + // Walk the list + for (;;) { + // Make dirname point to the current path in the search path + const char *dirname; + + if (backwards) { + if (cursor == search_path) + break; + cursor--; + dirname = *cursor; + } else { + if (*cursor == NULL) + break; + dirname = *cursor; + cursor++; + } + + // Expand the macros in the path into the result buffer + int r = macro_expand(pathname, sizeof pathname - 1, dirname, + "%i", install_dir, + "%v", yadex_version, + "~", home, + (const char *) 0); + if (r != 0) { + trace("locate", "%s: Could not expand macro #%d", dirname, r); + continue; + } + + // Append the basename + if (strlen(pathname) > 0 && pathname[strlen (pathname)] - 1 != '/') { + if (strlen(pathname) + 2 >= sizeof pathname) { + warn("%s: file name too long, skipping\n", dirname); + continue; + } + strlcat(pathname, "/", sizeof(pathname)); + } + if (strlen(pathname) + strlen(name) + 1 >= sizeof pathname) { + warn("%s: file name too long, skipping\n", dirname); + continue; + } + strlcat(pathname, name, sizeof(pathname)); + + // Look for a file of that name. + struct stat s; + r = stat(pathname, &s); + if (r == 0 && !S_ISDIR(s.st_mode)) { + trace ("locate", "%s: %s: hit", name, pathname); + return pathname; + } else if (r == 0 && S_ISDIR(s.st_mode)) { + errno = EISDIR; + } else if (r != 0 && errno != ENOENT) { + warn ("%s: %s\n", pathname, strerror (errno)); + } + trace ("locate", "%s: %s: miss (%s)", name, pathname, strerror (errno)); + } + + return NULL; +} diff --git a/pool/shard007/C++/0095017_rtt-stream.cpp b/pool/shard007/C++/0095017_rtt-stream.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7e992fe6cad0d27dd05e5089092f6a240613af25 --- /dev/null +++ b/pool/shard007/C++/0095017_rtt-stream.cpp @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2010-2019 Belledonne Communications SARL. + * + * This file is part of Liblinphone. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ +#include "bctoolbox/defs.h" + +#include "ms2-streams.h" +#include "media-session.h" +#include "media-session-p.h" +#include "core/core.h" +#include "c-wrapper/c-wrapper.h" +#include "call/call.h" +#include "conference/participant.h" +#include "conference/params/media-session-params-p.h" + +#include "linphone/core.h" + +using namespace ::std; + +LINPHONE_BEGIN_NAMESPACE + +/* + * MS2RTTStream implementation. + */ + +MS2RTTStream::MS2RTTStream(StreamsGroup &sg, const OfferAnswerContext ¶ms) : MS2Stream(sg, params){ + string bindIp = getBindIp(); + mStream = text_stream_new2(getCCore()->factory, bindIp.empty() ? nullptr : bindIp.c_str(), mPortConfig.rtpPort, mPortConfig.rtcpPort); + initializeSessions(&mStream->ms); +} + +void MS2RTTStream::realTimeTextCharacterReceived (MSFilter *f, unsigned int id, void *arg) { + CallSessionListener *listener = getMediaSessionPrivate().getCallSessionListener(); + + if (id == MS_RTT_4103_RECEIVED_CHAR) { + RealtimeTextReceivedCharacter *data = static_cast<RealtimeTextReceivedCharacter *>(arg); + if (listener) + listener->onRealTimeTextCharacterReceived(getMediaSession().getSharedFromThis(), data); + } +} + +void MS2RTTStream::sRealTimeTextCharacterReceived (void *userData, MSFilter *f, unsigned int id, void *arg) { + MS2RTTStream *zis = static_cast<MS2RTTStream *>(userData); + zis->realTimeTextCharacterReceived(f, id, arg); +} + +bool MS2RTTStream::prepare(){ + MS2Stream::prepare(); + text_stream_prepare_text(mStream); + return false; +} + +void MS2RTTStream::finishPrepare(){ + MS2Stream::finishPrepare(); + text_stream_unprepare_text(mStream); +} + +void MS2RTTStream::render(const OfferAnswerContext ¶ms, CallSession::State targetState){ + const auto & tstream = params.getResultStreamDescription(); + bool basicChangesHandled = handleBasicChanges(params, targetState); + + if (basicChangesHandled) { + if (getState() == Running) MS2Stream::render(params, targetState); + return; + } + + MS2Stream::render(params, targetState); + RtpAddressInfo dest; + getRtpDestination(params, &dest); + int usedPt = -1; + RtpProfile * textProfile = makeProfile(params.resultMediaDescription, tstream, &usedPt); + if (usedPt == -1){ + lError() << "No payload type was accepted for text stream."; + stop(); + return; + } + getMediaSessionPrivate().getCurrentParams()->getPrivate()->setUsedRealtimeTextCodec(rtp_profile_get_payload(textProfile, usedPt)); + getMediaSessionPrivate().getCurrentParams()->enableRealtimeText(true); + + unsigned int interval = getMediaSessionPrivate().getParams()->realtimeTextKeepaliveInterval(); + getMediaSessionPrivate().getCurrentParams()->setRealtimeTextKeepaliveInterval(interval); + + text_stream_start(mStream, textProfile, dest.rtpAddr.c_str(), dest.rtpPort, dest.rtcpAddr.c_str(), dest.rtcpPort, usedPt); + ms_filter_add_notify_callback(mStream->rttsink, sRealTimeTextCharacterReceived, this, false); + ms_filter_call_method(mStream->rttsource, MS_RTT_4103_SOURCE_SET_KEEP_ALIVE_INTERVAL, &interval); + mStartCount++; +} + +void MS2RTTStream::stop(){ + MS2Stream::stop(); + text_stream_stop(mStream); + /* In mediastreamer2, stop actually stops and destroys. We immediately need to recreate the stream object for later use, keeping the + * sessions (for RTP, SRTP, ZRTP etc) that were setup at the beginning. */ + mStream = text_stream_new_with_sessions(getCCore()->factory, &mSessions); +} + +void MS2RTTStream::finish(){ + if (mStream){ + text_stream_stop(mStream); + mStream = nullptr; + } +} + +MS2RTTStream::~MS2RTTStream(){ + finish(); +} + +MediaStream *MS2RTTStream::getMediaStream()const{ + return &mStream->ms; +} + +void MS2RTTStream::handleEvent(const OrtpEvent *ev){ +} + +void MS2RTTStream::initZrtp() { + +} + +void MS2RTTStream::startZrtp() { + +} + +LINPHONE_END_NAMESPACE diff --git a/pool/shard007/C++/0095018_ComportementAssassinMachine.cpp b/pool/shard007/C++/0095018_ComportementAssassinMachine.cpp new file mode 100644 index 0000000000000000000000000000000000000000..056d50efd8c560d8c0890324b24aeaed5bdc8efc --- /dev/null +++ b/pool/shard007/C++/0095018_ComportementAssassinMachine.cpp @@ -0,0 +1,56 @@ +/*! +* \file ComportementAssassinMachine.cpp +* \brief Fichier contenant l'implémentation de la classe ComportementAssassinMachine +* \author François Hallereau +* \author Sébastien Vallée +* \date 12.2014 +*/ + +//-------------------------------------------------- +/*! +* \brief Constructeur de la classe +*/ +ComportementAssassinMachine::ComportementAssassinMachine():ComportementMachine(){} + +//-------------------------------------------------- +/*! +* \brief Destructeur de la classe +*/ +ComportementAssassinMachine::~ComportementAssassinMachine(){} + + +//-------------------------------------------------- +/*! +* \brief méthode de jeu pour l'assassin machine +* \param partie la partie +* \param joueur le joueur +*/ +void ComportementAssassinMachine::jouer(Partie *p, Joueur *j){ + choisirGainTour(j); + choixAssassinat(p,j); + choisirConstruction(j); +} + + +//-------------------------------------------------- +/*! +* \brief méthode qui effectue l'assassinat +* \param partie la partie +* \param joueur le joueur +*/ +void ComportementAssassinMachine::choixAssassinat(Partie * p, Joueur * j){ + vector<Personnage*> tmp = p->recupererListePersonnages(); + vector<int> exclus; + bool trouve = false; + int i; + + while(!trouve && exclus.size() < tmp.size()){ + i = Aleatoire::tirerEntierAvecExclusion(exclus,0,tmp.size()-1); + if(tmp.at(i) != p->retrouverP(j)){ + trouve = true; + Assassin::assassiner(p,tmp.at(i)); + } + + } + +} diff --git a/pool/shard007/C++/0095019_system_error.cc b/pool/shard007/C++/0095019_system_error.cc new file mode 100644 index 0000000000000000000000000000000000000000..41726e483ac1e2473a58c79d532092e539fe2fb1 --- /dev/null +++ b/pool/shard007/C++/0095019_system_error.cc @@ -0,0 +1,122 @@ +// <system_error> implementation file + +// Copyright (C) 2007-2016 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// Under Section 7 of GPL version 3, you are granted additional +// permissions described in the GCC Runtime Library Exception, version +// 3.1, as published by the Free Software Foundation. + +// You should have received a copy of the GNU General Public License and +// a copy of the GCC Runtime Library Exception along with this program; +// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see +// <http://www.gnu.org/licenses/>. + + +#define _GLIBCXX_USE_CXX11_ABI 1 +#define __sso_string __sso_stringxxx +#include <cstring> +#include <system_error> +#include <bits/functexcept.h> +#include <limits> +#undef __sso_string + +namespace +{ + using std::string; + + struct generic_error_category : public std::error_category + { + virtual const char* + name() const noexcept + { return "generic"; } + + _GLIBCXX_DEFAULT_ABI_TAG + virtual string + message(int i) const + { + // XXX locale issues: how does one get or set loc. + // _GLIBCXX_HAVE_STRERROR_L, strerror_l(i, cloc) + return string(strerror(i)); + } + }; + + struct system_error_category : public std::error_category + { + virtual const char* + name() const noexcept + { return "system"; } + + _GLIBCXX_DEFAULT_ABI_TAG + virtual string + message(int i) const + { + // XXX locale issues: how does one get or set loc. + // _GLIBCXX_HAVE_STRERROR_L, strerror_l(i, cloc) + return string(strerror(i)); + } + }; + + const generic_error_category generic_category_instance{}; + const system_error_category system_category_instance{}; +} + +namespace std _GLIBCXX_VISIBILITY(default) +{ +_GLIBCXX_BEGIN_NAMESPACE_VERSION + + void + __throw_system_error(int __i __attribute__((unused))) + { + _GLIBCXX_THROW_OR_ABORT(system_error(error_code(__i, generic_category()))); + } + + error_category::~error_category() noexcept = default; + + const error_category& + _V2::system_category() noexcept { return system_category_instance; } + + const error_category& + _V2::generic_category() noexcept { return generic_category_instance; } + + system_error::~system_error() noexcept = default; + + error_condition + error_category::default_error_condition(int __i) const noexcept + { return error_condition(__i, *this); } + + bool + error_category::equivalent(int __i, + const error_condition& __cond) const noexcept + { return default_error_condition(__i) == __cond; } + + bool + error_category::equivalent(const error_code& __code, int __i) const noexcept + { return *this == __code.category() && __code.value() == __i; } + + error_condition + error_code::default_error_condition() const noexcept + { return category().default_error_condition(value()); } + +#if _GLIBCXX_USE_CXX11_ABI + // Return error_category::message() as a COW string + __cow_string + error_category::_M_message(int i) const + { + string msg = this->message(i); + return {msg.c_str(), msg.length()}; + } +#endif + +_GLIBCXX_END_NAMESPACE_VERSION +} // namespace diff --git a/pool/shard007/C++/0095021_com_pushd_ColorPal.cpp b/pool/shard007/C++/0095021_com_pushd_ColorPal.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1a5b6682141983d1f9d90e5712594793958341e --- /dev/null +++ b/pool/shard007/C++/0095021_com_pushd_ColorPal.cpp @@ -0,0 +1,208 @@ +/** + * Copyright 2016 pushd inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "lcms2.h" + +#include <stdlib.h> +#include <jni.h> +#include <time.h> +#include <android/log.h> +#include <android/bitmap.h> +#include <endian.h> +#include <stdarg.h> +#include <math.h> + +#define LOG_TAG "ColorPal.CorrectorJNI" +#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) +#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) +#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) + +#ifdef __cplusplus +extern "C" { +#endif + +// AssertionErrors are fancy, ThrowNew won't work since it has an Object ctor, not a String ctor +void throwAssertionError(JNIEnv* env, const char *msgFormat, ...) { + char msg[128]; + va_list args; + va_start(args, msgFormat); + vsprintf(msg, msgFormat, args); + va_end(args); + + jclass cls = env->FindClass("java/lang/AssertionError"); + jmethodID constructor = env->GetMethodID(cls, "<init>", "(Ljava/lang/Object;)V"); + jstring jmsg = env->NewStringUTF(msg); + jthrowable throwable = (jthrowable)env->NewObject(cls, constructor, (jobject)jmsg); + env->Throw(throwable); +} + +JNIEXPORT jintArray JNICALL Java_com_pushd_colorpal_ColorCorrector_create3DLUT(JNIEnv *env, jobject obj, jlong longHandle) { + static const int DIM = 64; // 8MB LUT + + if (!longHandle) { + throwAssertionError(env, "No tansform handle available"); + return NULL; + } + + cmsHTRANSFORM hTransform = (cmsHTRANSFORM)longHandle; + + jintArray ret = env->NewIntArray(DIM * DIM * DIM); + jint *lut = env->GetIntArrayElements(ret, NULL); + + for (uint16_t r = 0; r < DIM; ++r) { + for (uint16_t g = 0; g < DIM; ++g) { + for (uint16_t b = 0; b < DIM; ++b) { + int r_scaled = floor((double) r / (DIM - 1) * 255.0 + 0.5); + int b_scaled = floor((double) b / (DIM - 1) * 255.0 + 0.5); + int g_scaled = floor((double) g / (DIM - 1) * 255.0 + 0.5); + + // little-endian RGBA -> ABGR + uint32_t pixel = (0xFF << 24) | (b_scaled << 16) | (g_scaled << 8) | (r_scaled << 0); + uint32_t mapped = 0; + cmsDoTransform(hTransform, &pixel, &mapped, 1); + + // expects [b][g][r] "flat" index + lut[b*DIM*DIM + g*DIM + r] = mapped; + //LOGD("pixel: 0x%08x, transformed: 0x%08x", pixel, mapped); + } + } + } + + env->ReleaseIntArrayElements(ret, lut, 0); + return ret; +} + +JNIEXPORT jlong JNICALL Java_com_pushd_colorpal_ColorCorrector_createTransform(JNIEnv *env, jobject obj, jstring javaString) { + + cmsHPROFILE hInputProfile = cmsCreate_sRGBProfile(); + + if (!hInputProfile) { + throwAssertionError(env, "Could not open SRGB Profile"); + return 0; + } + + // this will give us java's "modified" UTF-8 but for icc profile paths this shouldn't matter + const char *iccPath = env->GetStringUTFChars(javaString, JNI_FALSE); + + cmsHPROFILE hOutputProfile = cmsOpenProfileFromFile(iccPath, "r"); + + if (!hOutputProfile) { + throwAssertionError(env, "Could not load ICC Profile at %s", iccPath); + env->ReleaseStringUTFChars(javaString, iccPath); + return 0; + } + + // create the transform for concurrent use (cmsFLAGS_NOCACHE) + // http://littlecms2.blogspot.com/2010/12/multithreading-question.html + cmsHTRANSFORM hTransform = cmsCreateTransform(hInputProfile, + TYPE_RGBA_8, + hOutputProfile, + TYPE_RGBA_8, + INTENT_PERCEPTUAL, + cmsFLAGS_NOCACHE|cmsFLAGS_NOOPTIMIZE); + + if (!hTransform) { + throwAssertionError(env, "Could not create transform"); + env->ReleaseStringUTFChars(javaString, iccPath); + return 0; + } + + // once the transform is created we can free the profiles + cmsCloseProfile(hInputProfile); + cmsCloseProfile(hOutputProfile); + hInputProfile = hOutputProfile = NULL; + + env->ReleaseStringUTFChars(javaString, iccPath); + + return (jlong)(hTransform); +} + +JNIEXPORT void JNICALL Java_com_pushd_colorpal_ColorCorrector_disposeTransform(JNIEnv *env, jobject obj, jlong longHandle) { + if (!longHandle) { + env->ThrowNew(env->FindClass("java/lang/IllegalArgumentException"), "No tansform handle to dispose"); + return; + } + + cmsHTRANSFORM hTransform = (cmsHTRANSFORM)longHandle; + cmsDeleteTransform(hTransform); +} + + +JNIEXPORT void JNICALL Java_com_pushd_colorpal_ColorCorrector_correctBitmap(JNIEnv *env, jobject /*obj*/, jlong longHandle, jobject bitmap) { + AndroidBitmapInfo info; + void *pixels = NULL; + int ret = 0; + char excmsg[128]; + + if (!longHandle) { + env->ThrowNew(env->FindClass("java/lang/IllegalArgumentException"), "No tansform handle provided"); + return; + } + + if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) { + throwAssertionError(env, "AndroidBitmap_getInfo() failed ! error=%d", ret); + return; + } + + if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) { + throwAssertionError(env, "Bitmap format is not RGBA_8888 !"); + return; + } + + if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) { + throwAssertionError(env, "AndroidBitmap_lockPixels() failed ! error=%d", ret); + return; + } + + // do the thing + cmsHTRANSFORM hTransform = (cmsHTRANSFORM)longHandle; + cmsDoTransform(hTransform, pixels, pixels, info.width * info.height); + + if ((ret = AndroidBitmap_unlockPixels(env, bitmap)) < 0) { + throwAssertionError(env, "AndroidBitmap_unlockPixels() failed ! error=%d", ret); + return; + } + +} + +JNIEXPORT jint JNICALL Java_com_pushd_colorpal_ColorCorrector_correctedColor(JNIEnv */*env*/, jobject /*obj*/, jlong longHandle, jint argb) { + + // ARGB -> ABGR + uint8_t a = (argb >> 24) & 0xFF; + uint8_t r = (argb >> 16) & 0xFF; + uint8_t g = (argb >> 8) & 0xFF; + uint8_t b = argb & 0xFF; + + // do not map alpha channel, so replace with 0xFF + uint32_t pixel = 0xFF << 24 | b << 16 | g << 8 | r; + + uint32_t mapped = 0; + cmsHTRANSFORM hTransform = (cmsHTRANSFORM)longHandle; + cmsDoTransform(hTransform, &pixel, &mapped, 1); + + // ABGR -> ARGB + b = (mapped >> 16) & 0xFF; + g = (mapped >> 8) & 0xFF; + r = mapped & 0xFF; + + // use original alpha + return a << 24 | r << 16 | g << 8 | b; +} + +#ifdef __cplusplus +} +#endif + diff --git a/pool/shard007/C++/0095022_divisors_of_factorial.cc b/pool/shard007/C++/0095022_divisors_of_factorial.cc new file mode 100644 index 0000000000000000000000000000000000000000..79c7ccd3783783857ffd565c2f4c305454617638 --- /dev/null +++ b/pool/shard007/C++/0095022_divisors_of_factorial.cc @@ -0,0 +1,72 @@ +// Jakub Staroń, 2016-2017 +// +// Solution to SPOJ problem, see +// http://www.spoj.com/problems/DIVFACT/ + +#include "headers.h" +#include "numeric/number_theory.h" +#include "numeric/prime_field.h" +#include "io.h" + +using namespace pcl; + +constexpr uint32 kPrime = 1000 * 1000 * 1000 + 7; +constexpr uint32 kMaxN = 50 * 1000; + +auto primes = numeric::PrimeNumbers(kMaxN + 1); +using result_type = numeric::prime_field<kPrime>; + + +/** + * Returns power of given prime in factorization of N!. + * + * Note that p must be prime number. + * Computational complexity is O(log_p(N)). + */ +uint32 PowerInFactorial(uint32 p, uint64 N) { + uint32 result = 0; + for (uint64 q = p; q <= N; q *= p) + result += N / q; + return result; +} + + +class Application { +public: + Application() { } + + uint64 Result(uint32 N) { + result_type result = 1; + for (uint32 p: primes) { + if (p > N) + break; + result *= (PowerInFactorial(p, N) + 1); + } + + return result.value(); + } + + void Run() { + auto input = ReadSequence<uint32>(std::cin, T); + iterate(input, [this](uint32 N) { + print("%0", Result(N)); + }); + } + + void LoadData() { + read(std::cin, T); + } + +private: + uint32 T; +}; + +int main(int argc, const char* argv[]) { + std::ios::sync_with_stdio(false); + std::cin.tie(nullptr); + std::cout.tie(nullptr); + Application application; + application.LoadData(); + application.Run(); + return 0; +} diff --git a/pool/shard007/C++/0095025_main.cpp b/pool/shard007/C++/0095025_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..13319fb8a9ad6f000a725f474150bafc912ae729 --- /dev/null +++ b/pool/shard007/C++/0095025_main.cpp @@ -0,0 +1,31 @@ +#include <iostream> +#include <string> + +using namespace std; + +int main(){ + + string input; + + while(cin >> input){ + string num_str = input.substr(0, 2); + int num = stoi(num_str); + int rev_num = num - 18; + if(rev_num <= 0) rev_num += 36; + if(rev_num < 10) + cout << '0' << rev_num; + else + cout << rev_num; + if(input.size() == 3){ + if(input[2] == 'R') + cout << 'L'; + else if(input[2] == 'L') + cout << 'R'; + else + cout << 'C'; + } + cout << '\n'; + } + + return 0; +} diff --git a/pool/shard007/C++/0095027_logconsole.cpp b/pool/shard007/C++/0095027_logconsole.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3fec00bc78fbce42da86b744c860943402482162 --- /dev/null +++ b/pool/shard007/C++/0095027_logconsole.cpp @@ -0,0 +1,122 @@ +// Copyright 2016 Chirstopher Torres (Raven), L3nn0x +// +// 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. + +// #undef UNICODE +// +#include <sstream> +#include "logconsole.h" + +#ifdef _WIN32 + #include <spdlog/sinks/msvc_sink.h> +#else + #include <spdlog/sinks/syslog_sink.h> + //#include <spdlog/sinks/systemd_sink.h> +#endif + +namespace Core { + +spdlog::level::level_enum CLog::level_ = spdlog::level::info; + +void CLog::SetLevel(spdlog::level::level_enum _level) { + level_ = _level; + + std::ostringstream format; + format << "[%H:%M:%S.%e.%f %z] [%^%L%$]"; + + if (level_ <= spdlog::level::debug) format << " [thread %t]"; + format << " [%n]" << " %v "; + spdlog::set_pattern(format.str()); +} + +std::weak_ptr<spdlog::logger> CLog::GetLogger( + log_type _type) { + std::weak_ptr<spdlog::logger> logger; + try + { + switch (_type) { + case log_type::NETWORK: + logger = spdlog::get("net"); + break; + + case log_type::DATABASE: + logger = spdlog::get("db"); + break; + + case log_type::GENERAL: + default: + logger = spdlog::get("server"); + break; + } + + if (logger.expired()) { + std::ostringstream format; + format << "[%H:%M:%S.%e.%f %z] [%^%L%$]"; + + if (level_ <= spdlog::level::debug) format << " [thread %t]"; + format << " [%n]" << " %v "; + + std::string path, name; + + switch (_type) { + case log_type::NETWORK: { + path = "logs/network"; + name = "net"; + break; + } + case log_type::DATABASE: { + path = "logs/database"; + name = "db"; + break; + } + case log_type::GENERAL: + default: { + path = "logs/server"; + name = "server"; + break; + } + } +#ifndef DISABLE_ASYNC_LOGGING + if(spdlog::thread_pool() == nullptr) + spdlog::init_thread_pool(8192, 1); +#endif + std::vector<spdlog::sink_ptr> sinks; + + auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>(); + sinks.push_back(console_sink); +#ifdef _WIN32 + sinks.push_back(std::make_shared<spdlog::sinks::msvc_sink_mt>()); +#else + #ifdef SPDLOG_ENABLE_SYSLOG + auto syslog_sink = std::make_shared<spdlog::sinks::syslog_sink_mt>(name.c_str()); + syslog_sink->set_level(spdlog::level::warn); + sinks.push_back(syslog_sink); + #endif +#endif +#ifndef DISABLE_ASYNC_LOGGING + auto combined_logger = std::make_shared<spdlog::async_logger>(name.c_str(), sinks.begin(), sinks.end(), spdlog::thread_pool(), spdlog::async_overflow_policy::block); +#else + auto combined_logger = std::make_shared<spdlog::logger>(name.c_str(), sinks.begin(), sinks.end()); +#endif + combined_logger->set_level(level_); + combined_logger->set_pattern(format.str()); + spdlog::register_logger(combined_logger); + + return combined_logger; + } + } catch (const spdlog::spdlog_ex& ex) { + std::cout << "Log failed: " << ex.what() << std::endl; + } + return logger; +} +} diff --git a/pool/shard007/C++/0095030_test_pipe_info.cpp b/pool/shard007/C++/0095030_test_pipe_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e7b486dbe9f69126a70d112bd80b3bb8dbd6baa9 --- /dev/null +++ b/pool/shard007/C++/0095030_test_pipe_info.cpp @@ -0,0 +1,88 @@ +// +// Copyright (c) 2017 The Khronos Group Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#include "procs.h" +#include "harness/parseParameters.h" + +const char* pipe_kernel_code = { + "__kernel void pipe_kernel(__write_only pipe int out_pipe)\n" + "{}\n" }; + +int test_pipe_info( cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements ) +{ + clMemWrapper pipe; + cl_int err; + cl_uint pipe_width = 512; + cl_uint pipe_depth = 1024; + cl_uint returnVal; + clProgramWrapper program; + clKernelWrapper kernel; + + pipe = clCreatePipe(context, CL_MEM_HOST_NO_ACCESS, pipe_width, pipe_depth, + NULL, &err); + test_error(err, "clCreatePipe failed."); + + err = clGetPipeInfo(pipe, CL_PIPE_PACKET_SIZE, sizeof(pipe_width), + (void *)&returnVal, NULL); + test_error(err, "clGetPipeInfo failed."); + + if (pipe_width != returnVal) + { + test_fail("Error in clGetPipeInfo() check of pipe packet size\n"); + } + else + { + log_info( " CL_PIPE_PACKET_SIZE passed.\n" ); + } + + err = clGetPipeInfo(pipe, CL_PIPE_MAX_PACKETS, sizeof(pipe_depth), (void *)&returnVal, NULL); + test_error(err, "clGetPipeInfo failed."); + + if(pipe_depth != returnVal) + { + test_fail("Error in clGetPipeInfo() check of pipe max packets\n"); + } + else + { + log_info( " CL_PIPE_MAX_PACKETS passed.\n" ); + } + + err = create_single_kernel_helper_with_build_options( + context, &program, &kernel, 1, &pipe_kernel_code, "pipe_kernel", + "-cl-std=CL2.0 -cl-kernel-arg-info"); + test_error_fail(err, "Error creating program"); + + cl_kernel_arg_type_qualifier arg_type_qualifier = 0; + err = clGetKernelArgInfo(kernel, 0, CL_KERNEL_ARG_TYPE_QUALIFIER, + sizeof(arg_type_qualifier), &arg_type_qualifier, + NULL); + if (gCompilationMode == kOnline) + { + test_error_fail(err, "clGetKernelArgInfo failed"); + if (arg_type_qualifier != CL_KERNEL_ARG_TYPE_PIPE) + { + test_fail("ERROR: Incorrect type qualifier: %i\n", + arg_type_qualifier); + } + } + else + { + test_failure_error_ret(err, CL_KERNEL_ARG_INFO_NOT_AVAILABLE, + "clGetKernelArgInfo error not as expected", + TEST_FAIL); + } + + return TEST_PASS; +} diff --git a/pool/shard007/C++/0095039_audio_device_listener_win_unittest.cc b/pool/shard007/C++/0095039_audio_device_listener_win_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..4b78d934f10ca1aa64c35470281b6769a6bcae26 --- /dev/null +++ b/pool/shard007/C++/0095039_audio_device_listener_win_unittest.cc @@ -0,0 +1,109 @@ +// Copyright (c) 2012 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 <string> + +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/memory/scoped_ptr.h" +#include "base/strings/utf_string_conversions.h" +#include "base/test/simple_test_tick_clock.h" +#include "base/win/scoped_com_initializer.h" +#include "media/audio/audio_manager.h" +#include "media/audio/audio_unittest_util.h" +#include "media/audio/win/audio_device_listener_win.h" +#include "media/audio/win/core_audio_util_win.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using base::win::ScopedCOMInitializer; + +namespace media { + +static const char kFirstTestDevice[] = "test_device_0"; +static const char kSecondTestDevice[] = "test_device_1"; + +class AudioDeviceListenerWinTest : public testing::Test { + public: + AudioDeviceListenerWinTest() { + DCHECK(com_init_.succeeded()); + } + + virtual void SetUp() { + if (!CoreAudioUtil::IsSupported()) + return; + + output_device_listener_.reset(new AudioDeviceListenerWin(base::Bind( + &AudioDeviceListenerWinTest::OnDeviceChange, base::Unretained(this)))); + + tick_clock_ = new base::SimpleTestTickClock(); + tick_clock_->Advance(base::TimeDelta::FromSeconds(12345)); + output_device_listener_->tick_clock_.reset(tick_clock_); + } + + void AdvanceLastDeviceChangeTime() { + tick_clock_->Advance(base::TimeDelta::FromMilliseconds( + AudioDeviceListenerWin::kDeviceChangeLimitMs + 1)); + } + + // Simulate a device change where no output devices are available. + bool SimulateNullDefaultOutputDeviceChange() { + return output_device_listener_->OnDefaultDeviceChanged( + static_cast<EDataFlow>(eConsole), static_cast<ERole>(eRender), + NULL) == S_OK; + } + + bool SimulateDefaultOutputDeviceChange(const char* new_device_id) { + return output_device_listener_->OnDefaultDeviceChanged( + static_cast<EDataFlow>(eConsole), static_cast<ERole>(eRender), + base::ASCIIToUTF16(new_device_id).c_str()) == S_OK; + } + + + MOCK_METHOD0(OnDeviceChange, void()); + + private: + ScopedCOMInitializer com_init_; + scoped_ptr<AudioDeviceListenerWin> output_device_listener_; + base::SimpleTestTickClock* tick_clock_; + + DISALLOW_COPY_AND_ASSIGN(AudioDeviceListenerWinTest); +}; + +// Simulate a device change events and ensure we get the right callbacks. +TEST_F(AudioDeviceListenerWinTest, OutputDeviceChange) { + ABORT_AUDIO_TEST_IF_NOT(CoreAudioUtil::IsSupported()); + + EXPECT_CALL(*this, OnDeviceChange()).Times(1); + ASSERT_TRUE(SimulateDefaultOutputDeviceChange(kFirstTestDevice)); + + testing::Mock::VerifyAndClear(this); + AdvanceLastDeviceChangeTime(); + EXPECT_CALL(*this, OnDeviceChange()).Times(1); + ASSERT_TRUE(SimulateDefaultOutputDeviceChange(kSecondTestDevice)); + + // The second device event should be ignored since it occurs too soon. + ASSERT_TRUE(SimulateDefaultOutputDeviceChange(kSecondTestDevice)); +} + +// Ensure that null output device changes don't crash. Simulates the situation +// where we have no output devices. +TEST_F(AudioDeviceListenerWinTest, NullOutputDeviceChange) { + ABORT_AUDIO_TEST_IF_NOT(CoreAudioUtil::IsSupported()); + + EXPECT_CALL(*this, OnDeviceChange()).Times(1); + ASSERT_TRUE(SimulateNullDefaultOutputDeviceChange()); + + testing::Mock::VerifyAndClear(this); + AdvanceLastDeviceChangeTime(); + EXPECT_CALL(*this, OnDeviceChange()).Times(1); + ASSERT_TRUE(SimulateDefaultOutputDeviceChange(kFirstTestDevice)); + + testing::Mock::VerifyAndClear(this); + AdvanceLastDeviceChangeTime(); + EXPECT_CALL(*this, OnDeviceChange()).Times(1); + ASSERT_TRUE(SimulateNullDefaultOutputDeviceChange()); +} + +} // namespace media diff --git a/pool/shard007/C++/0095040_CWE762_Mismatched_Memory_Management_Routines__delete_array_long_realloc_17.cpp b/pool/shard007/C++/0095040_CWE762_Mismatched_Memory_Management_Routines__delete_array_long_realloc_17.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d7b29b3a3b51aca260def5692330e328912a8ab --- /dev/null +++ b/pool/shard007/C++/0095040_CWE762_Mismatched_Memory_Management_Routines__delete_array_long_realloc_17.cpp @@ -0,0 +1,124 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_long_realloc_17.cpp +Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml +Template File: sources-sinks-17.tmpl.cpp +*/ +/* + * @description + * CWE: 762 Mismatched Memory Management Routines + * BadSource: realloc Allocate data using realloc() + * GoodSource: Allocate data using new [] + * Sinks: + * GoodSink: Deallocate data using free() + * BadSink : Deallocate data using delete [] + * Flow Variant: 17 Control flow: for loops + * */ + +#include "std_testcase.h" + +namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_long_realloc_17 +{ + +#ifndef OMITBAD + +void bad() +{ + int i,j; + long * data; + /* Initialize data*/ + data = NULL; + for(i = 0; i < 1; i++) + { + data = NULL; + /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ + data = (long *)realloc(data, 100*sizeof(long)); + } + for(j = 0; j < 1; j++) + { + /* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may + * require a call to free() to deallocate the memory */ + delete [] data; + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodB2G() - use badsource and goodsink in the for statements */ +static void goodB2G() +{ + int i,k; + long * data; + /* Initialize data*/ + data = NULL; + for(i = 0; i < 1; i++) + { + data = NULL; + /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ + data = (long *)realloc(data, 100*sizeof(long)); + } + for(k = 0; k < 1; k++) + { + /* FIX: Free memory using free() */ + free(data); + } +} + +/* goodG2B() - use goodsource and badsink in the for statements */ +static void goodG2B() +{ + int h,j; + long * data; + /* Initialize data*/ + data = NULL; + for(h = 0; h < 1; h++) + { + /* FIX: Allocate memory using new [] */ + data = new long[100]; + } + for(j = 0; j < 1; j++) + { + /* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may + * require a call to free() to deallocate the memory */ + delete [] data; + } +} + +void good() +{ + goodB2G(); + goodG2B(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +using namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_long_realloc_17; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard007/C++/0095047_discord.cpp b/pool/shard007/C++/0095047_discord.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8bc629a097660f325088c2828e75b4e767a04b6e --- /dev/null +++ b/pool/shard007/C++/0095047_discord.cpp @@ -0,0 +1,82 @@ +#include "discord.h" +#include "playerInfo.h" +#include "gameGlobalInfo.h" +#include "spaceObjects/playerSpaceship.h" +#include <discord_game_sdk.h> + +static IDiscordCore* core; +static IDiscordActivityManager* activityManager; +static IDiscordCoreEvents events; + +static DiscordActivity previousActivity; + +DiscordRichPresence::DiscordRichPresence() +{ + DiscordCreateParams params; + params.client_id = 697525001603252304; + params.flags = DiscordCreateFlags_NoRequireDiscord; + params.events = &events; + params.event_data = nullptr; + + if (DiscordCreate(DISCORD_VERSION, ¶ms, &core) != DiscordResult_Ok) + { + LOG(WARNING) << "Discord not installed or not running. Not using discord rich presence"; + return; + } + + activityManager = core->get_activity_manager(core); +} + +void DiscordRichPresence::update(float delta) +{ + if (!core) + return; + + core->run_callbacks(core); + + if (updateDelay >= 0.0f) + updateDelay -= delta; + if (updateDelay >= 0.0f) + return; + + DiscordActivity activity; + memset(&activity, 0, sizeof(activity)); + strcpy(activity.assets.large_image, "logo"); + + if (my_spaceship && my_player_info) + { + auto name = my_spaceship->getCallSign() + " [" + my_spaceship->getTypeName() + "]"; + strncpy(activity.details, name.c_str(), sizeof(activity.details)); + + for(int idx=0; idx<max_crew_positions; idx++) + { + if (my_player_info->crew_position[idx]) + { + strncpy(activity.state, getCrewPositionName(ECrewPosition(idx)).c_str(), sizeof(activity.state)); + if (idx == helmsOfficer) + strcpy(activity.assets.small_image, "helms_white"); + if (idx == weaponsOfficer) + strcpy(activity.assets.small_image, "weapons_white"); + if (idx == engineering) + strcpy(activity.assets.small_image, "engineering_white"); + if (idx == scienceOfficer) + strcpy(activity.assets.small_image, "science_white"); + if (idx == relayOfficer) + strcpy(activity.assets.small_image, "relay_white"); + break; + } + } + if (my_player_info->isOnlyMainScreen()) + { + strncpy(activity.state, "Captain", sizeof(activity.state)); + strcpy(activity.assets.small_image, "captain_white"); + } + } + + if (memcmp(&activity, &previousActivity, sizeof(activity)) != 0) + { + activityManager->update_activity(activityManager, &activity, nullptr, nullptr); + previousActivity = activity; + updateDelay = 4.0; + } +} diff --git a/pool/shard007/C++/0095048_op_conditional.cpp b/pool/shard007/C++/0095048_op_conditional.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2991fcf6cb6e61de03ff941e4ff0fa8ac540a1e0 --- /dev/null +++ b/pool/shard007/C++/0095048_op_conditional.cpp @@ -0,0 +1,56 @@ +#include "../types.hpp" +#include "../ultra.hpp" +#include "../config.hpp" +#include "../request.hpp" +#include "../response_text.hpp" +#include "../utils.hpp" + +#include "base.hpp" +#include "op_conditional.hpp" + +void +UltraRemapOpConditional::process(sgxString &resultPattern, const sgxString &source) const { + // NOP - all processing is done in the evaluator +} + +bool +UltraRemapOpConditional::evaluate(sgxString &result, const UltraLine *pLine, const UltraRequest *pRequest) const { + bool rt = true; + + // Strip the op.==: bit + size_t colonPosition = pLine->m_szLine.find_first_of(':'); + sgxString childrenString(pLine->m_szLine.substr(colonPosition + 1)); + + + // Then process all the children nodes + std::vector<UltraLine *>::const_iterator cit = pLine->m_Children.begin(); + for(;cit != pLine->m_Children.end();++cit) { + rt &= (*cit)->m_pRemap->evaluate(childrenString, *cit, pRequest); + } + + // Then remap the completed string, if appropriate + + std::vector<sgxString> argList; + int numArgs = ::splitString(argList, childrenString, ' '); + + switch(numArgs) { + case 2: // if-then + if (argList[0] == "1") { + result += argList[1]; + } + break; + case 3: // if-then-else + if (argList[0] == "1") { + result += argList[1]; + } else { + result += argList[2]; + } + break; + default: + log(LOG_WARNING, "Only %d arguments in a conditional", numArgs); + } + + + return rt; + +} diff --git a/pool/shard007/C++/0095050_CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_72a.cpp b/pool/shard007/C++/0095050_CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_72a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7547a6d283fc8bab5934b40d7c0bda74ed38714d --- /dev/null +++ b/pool/shard007/C++/0095050_CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_72a.cpp @@ -0,0 +1,145 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_72a.cpp +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-72a.tmpl.cpp +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: console Read input from the console + * GoodSource: Fixed string + * Sinks: w32_execvp + * BadSink : execute command with wexecvp + * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files + * + * */ + +#include "std_testcase.h" +#include <vector> + +#include <wchar.h> + +#ifdef _WIN32 +#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT L"cmd.exe" +#define COMMAND_ARG1 L"/c" +#define COMMAND_ARG2 L"dir" +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include <unistd.h> +#define COMMAND_INT_PATH L"/bin/sh" +#define COMMAND_INT L"sh" +#define COMMAND_ARG1 L"ls" +#define COMMAND_ARG2 L"-la" +#define COMMAND_ARG3 data +#endif + +using namespace std; + +namespace CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_72 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink(vector<wchar_t *> dataVector); + +void bad() +{ + wchar_t * data; + vector<wchar_t *> dataVector; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + { + /* Read input from the console */ + size_t dataLen = wcslen(data); + /* if there is room in data, read into it from the console */ + if (100-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgetws() */ + dataLen = wcslen(data); + if (dataLen > 0 && data[dataLen-1] == L'\n') + { + data[dataLen-1] = L'\0'; + } + } + else + { + printLine("fgetws() failed"); + /* Restore NUL terminator if fgetws fails */ + data[dataLen] = L'\0'; + } + } + } + /* Put data in a vector */ + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + badSink(dataVector); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good function declarations */ + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(vector<wchar_t *> dataVector); + +static void goodG2B() +{ + wchar_t * data; + vector<wchar_t *> dataVector; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + /* Put data in a vector */ + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + goodG2BSink(dataVector); +} + +void good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +using namespace CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_72; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard007/C++/0095054_virtual_method.cc b/pool/shard007/C++/0095054_virtual_method.cc new file mode 100644 index 0000000000000000000000000000000000000000..0ce242de15950c8864059a5f69d65f8dcdd59aa6 --- /dev/null +++ b/pool/shard007/C++/0095054_virtual_method.cc @@ -0,0 +1,98 @@ +#include <iostream> +#include <type_traits> + +#include "pointer_util.h" + +// General function type that can be reinterpreted to other function types. +typedef void (*Function)(void); +typedef void (*Method)(void *); + +class Box { +public: + void set(int len) { length = len; } + virtual void open() { std::cout << this << " : open" << std::endl; } + virtual void close() { std::cout << this << " : close" << std::endl; } + virtual void put() { std::cout << this << " : put" << std::endl; } + virtual void take() { std::cout << this << " : take" << std::endl; } + virtual void other1() { std::cout << this << " : other1" << std::endl; } + virtual void other2() { std::cout << this << " : other2" << std::endl; } + +private: + int height; + int width; + int length; +}; + +class Pencil { +public: + virtual void write() { std::cout << this << " : pencil write" << std::endl; } +}; + +class PencilBox : public Box, public Pencil { + virtual void open() { std::cout << this << ": open pencil box" << std::endl; } +}; + +union MView { + Function function; + Method method; + unsigned long number; +}; + +int fun() { return 12; } + +int main(void) { + auto box = Box(); + + std::cout << "Call open/close directly.\n"; + box.open(); + box.close(); + std::cout << "================\n"; + + printf("Print virtual method address\n"); + printf("open method address %d\n", &Box::open); + printf("close method address %d\n", &Box::close); + printf("put method address %d\n", &Box::put); + printf("take method address %d\n", &Box::take); + printf("other1 method address %d\n", &Box::other1); + printf("other2 method address %d\n", &Box::other2); + printf("================\n"); + + std::cout << Ptr2UL(&Box::open) << std::endl; + std::cout << Ptr2UL(&Box::close) << std::endl; + std::cout << Ptr2UL(&Box::put) << std::endl; + std::cout << Ptr2UL(&Box::take) << std::endl; + + auto vtbl = GetVPtr(&box); + printf("vtable address + 16: %x\n", vtbl); + + auto vtbl_ptr = UL2Ptr<unsigned long *>(vtbl); + printf("%x\n", vtbl_ptr[0]); + printf("%x\n", vtbl_ptr[1]); + + UL2Ptr<Method>(vtbl_ptr[0])(&box); + UL2Ptr<Method>(vtbl_ptr[1])(&box); + UL2Ptr<Method>(vtbl_ptr[2])(&box); + UL2Ptr<Method>(vtbl_ptr[3])(&box); + UL2Ptr<Method>(vtbl_ptr[4])(&box); + UL2Ptr<Method>(vtbl_ptr[5])(&box); + + printf("%x\n", UL2Ptr<Method>(vtbl_ptr[6])); + + // If you look at the assembly generated by gcc, + // you will see this in the constructor: + // movq vtable for Box+16, (%rax) + // That means the vptr in the object points to the vtable plus 16 bytes + // offset. The are 2 pointers leading the vtable: one for the multiple + // inheritance top pointer and another for RTTI. + // reinterpret_cast<Method>(vfun_ptr)(&box); + + return 0; +} + +void cast() { + PencilBox pb; + auto ptr = dynamic_cast<Pencil *>(&pb); + auto ptr1 = dynamic_cast<PencilBox *>(ptr); + std::cout << ptr << std::endl; + std::cout << ptr1 << std::endl; +} diff --git a/pool/shard007/C++/0095055_PHASER.cpp b/pool/shard007/C++/0095055_PHASER.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6fa869776d377dd532854aa2a56fbf3849c6cf84 --- /dev/null +++ b/pool/shard007/C++/0095055_PHASER.cpp @@ -0,0 +1,195 @@ +/* PHASER + + Runs samples through a user-specified number of allpass filters. It + processes only one input channel for a given note. + + p0 = output start time + p1 = input start time + p2 = input duration + p3 = amplitude multiplier + p4 = stages (should be even number, recommended 2 to 16 or 24) + p5 = LFO frequency (in cps) + p6 = reverb time (seconds) + p7 = wet/dry mix [optional (0.0 - 1.0), default is .5 (50% wet/50% dry)] + p8 = input channel [optional, default is 0] + p9 = pan (in percent-to-left format) [optional, default is .5] + + p3 (amp) and p9 (pan) can receive updates from a table or real-time + control source. + + Jenny Bernard <bernarjf at email dot uc dot edu>, 12/7/05 +*/ + +#include <stdio.h> +#include <stdlib.h> +#include <ugens.h> +#include <Ougens.h> +#include <rt.h> +#include <rtdefs.h> +#include "PHASER.h" + +using std::vector; + +#define DEBUG 0 + +const float kRingDur = 0.1; + + +PHASER::PHASER() + : _in(NULL), _branch(0) +{ +} + + +PHASER::~PHASER() +{ + delete [] _in; +} + + +int PHASER::init(double p[], int n_args) +{ + _nargs = n_args; // store this for use in doupdate() + + const float outskip = p[0]; + const float inskip = p[1]; + const float dur = p[2]; + _numfilters = int(p[4]); + _lfofreq = p[5]; + _reverbtime = p[6]; + _wetdry = (n_args > 7) ? p[7] : .5; // default is 0.5 (50% wet/50% dry) + if (_wetdry < 0.0 || _wetdry > 1.0) + _wetdry = 0.5; + _inchan = (n_args > 8) ? int(p[8]) : 0; // default is chan 0 + + // no need to retrieve amp or pan here, because these will be set + // before their first use inside of doupdate(). + + if (rtsetoutput(outskip, dur + kRingDur, this) == -1) + return DONT_SCHEDULE; + _insamps = int(dur * SR + 0.5); + + if (outputChannels() > 2) + return die("PHASER", "Use mono or stereo output only."); + + if (rtsetinput(inskip, this) == -1) + return DONT_SCHEDULE; + + if (_inchan >= inputChannels()) + return die("PHASER", "You asked for channel %d of a %d-channel input.", + _inchan, inputChannels()); + + // the Oallpassi's + float loopt = .01; + + lfo = new Ooscili(SR, _lfofreq, 2); + + _filtervector.resize(_numfilters); +#if DEBUG > 0 + printf("Vector successfully created.\n"); + printf("Vector size: %zd\n", _filtervector.size()); + printf("_reverbtime: %f\n", _reverbtime); +#endif + + for (int i = 0; i < _numfilters; i++) { + allpassptr = new Oallpassi(SR, loopt, loopt+.5, _reverbtime); + _filtervector[i] = allpassptr; + if (_filtervector[i]->frequency() == 0.0) + return die("PHASER", "Failed to allocate allpass memory!"); + loopt += 0.01; + } + +#if DEBUG > 0 + // This shows that the vector has been allocated with distinct filters + for (int i = 0; i < _numfilters; i++) { + printf("Oallpassi frequency in filtervector[%d]: %f\n", i, + _filtervector[i]->frequency()); + } +#endif + + return nSamps(); +} + + +int PHASER::configure() +{ + _in = new float [RTBUFSAMPS * inputChannels()]; + return _in ? 0 : -1; +} + + +void PHASER::doupdate() +{ + double p[10]; + update(p, 10); + + _amp = p[3]; + + _pan = (_nargs > 9) ? p[9] : 0.5; // default is .5 +} + + +int PHASER::run() +{ + const int samps = framesToRun() * inputChannels(); + + if (currentFrame() < _insamps) + rtgetin(_in, this, samps); + + for (int i = 0; i < samps; i += inputChannels()) { + if (--_branch <= 0) { + doupdate(); + _branch = getSkip(); + } + + // Grab the current input sample, scaled by the amplitude multiplier. + float insig = 0.0f; + if (currentFrame() < _insamps) + insig = _in[i + _inchan] * _amp; + + float delaysamps = lfo->next() * 0.5; + + // phasing loop + float wetsig = insig; + for (int j = 0; j < _numfilters; j++) { +// float thisdelay = (SR / (_filtervector[j]->frequency())); + wetsig = _filtervector[j]->next(wetsig, delaysamps); + } + + // cut down volume of filter output before mixing wet and dry--this is a hack +// wetsig = wetsig / float(_numfilters - (0.5 * (_numfilters - 1)); + + // mix wet and dry + float out[2]; + out[0] = (_wetdry * wetsig) + ((1.0f - _wetdry) * insig); + + // cut down volume after mixing wet and dry +// out[0] = out[0] / (float(_numfilters) * .55); + + if (outputChannels() == 2) { + out[1] = out[0] * (1.0f - _pan); + out[0] *= _pan; + } + + rtaddout(out); + increment(); + } + + return framesToRun(); +} + + +Instrument *makePHASER() +{ + PHASER *inst = new PHASER(); + inst->set_bus_config("PHASER"); + + return inst; +} + +#ifndef MAXMSP +void rtprofile() +{ + RT_INTRO("PHASER", makePHASER); +} +#endif diff --git a/pool/shard007/C++/0095060_CWE590_Free_Memory_Not_on_Heap__delete_char_alloca_65a.cpp b/pool/shard007/C++/0095060_CWE590_Free_Memory_Not_on_Heap__delete_char_alloca_65a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c220901c9d2aeeadae2ee4d95b918f663fe81b0 --- /dev/null +++ b/pool/shard007/C++/0095060_CWE590_Free_Memory_Not_on_Heap__delete_char_alloca_65a.cpp @@ -0,0 +1,101 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE590_Free_Memory_Not_on_Heap__delete_char_alloca_65a.cpp +Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete.pointer.label.xml +Template File: sources-sink-65a.tmpl.cpp +*/ +/* + * @description + * CWE: 590 Free Memory Not on Heap + * BadSource: alloca Data buffer is allocated on the stack with alloca() + * GoodSource: Allocate memory on the heap + * Sinks: + * BadSink : Print then free data + * Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer + * + * */ + +#include "std_testcase.h" + +#include <wchar.h> + +namespace CWE590_Free_Memory_Not_on_Heap__delete_char_alloca_65 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink(char * data); + +void bad() +{ + char * data; + /* define a function pointer */ + void (*funcPtr) (char *) = badSink; + data = NULL; /* Initialize data */ + { + /* FLAW: data is allocated on the stack and deallocated in the BadSink */ + char * dataBuffer = (char *)ALLOCA(sizeof(char)); + *dataBuffer = 'A'; + data = dataBuffer; + } + /* use the function pointer */ + funcPtr(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(char * data); + +static void goodG2B() +{ + char * data; + void (*funcPtr) (char *) = goodG2BSink; + data = NULL; /* Initialize data */ + { + /* FIX: data is allocated on the heap and deallocated in the BadSink */ + char * dataBuffer = new char; + *dataBuffer = 'A'; + data = dataBuffer; + } + funcPtr(data); +} + +void good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +using namespace CWE590_Free_Memory_Not_on_Heap__delete_char_alloca_65; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard007/C++/0095061_moc_overviewpage.cpp b/pool/shard007/C++/0095061_moc_overviewpage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e5585d0abf797d016cdc88ce81f6985e917b0468 --- /dev/null +++ b/pool/shard007/C++/0095061_moc_overviewpage.cpp @@ -0,0 +1,113 @@ +/**************************************************************************** +** Meta object code from reading C++ file 'overviewpage.h' +** +** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6) +** +** WARNING! All changes made in this file will be lost! +*****************************************************************************/ + +#include "../src/qt/overviewpage.h" +#if !defined(Q_MOC_OUTPUT_REVISION) +#error "The header file 'overviewpage.h' doesn't include <QObject>." +#elif Q_MOC_OUTPUT_REVISION != 63 +#error "This file was generated using the moc from 4.8.6. It" +#error "cannot be used with the include files from this version of Qt." +#error "(The moc has changed too much.)" +#endif + +QT_BEGIN_MOC_NAMESPACE +static const uint qt_meta_data_OverviewPage[] = { + + // content: + 6, // revision + 0, // classname + 0, 0, // classinfo + 5, 14, // methods + 0, 0, // properties + 0, 0, // enums/sets + 0, 0, // constructors + 0, // flags + 1, // signalCount + + // signals: signature, parameters, type, tag, flags + 20, 14, 13, 13, 0x05, + + // slots: signature, parameters, type, tag, flags + 101, 52, 13, 13, 0x0a, + 141, 13, 13, 13, 0x0a, + 156, 13, 13, 13, 0x08, + 176, 14, 13, 13, 0x08, + + 0 // eod +}; + +static const char qt_meta_stringdata_OverviewPage[] = { + "OverviewPage\0\0index\0transactionClicked(QModelIndex)\0" + "balance,stake,unconfirmedBalance,immatureBalance\0" + "setBalance(qint64,qint64,qint64,qint64)\0" + "unlockWallet()\0updateDisplayUnit()\0" + "handleTransactionClicked(QModelIndex)\0" +}; + +void OverviewPage::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) +{ + if (_c == QMetaObject::InvokeMetaMethod) { + Q_ASSERT(staticMetaObject.cast(_o)); + OverviewPage *_t = static_cast<OverviewPage *>(_o); + switch (_id) { + case 0: _t->transactionClicked((*reinterpret_cast< const QModelIndex(*)>(_a[1]))); break; + case 1: _t->setBalance((*reinterpret_cast< qint64(*)>(_a[1])),(*reinterpret_cast< qint64(*)>(_a[2])),(*reinterpret_cast< qint64(*)>(_a[3])),(*reinterpret_cast< qint64(*)>(_a[4]))); break; + case 2: _t->unlockWallet(); break; + case 3: _t->updateDisplayUnit(); break; + case 4: _t->handleTransactionClicked((*reinterpret_cast< const QModelIndex(*)>(_a[1]))); break; + default: ; + } + } +} + +const QMetaObjectExtraData OverviewPage::staticMetaObjectExtraData = { + 0, qt_static_metacall +}; + +const QMetaObject OverviewPage::staticMetaObject = { + { &QWidget::staticMetaObject, qt_meta_stringdata_OverviewPage, + qt_meta_data_OverviewPage, &staticMetaObjectExtraData } +}; + +#ifdef Q_NO_DATA_RELOCATION +const QMetaObject &OverviewPage::getStaticMetaObject() { return staticMetaObject; } +#endif //Q_NO_DATA_RELOCATION + +const QMetaObject *OverviewPage::metaObject() const +{ + return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; +} + +void *OverviewPage::qt_metacast(const char *_clname) +{ + if (!_clname) return 0; + if (!strcmp(_clname, qt_meta_stringdata_OverviewPage)) + return static_cast<void*>(const_cast< OverviewPage*>(this)); + return QWidget::qt_metacast(_clname); +} + +int OverviewPage::qt_metacall(QMetaObject::Call _c, int _id, void **_a) +{ + _id = QWidget::qt_metacall(_c, _id, _a); + if (_id < 0) + return _id; + if (_c == QMetaObject::InvokeMetaMethod) { + if (_id < 5) + qt_static_metacall(this, _c, _id, _a); + _id -= 5; + } + return _id; +} + +// SIGNAL 0 +void OverviewPage::transactionClicked(const QModelIndex & _t1) +{ + void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; + QMetaObject::activate(this, &staticMetaObject, 0, _a); +} +QT_END_MOC_NAMESPACE diff --git a/pool/shard007/C++/0095062_suite.cpp b/pool/shard007/C++/0095062_suite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b40ffaafadca4d27ccb534627faa61c9a8a6c2db --- /dev/null +++ b/pool/shard007/C++/0095062_suite.cpp @@ -0,0 +1,258 @@ +// --- +// +// $Id: suite.cpp,v 1.3 2005/06/08 08:08:06 nilu Exp $ +// +// CppTest - A C++ Unit Testing Framework +// Copyright (c) 2003 Niklas Lundell +// +// --- +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the +// Free Software Foundation, Inc., 59 Temple Place - Suite 330, +// Boston, MA 02111-1307, USA. +// +// --- + +#include <algorithm> +#include <cassert> +#include <cstring> +#include <functional> +#include <numeric> + +#include "config.h" +#include "cpptest-output.h" +#include "cpptest-source.h" +#include "cpptest-suite.h" + +using namespace std; + +namespace Test +{ + namespace + { + // Destroys all dynamically allocated objects within the given range. + // + template <class FwdIter> + void + destroy_range(FwdIter first, FwdIter last) + { + while (first != last) + delete *first++; + } + + } // anonymous namespace + + /// Constructs an empty test suite. + /// + Suite::Suite() + : _cur_test(0), + _output(0), + _success(true) + {} + + /// Destroys this suite object. + /// + Suite::~Suite() + { + destroy_range(_suites.begin(), _suites.end()); + } + + /// Starts the testing. All tests in this suite and embedded suites will + /// be executed. + /// + /// \param output Progress report destination. + /// \param cont_after_fail Continue functions despite failures. + /// + /// \return True if no test failed; false otherwise. + /// + bool + Suite::run(Output& output, bool cont_after_fail) + { + int ntests = total_tests(); + output.initialize(ntests); + do_run(&output, cont_after_fail); + output.finished(ntests, total_time(true)); + return _success; + } + + /// \fn void Suite::setup() + /// + /// Setups a test fixture. This function is called before each test, + /// in this suite, is executed. + /// + /// This function should be overloaded by derived classes to provide + /// specialized behavior. + /// + /// \see tear_down() + + /// \fn void Suite::tear_down() + /// + /// Tears down a test fixture. This function is called after each test, + /// in this suite, have been executed. + /// + /// This function should be overloaded by derived classes to provide + /// specialized behavior. + /// + /// \see setup() + + /// Adds a suite to this suite. Tests in added suites will be executed + /// when run() of the top-level suite is called. + /// + /// \param suite %Test suite to add. + /// + void + Suite::add(auto_ptr<Suite> suite) + { + _suites.push_back(suite.release()); + } + + /// Registers a test function. + /// + /// \b Note: Do not call this function directly, use the TEST_ADD(func) + /// macro instead. + /// + /// \param func Pointer to a test function. + /// \param name Class and function name of the function. The format \b must + /// equal \e class::func. + /// + void + Suite::register_test(Func func, const string& name) + { + string::size_type pos = name.find_first_of(':'); + assert(!name.empty() && name[pos + 1] == ':' && name[pos + 2] != '\0'); + + _name.assign(name, 0, pos); + _tests.push_back(Data(func, name.substr(pos + 2))); + } + + /// Issues an assertment to the output handler. + /// + /// Do not call this function directly, use one of the available assertment + /// macros instead, see \ref asserts. + /// + /// \param s Assert point information. + /// + void + Suite::assertment(Source s) + { + s._suite = _name; + s._test = *_cur_test; + _output->assertment(s); + _result = _success = false; + } + + // Functor to execute tests for the given suite. + // + struct Suite::ExecTests + { + Suite& _suite; + + ExecTests(Suite& s) : _suite(s) {} + + void operator()(Data& data) + { + _suite._cur_test = &data._name; + _suite._result = true; // assume success, assert will set to false + _suite._output->test_start(data._name); + + _suite.setup(); + Time start(Time::current()); + (_suite.*data._func)(); + Time end(Time::current()); + _suite.tear_down(); + + data._time = end - start; + _suite._output->test_end(data._name, _suite._result, data._time); + } + }; + + // Functor to execute a suite. + // + struct Suite::DoRun + { + bool _continue; + Output* _output; + + DoRun(Output* output, bool cont) : _continue(cont), _output(output) {} + void operator()(Suite* suite) { suite->do_run(_output, _continue); } + }; + + // Execute all tests in this and added suites. + // + void + Suite::do_run(Output* os, bool cont_after_fail) + { + _continue = cont_after_fail; + _output = os; + + _output->suite_start(_tests.size(), _name); + for_each(_tests.begin(), _tests.end(), ExecTests(*this)); + _output->suite_end(_tests.size(), _name, total_time(false)); + + for_each(_suites.begin(), _suites.end(), DoRun(_output, _continue)); + } + + // Functor to count all tests in a suite. + // + struct Suite::SubSuiteTests + { + int operator()(size_t value, const Suite* s) const + { + return value + s->total_tests(); + } + }; + + // Counts all tests in this and all its embedded suites. + // + int + Suite::total_tests() const + { + return accumulate(_suites.begin(), _suites.end(), + _tests.size(), SubSuiteTests()); + } + + // Functor to accumulate execution time for tests. + // + struct Suite::SuiteTime + { + Time operator()(const Time& time, const Data& data) + { + return time + data._time; + } + }; + + // Functor to accumulate execution time for suites. + // + struct Suite::SubSuiteTime + { + Time operator()(Time time, const Suite* s) const + { + return time + s->total_time(true); + } + }; + + // Counts time accumulated execution time for all tests in this and all + // its embedded suites. + // + Time + Suite::total_time(bool recursive) const + { + Time time = accumulate(_tests.begin(), _tests.end(), + Time(), SuiteTime()); + + return !recursive ? time : accumulate(_suites.begin(), _suites.end(), + time, SubSuiteTime()); + } + +} // namespace Test diff --git a/pool/shard007/C++/0095063_content_index_service_impl.cc b/pool/shard007/C++/0095063_content_index_service_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..175cffbc82a88c1fb79283c57973b577f01af9ed --- /dev/null +++ b/pool/shard007/C++/0095063_content_index_service_impl.cc @@ -0,0 +1,167 @@ +// Copyright 2019 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 "content/browser/content_index/content_index_service_impl.h" + +#include <memory> + +#include "base/bind.h" +#include "base/task/post_task.h" +#include "content/browser/bad_message.h" +#include "content/browser/content_index/content_index_database.h" +#include "content/browser/storage_partition_impl.h" +#include "content/public/browser/browser_task_traits.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/render_process_host.h" +#include "content/public/browser/service_worker_version_base_info.h" +#include "mojo/public/cpp/bindings/self_owned_receiver.h" +#include "third_party/blink/public/common/storage_key/storage_key.h" +#include "url/origin.h" + +namespace content { + +namespace { + +void DidCheckOfflineCapability( + ContentIndexServiceImpl::CheckOfflineCapabilityCallback callback, + int64_t expected_registration_id, + OfflineCapability capability, + int64_t registration_id) { + switch (capability) { + case OfflineCapability::kUnsupported: + std::move(callback).Run(false); + return; + case OfflineCapability::kSupported: + std::move(callback).Run(expected_registration_id == registration_id); + return; + } +} + +} // namespace + +// static +void ContentIndexServiceImpl::CreateForFrame( + RenderFrameHost* render_frame_host, + mojo::PendingReceiver<blink::mojom::ContentIndexService> receiver) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + RenderProcessHost* render_process_host = render_frame_host->GetProcess(); + DCHECK(render_process_host); + auto* storage_partition = static_cast<StoragePartitionImpl*>( + render_process_host->GetStoragePartition()); + + mojo::MakeSelfOwnedReceiver( + std::make_unique<ContentIndexServiceImpl>( + render_frame_host->GetLastCommittedOrigin(), + storage_partition->GetContentIndexContext(), + storage_partition->GetServiceWorkerContext(), + render_frame_host->GetParentOrOuterDocument() == nullptr), + std::move(receiver)); +} + +// static +void ContentIndexServiceImpl::CreateForWorker( + const ServiceWorkerVersionBaseInfo& info, + mojo::PendingReceiver<blink::mojom::ContentIndexService> receiver) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + RenderProcessHost* render_process_host = + RenderProcessHost::FromID(info.process_id); + + if (!render_process_host) + return; + + auto* storage_partition = static_cast<StoragePartitionImpl*>( + render_process_host->GetStoragePartition()); + + mojo::MakeSelfOwnedReceiver(std::make_unique<ContentIndexServiceImpl>( + info.storage_key.origin(), + storage_partition->GetContentIndexContext(), + storage_partition->GetServiceWorkerContext(), + info.storage_key.IsFirstPartyContext()), + std::move(receiver)); +} + +ContentIndexServiceImpl::ContentIndexServiceImpl( + const url::Origin& origin, + scoped_refptr<ContentIndexContextImpl> content_index_context, + scoped_refptr<ServiceWorkerContextWrapper> service_worker_context, + bool is_top_level_context) + : origin_(origin), + content_index_context_(std::move(content_index_context)), + service_worker_context_(std::move(service_worker_context)), + is_top_level_context_(is_top_level_context) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); +} + +ContentIndexServiceImpl::~ContentIndexServiceImpl() = default; + +void ContentIndexServiceImpl::GetIconSizes( + blink::mojom::ContentCategory category, + GetIconSizesCallback callback) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + content_index_context_->GetIconSizes(category, std::move(callback)); +} + +void ContentIndexServiceImpl::CheckOfflineCapability( + int64_t service_worker_registration_id, + const GURL& launch_url, + CheckOfflineCapabilityCallback callback) { + // TODO(rayankans): Figure out if we can check the service worker specified + // by |service_worker_registration_id| rather than any service worker. + service_worker_context_->CheckOfflineCapability( + launch_url, blink::StorageKey(url::Origin::Create(launch_url)), + base::BindOnce(&DidCheckOfflineCapability, std::move(callback), + service_worker_registration_id)); +} + +void ContentIndexServiceImpl::Add( + int64_t service_worker_registration_id, + blink::mojom::ContentDescriptionPtr description, + const std::vector<SkBitmap>& icons, + const GURL& launch_url, + AddCallback callback) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + for (const auto& icon : icons) { + if (icon.isNull() || icon.width() * icon.height() > kMaxIconResolution) { + mojo::ReportBadMessage("Invalid icon"); + std::move(callback).Run( + blink::mojom::ContentIndexError::INVALID_PARAMETER); + return; + } + } + + if (!launch_url.is_valid() || !origin_.IsSameOriginWith(url::Origin::Create( + launch_url.DeprecatedGetOriginAsURL()))) { + mojo::ReportBadMessage("Invalid launch URL"); + std::move(callback).Run(blink::mojom::ContentIndexError::INVALID_PARAMETER); + return; + } + + content_index_context_->database().AddEntry( + service_worker_registration_id, origin_, is_top_level_context_, + std::move(description), icons, launch_url, std::move(callback)); +} + +void ContentIndexServiceImpl::Delete(int64_t service_worker_registration_id, + const std::string& content_id, + DeleteCallback callback) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + content_index_context_->database().DeleteEntry( + service_worker_registration_id, origin_, content_id, std::move(callback)); +} + +void ContentIndexServiceImpl::GetDescriptions( + int64_t service_worker_registration_id, + GetDescriptionsCallback callback) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + content_index_context_->database().GetDescriptions( + service_worker_registration_id, origin_, std::move(callback)); +} + +} // namespace content diff --git a/pool/shard007/C++/0095066_random.cpp b/pool/shard007/C++/0095066_random.cpp new file mode 100644 index 0000000000000000000000000000000000000000..15944d8d4a852095f3e9177a87bfba403ef06cd2 --- /dev/null +++ b/pool/shard007/C++/0095066_random.cpp @@ -0,0 +1,230 @@ +/* + * Copyright (c) 2016 - 2021 Pedro Falcato + * This file is part of Onyx, and is released under the terms of the MIT License + * check LICENSE at the root directory for more information + * + * SPDX-License-Identifier: MIT + */ + +#include <assert.h> +#include <errno.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> + +#include <onyx/clock.h> +#include <onyx/compiler.h> +#include <onyx/dev.h> +#include <onyx/process.h> +#include <onyx/random.h> +#include <onyx/timer.h> + +#include <drivers/rtc.h> + +const size_t max_entropy = PAGE_SIZE * 4; +static char entropy_buffer[PAGE_SIZE * 4] = {}; +struct spinlock entropy_lock; +static size_t current_entropy = 0; + +void add_entropy(void *ent, size_t size) +{ + scoped_lock g{entropy_lock}; + if (current_entropy == max_entropy || current_entropy + size > max_entropy) + { + } + else + { + memcpy(&entropy_buffer[current_entropy], ent, size); + current_entropy += size; + } +} + +void entropy_refill(void) +{ + unsigned int *buf = (unsigned int *) entropy_buffer; + size_t nr_refills = max_entropy / sizeof(unsigned int); + for (size_t i = 0; i < nr_refills; i++) + { + *buf++ = + clock_get_posix_time() << 28 | ((entropy::platform::get_hwrandom() << 20) ^ rand()); + } + + current_entropy = max_entropy; +} + +extern "C" void get_entropy(char *buf, size_t s) +{ + scoped_lock g{entropy_lock}; + + for (size_t i = 0; i < s; i++) + { + if (current_entropy == 0) + entropy_refill(); + *buf++ = entropy_buffer[0]; + current_entropy--; + memmove(entropy_buffer, &entropy_buffer[1], current_entropy); + } +} + +size_t ent_read(size_t off, size_t count, void *buffer, struct file *node) +{ + get_entropy((char *) buffer, count); + return count; +} + +void initialize_entropy(void) +{ + entropy::platform::init_random(); + /* Use get_posix_time as entropy, together with the platform's seed */ + uint64_t p = get_posix_time_early(); + add_entropy(&p, sizeof(uint64_t)); + auto seed = entropy::platform::get_seed(); + add_entropy(&seed, sizeof(uint64_t)); + srand((unsigned int) (seed | ~p)); + for (size_t i = current_entropy; i < max_entropy; i += sizeof(int)) + { + int r = rand(); + add_entropy(&r, sizeof(int)); + } +} + +size_t random_get_entropy(size_t size, void *buffer) +{ + unsigned char *buf = (unsigned char *) buffer; + size_t to_read = size; + while (to_read) + { + if (signal_is_pending()) + return -EINTR; + + if (current_entropy) + { + size_t r = current_entropy > to_read ? to_read : current_entropy; + + if (copy_to_user(buf, entropy_buffer, r) < 0) + return -EFAULT; + + buf += r; + to_read -= r; + } + } + return size; +} + +size_t urandom_get_entropy(size_t size, void *buffer) +{ + unsigned char *buf = (unsigned char *) buffer; + size_t to_read = size; + while (to_read) + { + if (signal_is_pending()) + return -EINTR; + if (current_entropy) + { + size_t r = current_entropy > to_read ? to_read : current_entropy; + + if (copy_to_user(buf, entropy_buffer, r) < 0) + return -EFAULT; + + buf += r; + to_read -= r; + } + else + { + entropy_refill(); + } + } + return size; +} + +size_t get_entropy_from_pool(int pool, size_t size, void *buffer) +{ + assert(pool == ENTROPY_POOL_RANDOM || pool == ENTROPY_POOL_URANDOM); + size_t ret = (size_t) -EINVAL; + + scoped_lock g{entropy_lock}; + + switch (pool) + { + case ENTROPY_POOL_RANDOM: { + ret = random_get_entropy(size, buffer); + break; + } + + case ENTROPY_POOL_URANDOM: { + ret = urandom_get_entropy(size, buffer); + break; + } + } + + return ret; +} + +size_t random_read(size_t offset, size_t sizeofreading, void *buffer, struct file *f) +{ + return get_entropy_from_pool(ENTROPY_POOL_RANDOM, sizeofreading, buffer); +} + +size_t urandom_read(size_t offset, size_t sizeofreading, void *buffer, struct file *f) +{ + return get_entropy_from_pool(ENTROPY_POOL_URANDOM, sizeofreading, buffer); +} + +#define DEV_RANDOM_MINOR 0 +#define DEV_URANDOM_MINOR 1 + +const file_ops random_fops = {.read = random_read}; + +const file_ops urandom_fops = {.read = urandom_read}; + +static chardev *random_dev, *urandom_dev; + +static int init_random_dev(dev_t *major) +{ + auto ex = dev_register_chardevs(DEV_RANDOM_MINOR, 1, 0, &random_fops, cul::string{"random"}); + + if (ex.has_error()) + return ex.error(); + + random_dev = ex.value(); + random_dev->show(0666); + *major = MAJOR(random_dev->dev()); + + return 0; +} + +static int init_urandom_dev(dev_t major_nr) +{ + auto ex = dev_register_chardevs(0, 1, 0, &urandom_fops, cul::string{"urandom"}); + if (ex.has_error()) + return ex.error(); + + urandom_dev = ex.value(); + urandom_dev->show(0666); + + return 0; +} + +void entropy_init_dev(void) +{ + // random registration is responsible for getting the major number for random and urandom + // This is kind of not very pretty honestly... + dev_t random_devs_major = 0; + + if (init_random_dev(&random_devs_major) < 0) + return; + + init_urandom_dev(random_devs_major); +} + +unsigned int get_random_int(void) +{ + auto num = entropy::platform::get_hwrandom(); + + return (unsigned int) num ^ (num >> 32); +} + +int sys_getrandom(void *buf, size_t buflen, unsigned int flags) +{ + return (int) get_entropy_from_pool(ENTROPY_POOL_URANDOM, buflen, buf); +} diff --git a/pool/shard007/C++/0095067_indexeddb_key_path.cc b/pool/shard007/C++/0095067_indexeddb_key_path.cc new file mode 100644 index 0000000000000000000000000000000000000000..00983c5a95289ec1e71fb2a8542e96603ff1cc07 --- /dev/null +++ b/pool/shard007/C++/0095067_indexeddb_key_path.cc @@ -0,0 +1,55 @@ +// Copyright (c) 2012 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 "third_party/blink/public/common/indexeddb/indexeddb_key_path.h" + +#include "base/check.h" +#include "base/notreached.h" +#include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom-shared.h" + +namespace blink { + +IndexedDBKeyPath::IndexedDBKeyPath() : type_(mojom::IDBKeyPathType::Null) {} + +IndexedDBKeyPath::IndexedDBKeyPath(const std::u16string& string) + : type_(mojom::IDBKeyPathType::String), string_(string) {} + +IndexedDBKeyPath::IndexedDBKeyPath(const std::vector<std::u16string>& array) + : type_(mojom::IDBKeyPathType::Array), array_(array) {} + +IndexedDBKeyPath::IndexedDBKeyPath(const IndexedDBKeyPath& other) = default; +IndexedDBKeyPath::IndexedDBKeyPath(IndexedDBKeyPath&& other) = default; +IndexedDBKeyPath::~IndexedDBKeyPath() = default; +IndexedDBKeyPath& IndexedDBKeyPath::operator=(const IndexedDBKeyPath& other) = + default; +IndexedDBKeyPath& IndexedDBKeyPath::operator=(IndexedDBKeyPath&& other) = + default; + +const std::vector<std::u16string>& IndexedDBKeyPath::array() const { + DCHECK(type_ == blink::mojom::IDBKeyPathType::Array); + return array_; +} + +const std::u16string& IndexedDBKeyPath::string() const { + DCHECK(type_ == blink::mojom::IDBKeyPathType::String); + return string_; +} + +bool IndexedDBKeyPath::operator==(const IndexedDBKeyPath& other) const { + if (type_ != other.type_) + return false; + + switch (type_) { + case mojom::IDBKeyPathType::Null: + return true; + case mojom::IDBKeyPathType::String: + return string_ == other.string_; + case mojom::IDBKeyPathType::Array: + return array_ == other.array_; + } + NOTREACHED(); + return false; +} + +} // namespace blink diff --git a/pool/shard007/C++/0095070_bencher.cc b/pool/shard007/C++/0095070_bencher.cc new file mode 100644 index 0000000000000000000000000000000000000000..144ab08521df3f502785456fbd0bfd1ebafaa2e4 --- /dev/null +++ b/pool/shard007/C++/0095070_bencher.cc @@ -0,0 +1,210 @@ +/* + * Copyright (C) 2007 The Vaucanson Group. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + */ + +/** + ** \file misc/bencher.cc + ** \brief Implementation for misc/bencher.hh. + */ + +#ifndef VCSN_MISC_BENCHER_CC +# define VCSN_MISC_BENCHER_CC + +# include <vaucanson/misc/bencher.hh> + +/// This file is also used in Tiger Compiler, where it is compiled in +/// a C library, so INLINE_TIMER_CC should be defined to empty in that +/// case. +# if VAUCANSON +# define INLINE_BENCHER_CC inline +# else +# define INLINE_BENCHER_CC +# endif + + +NAMESPACE_VCSN_BEGIN + +namespace misc +{ + + INLINE_BENCHER_CC + timer::Timer + Bencher::sum () const + { + timer::Timer res; + for (std::vector< timer::Timer >::const_iterator i = timers_.begin (); + i != timers_.end (); ++i) + res += *i; + return res; + } + + INLINE_BENCHER_CC + timer::Timer + Bencher::mean () const + { + precondition (!timers_.empty()); + return sum() / timers_.size(); + } + + INLINE_BENCHER_CC + timer::Timer + Bencher::min () const + { + precondition (!timers_.empty()); + return *std::min_element(timers_.begin (), timers_.end ()); + } + + INLINE_BENCHER_CC + timer::Timer + Bencher::max () const + { + precondition (!timers_.empty()); + return *std::max_element(timers_.begin (), timers_.end ()); + } + + INLINE_BENCHER_CC + timer::Timer + Bencher::prepare (timer::Timer t) const + { + precondition (!timers_.empty()); + return t; + } + + INLINE_BENCHER_CC + std::ostream& + Bencher::print (std::ostream& o) const + { + const char* line = "-------------------------"; + std::vector< timer::Timer >::const_iterator i; + for (i = this->timers_.begin (); i != this->timers_.end (); ++i) + { + o << line << std::endl + << (*i); + } + o << std::endl + << line << " SUMMARY " << line << std::endl + << line << " Arithmetic mean" << std::endl << prepare(mean()) + << line << " Sum" << std::endl << prepare(sum()) + << line << " Min" << std::endl << prepare(min()) + << line << " Max" << std::endl << prepare(max()); + return o; + } + + INLINE_BENCHER_CC + void + Bencher::plot (std::ostream& o) const + { + std::vector< timer::Timer >::const_iterator i; + for (i = this->timers_.begin (); i != this->timers_.end (); ++i) + { + o << (*i) + << std::endl; + } + } + + + /*--------------------------. + | Free standing functions. | + `--------------------------*/ + + /// Dump \a t on \a o. + INLINE_BENCHER_CC + std::ostream& + operator<< (std::ostream& o, const Bencher& t) + { + return t.print (o); + } + +}// namespace misc + +NAMESPACE_VCSN_END + + +# if TEST_BENCHER + +# include <iostream> +# include <vaucanson/misc/bencher.hh> +# include <fstream> + +# define msleep(MilliSecond) usleep(MilliSecond * 1000) + +/// Test the bencher. +int +main () +{ +# if defined VAUCANSON + using namespace vcsn; +# endif + + misc::Bencher b; + timer::Timer timer; + enum timevar + { + One = 1, + Two, + Three, + Four + }; + + std::ofstream outfile ("test.plot", + std::ofstream::out | std::ofstream::trunc); + + for (int i = 0; i < 10; i++) + { + timer.clear(); + + timer.name (One, "One"); + timer.name (Two, "Two"); + timer.name (Three, "Three"); + timer.name (Four, "Four"); + + timer.start (); + + timer.push (One); + msleep (i * 10); + + timer.push ("Two"); + msleep (i * 10); + timer.push ("Four"); + msleep (i * 10); + + timer.pop ("Four"); + timer.pop ("Two"); + timer.pop (1); + + timer.push ("Three"); + msleep (i * 10); + timer.pop (Three); + + timer.stop (); + b.push (timer); + } + b.print(std::cerr); + b.plot(outfile); + + outfile.close(); + return 0; +} + +# endif // TEST_BENCHER + +#endif // !VCSN_MISC_BENCHER_CC + +/// Local Variables: +/// compile-command: "g++ -I ../.. -I ../../../_build/include -DTEST_BENCHER timer.cc bencher.cc -o test-bencher -Wall && ./test-bencher" +/// End: diff --git a/pool/shard007/C++/0095071_audiostream.cpp b/pool/shard007/C++/0095071_audiostream.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a809420e05266cbe98d74da425a2e7c316d00ca0 --- /dev/null +++ b/pool/shard007/C++/0095071_audiostream.cpp @@ -0,0 +1,203 @@ +/* xoreos - A reimplementation of BioWare's Aurora engine + * + * xoreos is the legal property of its developers, whose names + * can be found in the AUTHORS file distributed with this source + * distribution. + * + * xoreos is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 3 + * of the License, or (at your option) any later version. + * + * xoreos is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with xoreos. If not, see <http://www.gnu.org/licenses/>. + */ + +// Largely based on the AudioStream implementation found in ScummVM. + +/** @file + * Streaming audio. + */ + +#include <queue> + +#include "src/common/error.h" +#include "src/common/mutex.h" + +#include "src/sound/audiostream.h" + +namespace Sound { + +LoopingAudioStream::LoopingAudioStream(RewindableAudioStream *stream, size_t loops, bool disposeAfterUse) + : _parent(stream), _disposeAfterUse(disposeAfterUse), _loops(loops), _completeIterations(0) { +} + +LoopingAudioStream::~LoopingAudioStream() { + if (_disposeAfterUse) + delete _parent; +} + +size_t LoopingAudioStream::readBuffer(int16 *buffer, const size_t numSamples) { + if ((_loops && _completeIterations == _loops) || !numSamples) + return 0; + + const size_t samplesRead = _parent->readBuffer(buffer, numSamples); + if (samplesRead == kSizeInvalid) + return kSizeInvalid; + + if (_parent->endOfStream()) { + ++_completeIterations; + if (_completeIterations == _loops) + return samplesRead; + + const size_t remainingSamples = numSamples - samplesRead; + + if (!_parent->rewind()) { + // TODO: Properly indicate error + _loops = _completeIterations = 1; + return samplesRead; + } + + const size_t samplesReadNext = readBuffer(buffer + samplesRead, remainingSamples); + if (samplesReadNext == kSizeInvalid) + return kSizeInvalid; + + return samplesRead + samplesReadNext; + } + + return samplesRead; +} + +bool LoopingAudioStream::endOfData() const { + return (_loops != 0 && (_completeIterations == _loops)); +} + +AudioStream *makeLoopingAudioStream(RewindableAudioStream *stream, size_t loops) { + if (loops != 1) + return new LoopingAudioStream(stream, loops); + else + return stream; +} + +class QueuingAudioStreamImpl : public QueuingAudioStream { +private: + /** + * We queue a number of (pointers to) audio stream objects. + * In addition, we need to remember for each stream whether + * to dispose it after all data has been read from it. + * Hence, we don't store pointers to stream objects directly, + * but rather StreamHolder structs. + */ + struct StreamHolder { + AudioStream *_stream; + bool _disposeAfterUse; + StreamHolder(AudioStream *stream, bool disposeAfterUse) + : _stream(stream), + _disposeAfterUse(disposeAfterUse) {} + }; + + /** + * The sampling rate of this audio stream. + */ + const int _rate; + + /** + * The number of channels in this audio stream. + */ + const int _channels; + + /** + * This flag is set by the finish() method only. See there for more details. + */ + bool _finished; + + /** + * A mutex to avoid access problems (causing e.g. corruption of + * the linked list) in thread aware environments. + */ + Common::Mutex _mutex; + + /** + * The queue of audio streams. + */ + std::queue<StreamHolder> _queue; + +public: + QueuingAudioStreamImpl(int rate, int channels) + : _rate(rate), _channels(channels), _finished(false) {} + ~QueuingAudioStreamImpl(); + + // Implement the AudioStream API + virtual size_t readBuffer(int16 *buffer, const size_t numSamples); + virtual int getChannels() const { return _channels; } + virtual int getRate() const { return _rate; } + virtual bool endOfData() const { + //Common::StackLock lock(_mutex); + return _queue.empty(); + } + virtual bool endOfStream() const { return _finished && _queue.empty(); } + + // Implement the QueuingAudioStream API + virtual void queueAudioStream(AudioStream *stream, bool disposeAfterUse); + virtual void finish() { _finished = true; } + + size_t numQueuedStreams() const { + //Common::StackLock lock(_mutex); + return _queue.size(); + } +}; + +QueuingAudioStreamImpl::~QueuingAudioStreamImpl() { + while (!_queue.empty()) { + StreamHolder tmp = _queue.front(); + _queue.pop(); + if (tmp._disposeAfterUse) + delete tmp._stream; + } +} + +void QueuingAudioStreamImpl::queueAudioStream(AudioStream *stream, bool disposeAfterUse) { + if (_finished) + throw Common::Exception("QueuingAudioStreamImpl::queueAudioStream(): Trying to queue another audio stream, but the QueuingAudioStream is finished."); + + if ((stream->getRate() != getRate()) || (stream->getChannels() != getChannels())) + throw Common::Exception("QueuingAudioStreamImpl::queueAudioStream(): stream has mismatched parameters"); + + Common::StackLock lock(_mutex); + _queue.push(StreamHolder(stream, disposeAfterUse)); +} + +size_t QueuingAudioStreamImpl::readBuffer(int16 *buffer, const size_t numSamples) { + Common::StackLock lock(_mutex); + size_t samplesDecoded = 0; + + while (samplesDecoded < numSamples && !_queue.empty()) { + AudioStream *stream = _queue.front()._stream; + + const size_t n = stream->readBuffer(buffer + samplesDecoded, numSamples - samplesDecoded); + if (n == kSizeInvalid) + return kSizeInvalid; + + samplesDecoded += n; + + if (stream->endOfData()) { + StreamHolder tmp = _queue.front(); + _queue.pop(); + if (tmp._disposeAfterUse) + delete stream; + } + } + + return samplesDecoded; +} + +QueuingAudioStream *makeQueuingAudioStream(int rate, int channels) { + return new QueuingAudioStreamImpl(rate, channels); +} + +} // End of namespace Sound diff --git a/pool/shard007/C++/0095082_HostInfoClass.cpp b/pool/shard007/C++/0095082_HostInfoClass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..87d77c975deb5af5a88ad98a48b9d41c83094031 --- /dev/null +++ b/pool/shard007/C++/0095082_HostInfoClass.cpp @@ -0,0 +1,170 @@ +#include "HostInfoClass.h" + +#using <mscorlib.dll> +using namespace System; +using namespace System::Runtime::InteropServices; + +// ---------------------- Callback Class for HostInfo ------------------------ + +namespace SharpSoundDevice +{ + namespace VST + { + HostInfoClass::HostInfoClass() + { + HostVendorPtr = new char[128]; + HostNamePtr = new char[128]; + } + + HostInfoClass::~HostInfoClass() + { + delete HostVendorPtr; + delete HostNamePtr; + } + + void HostInfoClass::SendEvent(int pluginSenderId, SharpSoundDevice::Event ev) + { + try + { + if (ev.Type == SharpSoundDevice::EventType::Parameter) + { + double val = ((System::Double)ev.Data); + int index = ev.EventIndex; + vstHost->setParameterAutomated(index, (float)val); + vstHost->updateDisplay(); + } + else if (ev.Type == SharpSoundDevice::EventType::Midi) + { + array<unsigned char>^ evData = (array<unsigned char>^)ev.Data; + VstEvents events; + events.numEvents = 1; + + //sysex + if (evData[0] == 0xF0) + { + unsigned char* data = new unsigned char[evData->Length]; + Marshal::Copy(evData, 0, (IntPtr)data, evData->Length); + + VstMidiSysexEvent sysexEv; + sysexEv.byteSize = sizeof(VstMidiSysexEvent); + sysexEv.deltaFrames = ev.EventIndex; + sysexEv.dumpBytes = evData->Length; + sysexEv.flags = 0; + sysexEv.sysexDump = (char*)data; + sysexEv.type = kVstSysExType; + + events.events[0] = (VstEvent*)&sysexEv; + vstHost->sendVstEventsToHost(&events); + delete data; + } + else + { + if (evData->Length < 1 || evData->Length > 4) + return; + + VstMidiEvent midiEv; + midiEv.byteSize = sizeof(VstMidiEvent); + midiEv.deltaFrames = ev.EventIndex; + midiEv.detune = 0; + midiEv.flags = kVstMidiEventIsRealtime; + midiEv.midiData[0] = evData[0]; + + if (evData->Length >= 2) + midiEv.midiData[1] = evData[1]; + else + midiEv.midiData[1] = 0; + + if (evData->Length >= 3) + midiEv.midiData[2] = evData[2]; + else + midiEv.midiData[2] = 0; + + midiEv.midiData[3] = 0; + midiEv.noteLength = 0; + midiEv.noteOffset = 0; + midiEv.noteOffVelocity = 0; + midiEv.type = kVstMidiType; + + events.events[0] = (VstEvent*)&midiEv; + vstHost->sendVstEventsToHost(&events); + } + } + else if (ev.Type == SharpSoundDevice::EventType::ProgramChange) + { + vstHost->updateDisplay(); + } + else if (ev.Type == SharpSoundDevice::EventType::WindowSize) + { + SharpSoundDevice::IAudioDevice^ dev = SharpSoundDevice::Interop::GetDevice(pluginSenderId); + vstHost->sizeWindow(dev->DeviceInfo.EditorWidth, dev->DeviceInfo.EditorHeight); + } + } + catch (Exception^ e) + { + SharpSoundDevice::Logging::LogDeviceException(pluginSenderId, e); + } + } + + double HostInfoClass::BPM::get() + { + VstTimeInfo* info = vstHost->getTimeInfo(kVstTempoValid); + return info->tempo; + } + + double HostInfoClass::SamplePosition::get() + { + VstTimeInfo* info = vstHost->getTimeInfo(0); + return info->samplePos; + } + + double HostInfoClass::SampleRate::get() + { + double fs = vstHost->Samplerate; + if (fs > 0) + { + return fs; + } + else + { + VstTimeInfo* info = vstHost->getTimeInfo(0); + return info->sampleRate; + } + } + + int HostInfoClass::BlockSize::get() + { + int blockSize = vstHost->getBlockSize(); + return blockSize; + } + + int HostInfoClass::TimeSignatureNum::get() + { + VstTimeInfo* info = vstHost->getTimeInfo(kVstTempoValid); + return info->timeSigNumerator; + } + + int HostInfoClass::TimeSignatureDen::get() + { + VstTimeInfo* info = vstHost->getTimeInfo(kVstTempoValid); + return info->timeSigDenominator; + } + + System::String^ HostInfoClass::HostVendor::get() + { + vstHost->getHostVendorString(HostVendorPtr); + return gcnew System::String(HostVendorPtr); + } + + System::String^ HostInfoClass::HostName::get() + { + vstHost->getHostProductString(HostNamePtr); + return gcnew String(HostNamePtr); + } + + unsigned int HostInfoClass::HostVersion::get() + { + unsigned int version = vstHost->getHostVendorVersion(); + return version; + } + } +} diff --git a/pool/shard007/C++/0095086_AC_PrecLand_IRLock.cpp b/pool/shard007/C++/0095086_AC_PrecLand_IRLock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f0fac086fb8f21d497e6ac6d8d73791f2df92759 --- /dev/null +++ b/pool/shard007/C++/0095086_AC_PrecLand_IRLock.cpp @@ -0,0 +1,62 @@ +/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- +#include <AP_HAL/AP_HAL.h> +#include "AC_PrecLand_IRLock.h" + +extern const AP_HAL::HAL& hal; + +// this only builds for PX4 so far +#if CONFIG_HAL_BOARD == HAL_BOARD_PX4 || CONFIG_HAL_BOARD == HAL_BOARD_VRBRAIN || CONFIG_HAL_BOARD == HAL_BOARD_SITL + +// Constructor +AC_PrecLand_IRLock::AC_PrecLand_IRLock(const AC_PrecLand& frontend, AC_PrecLand::precland_state& state) + : AC_PrecLand_Backend(frontend, state), + irlock(), + _have_los_meas(false), + _los_meas_time_ms(0) +{ +} + +// init - perform initialisation of this backend +void AC_PrecLand_IRLock::init() +{ + irlock.init(); +} + +// update - give chance to driver to get updates from sensor +void AC_PrecLand_IRLock::update() +{ + // update health + _state.healthy = irlock.healthy(); + + // get new sensor data + irlock.update(); + + if (irlock.num_targets() > 0 && irlock.last_update_ms() != _los_meas_time_ms) { + irlock.get_unit_vector_body(_los_meas_body); + _have_los_meas = true; + _los_meas_time_ms = irlock.last_update_ms(); + } + _have_los_meas = _have_los_meas && AP_HAL::millis()-_los_meas_time_ms <= 1000; +} + +// provides a unit vector towards the target in body frame +// returns same as have_los_meas() +bool AC_PrecLand_IRLock::get_los_body(Vector3f& ret) { + if (have_los_meas()) { + ret = _los_meas_body; + return true; + } + return false; +} + +// returns system time in milliseconds of last los measurement +uint32_t AC_PrecLand_IRLock::los_meas_time_ms() { + return _los_meas_time_ms; +} + +// return true if there is a valid los measurement available +bool AC_PrecLand_IRLock::have_los_meas() { + return _have_los_meas; +} + +#endif // PX4 diff --git a/pool/shard007/C++/0095087_Indices.cpp b/pool/shard007/C++/0095087_Indices.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c1cfb5a76355af6239b0dc4724a710f67886ad84 --- /dev/null +++ b/pool/shard007/C++/0095087_Indices.cpp @@ -0,0 +1,166 @@ +#include <iostream> +#include <seqan/index.h> +#include <seqan/align.h> + +using namespace seqan; + + + +template <typename TStringSet, typename TIndexSpec> +void qgramCounting(TStringSet &set, TIndexSpec) +{ + typedef Index<TStringSet, TIndexSpec> TIndex; + typedef typename Fibre<TIndex, QGramCounts>::Type TCounts; + typedef typename Fibre<TIndex, QGramCountsDir>::Type TCountsDir; + typedef typename Value<TCountsDir>::Type TDirValue; + typedef typename Iterator<TCounts, Standard>::Type TIterCounts; + typedef typename Iterator<TCountsDir, Standard>::Type TIterCountsDir; + TIndex index(set); + indexRequire(index, QGramCounts()); + // initialize distance matrix + int seqNum = countSequences(index); + Matrix<int, 2> distMat; + setLength(distMat, 0, seqNum); + setLength(distMat, 1, seqNum); + resize(distMat, 0); + std::cout << std::endl << "Length of the CountsDir fibre: " << length(indexCountsDir(index)) << std::endl; + TIterCountsDir itCountsDir = begin(indexCountsDir(index), Standard()); + TIterCountsDir itCountsDirEnd = end(indexCountsDir(index), Standard()); + TIterCounts itCountsBegin = begin(indexCounts(index), Standard()); + + // for each bucket count common q-grams for each sequence pair + TDirValue bucketBegin = *itCountsDir; + for(++itCountsDir; itCountsDir != itCountsDirEnd; ++itCountsDir) + { + TDirValue bucketEnd = *itCountsDir; + // q-gram must occur in at least 2 different sequences + if (bucketBegin != bucketEnd) + { + TIterCounts itA = itCountsBegin + bucketBegin; + TIterCounts itEnd = itCountsBegin + bucketEnd; + for(; itA != itEnd; ++itA) + for(TIterCounts itB = itA; itB != itEnd; ++itB) + distMat((*itA).i1, (*itB).i1) += _min((*itA).i2, (*itB).i2); + } + bucketBegin = bucketEnd; + } + std::cout << std::endl << "Common 5-mers for Seq_i, Seq_j" << std::endl; + std::cout << distMat; +} + + + + + + +int main (){ + + //String<char> myString = "abracadabra"; + // typedef Index< String<char> > TMyIndex; + // TMyIndex myIndex(myString); + + //Iterator< TMyIndex, TopDown< ParentLinks<Preorder> > >::Type myIterator(myIndex); + // while (!atEnd(myIterator)) + // { + // std::cout << representative(myIterator) << std::endl; + // ++myIterator; + // } + + //typedef String<char> TString; + //StringSet<TString> seq; + //appendValue(seq,"tobeornottobe"); + //appendValue(seq,"thebeeonthecomb"); + //appendValue(seq,"beingjohnmalkovich"); + + //typedef Index< StringSet<TString> > TMyIndex; + //TMyIndex myIndex(seq); + + //Iterator< TMyIndex, BottomUp<>>::Type myIterator(myIndex); + //while (!atEnd(myIterator)) + // { + // std::cout << representative(myIterator) << std::endl; + // ++myIterator; + // } + + //typedef String<char> TString; + //StringSet<TString> seq; + //appendValue(seq,"CDFGHC"); + //appendValue(seq,"CDEFGAHC"); + + //typedef Index< StringSet<TString> > TMyIndex; + //TMyIndex myIndex(seq); + + //Iterator< TMyIndex, Mums >::Type myIterator(myIndex); + // while (!atEnd(myIterator)) + // { + // std::cout << representative(myIterator) << std::endl; + // ++myIterator; + // } + + + + + //typedef String<char> TString; + //TString seq = "tobeornottobe"; + + //typedef Index<TString> TIndex; + //TIndex myIndex(seq); + //Iterator<TIndex, TopDown<ParentLinks<> > >::Type it(myIndex); + //bool a= true; + //while(a){ + // + // + // if(goDown(it)){ + // ::std::cout<<representative(it)<<std::endl; + // + // } + // else{ + // if(goRight(it)) + // ::std::cout<<representative(it)<<std::endl; + // else{ + // while(goUp(it)){ + // if(goRight(it)){ + // ::std::cout<<representative(it)<<std::endl; + // break; + // } + // a=false; + + // } + // } + // } + //} + + + + + //typedef Index<DnaString, IndexQGram< OneGappedShape > > TIndex;//da gap erst noch stringToShape + //TIndex index("CATGATTACATA"); + //stringToShape(indexShape(index),"1101"); + //hash(indexShape(index),"AT-A"); + //for(unsigned int i =0; i < length(getOccurrences(index, indexShape(index)));++i) + // std::cout<<getOccurrences(index, indexShape(index))[i]<<std::endl; + + + // for the sake of reproducibility + Rng<MersenneTwister> rng; + // create StringSet of 3 random sequences + StringSet<DnaString> stringSet; + reserve(stringSet, 3); + for (int seqNo = 0; seqNo < 3; ++seqNo) + { + DnaString tmp; + int len = pickRandomNumber(rng) % 100 + 10; + for (int i = 0; i < len; ++i) + appendValue(tmp, Dna(pickRandomNumber(rng) % 4)); + appendValue(stringSet, tmp); + std::cout << ">Seq" << seqNo << std::endl << tmp << std::endl; + } + qgramCounting(stringSet, IndexQGram<UngappedShape<5> >()); + qgramCounting(stringSet, IndexQGram<UngappedShape<5>, OpenAddressing>()); + + + + + return 0; + +} \ No newline at end of file diff --git a/pool/shard007/C++/0095089_lua_fileops.cpp b/pool/shard007/C++/0095089_lua_fileops.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6f38071eb89ffca9853ca4a21ea4b98b78aaec10 --- /dev/null +++ b/pool/shard007/C++/0095089_lua_fileops.cpp @@ -0,0 +1,276 @@ +/* + Copyright (C) 2014 - 2018 by Chris Beck <render787@gmail.com> + Part of the Battle for Wesnoth Project https://www.wesnoth.org/ + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY. + + See the COPYING file for more details. +*/ + +#include "scripting/lua_fileops.hpp" + +#include "filesystem.hpp" +#include "game_config.hpp" //for game_config::debug_lua +#include "game_errors.hpp" +#include "log.hpp" +#include "scripting/lua_common.hpp" // for chat_message, luaW_pcall +#include "scripting/push_check.hpp" + +#include <algorithm> +#include <exception> +#include <string> + +#include <boost/algorithm/string/predicate.hpp> + +#include "lua/lauxlib.h" +#include "lua/lua.h" +#include "lua/luaconf.h" // for LUAL_BUFFERSIZE + +static lg::log_domain log_scripting_lua("scripting/lua"); +#define DBG_LUA LOG_STREAM(debug, log_scripting_lua) +#define LOG_LUA LOG_STREAM(info, log_scripting_lua) +#define WRN_LUA LOG_STREAM(warn, log_scripting_lua) +#define ERR_LUA LOG_STREAM(err, log_scripting_lua) + +namespace lua_fileops { +static std::string get_calling_file(lua_State* L) +{ + std::string currentdir; + lua_Debug ar; + if(lua_getstack(L, 1, &ar)) { + lua_getinfo(L, "S", &ar); + if(ar.source[0] == '@') { + std::string calling_file(ar.source + 1); + for(int stack_pos = 2; calling_file == "lua/package.lua"; stack_pos++) { + if(!lua_getstack(L, stack_pos, &ar)) { + return currentdir; + } + lua_getinfo(L, "S", &ar); + if(ar.source[0] == '@') { + calling_file.assign(ar.source + 1); + } + } + currentdir = filesystem::directory_name(calling_file); + } + } + return currentdir; +} +/// resolves @a filename to an absolute path +/// @returns true if the filename was successfully resolved. +static bool canonical_path(std::string& filename, const std::string& currentdir) +{ + if(filename.size() < 2) { + return false; + } + if(filename[0] == '.' && filename[1] == '/') { + filename = currentdir + filename.substr(1); + } + if(std::find(filename.begin(), filename.end(), '\\') != filename.end()) { + return false; + } + //resolve /./ + while(true) { + std::size_t pos = filename.find("/./"); + if(pos == std::string::npos) { + break; + } + filename = filename.replace(pos, 2, ""); + } + //resolve // + while(true) { + std::size_t pos = filename.find("//"); + if(pos == std::string::npos) { + break; + } + filename = filename.replace(pos, 1, ""); + } + //resolve /../ + while(true) { + std::size_t pos = filename.find("/.."); + if(pos == std::string::npos) { + break; + } + std::size_t pos2 = filename.find_last_of('/', pos - 1); + if(pos2 == std::string::npos || pos2 >= pos) { + return false; + } + filename = filename.replace(pos2, pos- pos2 + 3, ""); + } + if(filename.find("..") != std::string::npos) { + return false; + } + return true; +} + +/// resolves @a filename to an absolute path +/// @returns true if the filename was successfully resolved. +static bool resolve_filename(std::string& filename, const std::string& currentdir, std::string* rel = nullptr) +{ + if(!canonical_path(filename, currentdir)) { + return false; + } + std::string p = filesystem::get_wml_location(filename); + if(p.empty()) { + return false; + } + if(rel) { + *rel = filename; + } + filename = p; + return true; +} + +int intf_canonical_path(lua_State *L) +{ + std::string m = luaL_checkstring(L, 1); + if(canonical_path(m, get_calling_file(L))) { + lua_push(L, m); + return 1; + } else { + return luaL_argerror(L, 1, "invalid path"); + } +} +/** + * Checks if a file exists (not necessarily a Lua script). + * - Arg 1: string containing the file name. + * - Arg 2: if true, the file must be a real file and not a directory + * - Ret 1: boolean + */ +int intf_have_file(lua_State *L) +{ + std::string m = luaL_checkstring(L, 1); + if(!resolve_filename(m, get_calling_file(L))) { + lua_pushboolean(L, false); + } else if(luaW_toboolean(L, 2)) { + lua_pushboolean(L, !filesystem::is_directory(m)); + } else { + lua_pushboolean(L, true); + } + return 1; +} + +/** + * Reads a file into a string, or a directory into a list of files therein. + * - Arg 1: string containing the file name. + * - Ret 1: string + */ +int intf_read_file(lua_State *L) +{ + std::string p = luaL_checkstring(L, 1); + + if(!resolve_filename(p, get_calling_file(L))) { + return luaL_argerror(L, -1, "file not found"); + } + + if(filesystem::is_directory(p)) { + std::vector<std::string> files, dirs; + filesystem::get_files_in_dir(p, &files, &dirs); + filesystem::default_blacklist.remove_blacklisted_files_and_dirs(files, dirs); + std::size_t ndirs = dirs.size(); + std::copy(files.begin(), files.end(), std::back_inserter(dirs)); + lua_push(L, dirs); + lua_pushnumber(L, ndirs); + lua_setfield(L, -2, "ndirs"); + return 1; + } + const std::unique_ptr<std::istream> fs(filesystem::istream_file(p)); + fs->exceptions(std::ios_base::goodbit); + std::size_t size = 0; + fs->seekg(0, std::ios::end); + if(!fs->good()) { + return luaL_error(L, "Error when reading file"); + } + size = fs->tellg(); + fs->seekg(0, std::ios::beg); + if(!fs->good()) { + return luaL_error(L, "Error when reading file"); + } + luaL_Buffer b; + luaL_buffinit(L, &b); + //throws an exception if malloc failed. + char* out = luaL_prepbuffsize(&b, size); + fs->read(out, size); + if(fs->good()) { + luaL_addsize(&b, size); + } + luaL_pushresult(&b); + return 1; +} + +class lua_filestream +{ +public: + lua_filestream(const std::string& fname) + : buff_() + , pistream_(filesystem::istream_file(fname)) + { + + } + + static const char * lua_read_data(lua_State * /*L*/, void *data, std::size_t *size) + { + lua_filestream* lfs = static_cast<lua_filestream*>(data); + + //int startpos = lfs->pistream_->tellg(); + lfs->pistream_->read(lfs->buff_, LUAL_BUFFERSIZE); + //int newpos = lfs->pistream_->tellg(); + *size = lfs->pistream_->gcount(); +#if 0 + ERR_LUA << "read bytes from " << startpos << " to " << newpos << " in total " *size << " from steam\n"; + ERR_LUA << "streamstate being " + << " goodbit:" << lfs->pistream_->good() + << " endoffile:" << lfs->pistream_->eof() + << " badbit:" << lfs->pistream_->bad() + << " failbit:" << lfs->pistream_->fail() << "\n"; +#endif + return lfs->buff_; + } + + static int lua_loadfile(lua_State *L, const std::string& fname, const std::string& relativename) + { + lua_filestream lfs(fname); + //lua uses '@' to know that this is a file (as opposed to something loaded via loadstring ) + std::string chunkname = '@' + relativename; + LOG_LUA << "starting to read from " << fname << "\n"; + return lua_load(L, &lua_filestream::lua_read_data, &lfs, chunkname.c_str(), "t"); + } +private: + char buff_[LUAL_BUFFERSIZE]; + const std::unique_ptr<std::istream> pistream_; +}; + +/** + * Loads a Lua file and pushes the contents on the stack. + * - Arg 1: string containing the file name. + * - Ret 1: the loaded contents of the file + */ +int load_file(lua_State *L) +{ + std::string p = luaL_checkstring(L, -1); + std::string rel; + + if(!resolve_filename(p, get_calling_file(L), &rel)) { + return luaL_argerror(L, -1, "file not found"); + } + + try + { + if(lua_filestream::lua_loadfile(L, p, rel)) { + return lua_error(L); + } + } + catch(const std::exception & ex) + { + luaL_argerror(L, -1, ex.what()); + } + lua_remove(L, -2); //remove the filename from the stack + + return 1; +} + +} // end namespace lua_fileops diff --git a/pool/shard007/C++/0095090_scoped_allocator_mgr.cc b/pool/shard007/C++/0095090_scoped_allocator_mgr.cc new file mode 100644 index 0000000000000000000000000000000000000000..be79cc4507124fbbef8104f87773045c07005ef6 --- /dev/null +++ b/pool/shard007/C++/0095090_scoped_allocator_mgr.cc @@ -0,0 +1,185 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#include "tensorflow/core/common_runtime/scoped_allocator_mgr.h" + +#include "tensorflow/core/common_runtime/scoped_allocator.h" +#include "tensorflow/core/framework/allocator.h" + +namespace tensorflow { + +Status ScopedAllocatorContainer::AddScopedAllocator( + const Tensor& backing_tensor, int32 scope_id, const string& scope_name, + const gtl::ArraySlice<ScopedAllocator::Field>& fields, + int32 expected_call_count) { + VLOG(1) << "AddScopedAllocator " << mgr_->device_name() + << " step_id_=" << step_id_ << " scope_id=" << scope_id; + mutex_lock l(mu_); + // Ensure none of the new scope_ids are in use. + auto it = allocators_.find(scope_id); + if (it != allocators_.end()) { + return errors::Internal("Cannot create ScopedAllocator because scope_id ", + scope_id, " for name ", scope_name, + " already exists"); + } + for (auto& f : fields) { + if (allocators_.find(f.scope_id) != allocators_.end()) { + return errors::Internal( + "Cannot create ScopedAllocator because field scope_id ", f.scope_id, + " for name ", scope_name, " already exists"); + } + } + VLOG(2) << " container " << this << " step_id " << step_id_; + ScopedAllocator* sa = new ScopedAllocator( + backing_tensor, scope_id, scope_name, fields, expected_call_count, this); + allocators_[scope_id] = + ScopedAllocatorContainer::SAField(ScopedAllocator::kBackingIndex, sa); + VLOG(2) << "#fields " << fields.size(); + for (int i = 0; i < fields.size(); ++i) { + const ScopedAllocator::Field& f = fields[i]; + VLOG(2) << "Adding instance with for " << mgr_->device_name() + << " scope_id=" << f.scope_id; + allocators_[f.scope_id] = ScopedAllocatorContainer::SAField( + i, new ScopedAllocatorInstance(sa, i)); + } + return Status::OK(); +} + +ScopedAllocator* ScopedAllocatorContainer::GetAllocator(int32 scope_id) { + mutex_lock l(mu_); + auto it = allocators_.find(scope_id); + if (it != allocators_.end()) { + CHECK_EQ(ScopedAllocator::kBackingIndex, it->second.field_index); + return it->second.scoped_allocator; + } else { + LOG(ERROR) << "Failed to find ScopedAllocator for " << scope_id + << " in container for step " << step_id_ << " on " + << mgr_->device_name(); + return nullptr; + } +} + +ScopedAllocatorInstance* ScopedAllocatorContainer::GetInstance(int32 scope_id) { + VLOG(2) << "GetInstance " << scope_id << " step " << step_id_ << " on " + << mgr_->device_name(); + mutex_lock l(mu_); + auto it = allocators_.find(scope_id); + if (it != allocators_.end()) { + return it->second.instance; + } + LOG(FATAL) << "Failed to find instance " << scope_id << " in container " + << step_id_ << " on " << mgr_->device_name(); + return nullptr; +} + +void ScopedAllocatorContainer::Drop(int32 scope_id, ScopedAllocator* sa) { + VLOG(2) << "Drop " << scope_id << " from container " << this << " step " + << step_id_ << " on " << mgr_->device_name(); + mutex_lock l(mu_); + auto it = allocators_.find(scope_id); + if (it != allocators_.end()) { + if (it->second.field_index != ScopedAllocator::kBackingIndex) { + it->second.instance->DropFromTable(); + } + allocators_.erase(it); + } +} + +ScopedAllocatorContainer::~ScopedAllocatorContainer() { + VLOG(2) << "~ScopedAllocatorContainer " << this << " step " << step_id_ + << " on " << mgr_->device_name(); + mutex_lock l(mu_); + // In normal execution the table should be empty and all of its + // contents deleted via Drop. When when a step ends early + // (e.g. through abnormal termination) we need to clean up + // explicitly. So long as graph execution of the associated step has + // completey terminated this should be safe. + for (auto& it : allocators_) { + if (it.second.field_index == ScopedAllocator::kBackingIndex) { + delete it.second.scoped_allocator; + } else { + it.second.instance->DropFromTable(); + } + } +} + +ScopedAllocatorMgr::~ScopedAllocatorMgr() { + mutex_lock l(mu_); + for (auto it : per_step_map_) { + // In normal execution the associated ScopedAllocatorContainer is + // empty and gone by the end of the step. But in abnormal termination, + // such as when an error has interrupted execution or in a unittest, + // we need to remove all of its Refs here to avoid memory leaks. + // This is safe so long as graph execution has ceased. + while (!it.second->Unref()) { + } + } +} + +void ScopedAllocatorMgr::Cleanup(int64 step_id) { + mutex_lock l(mu_); + auto it = per_step_map_.find(step_id); + if (it != per_step_map_.end()) { + it->second->Unref(); + per_step_map_.erase(it); + } +} + +ScopedAllocatorContainer* ScopedAllocatorMgr::GetContainer(int64 step_id) { + VLOG(2) << "GetContainer " << step_id << " on " << device_name(); + ScopedAllocatorContainer* sac = nullptr; + mutex_lock l(mu_); + auto it = per_step_map_.find(step_id); + if (it == per_step_map_.end()) { + sac = new ScopedAllocatorContainer(this, step_id); + per_step_map_[step_id] = sac; + } else { + sac = it->second; + } + return sac; +} + +Status ScopedAllocatorMgr::AddScopedAllocator( + const Tensor& backing_tensor, int64 step_id, int32 scope_id, + const string& scope_name, + const gtl::ArraySlice<ScopedAllocator::Field>& fields, + int32 expected_call_count) { + ScopedAllocatorContainer* sac = GetContainer(step_id); + return sac->AddScopedAllocator(backing_tensor, scope_id, scope_name, fields, + expected_call_count); +} + +void ScopedAllocatorMgr::PopulateFields( + int32 scope_id, const gtl::ArraySlice<TensorShape>& shapes, + const DataType dtype, std::vector<ScopedAllocator::Field>* fields) { + const int32 num_fields = static_cast<int32>(shapes.size()); + fields->resize(num_fields); + size_t offset = 0; + for (int32 i = 0; i < num_fields; ++i) { + size_t bytes = shapes[i].num_elements() * DataTypeSize(dtype); + (*fields)[i].scope_id = scope_id + 1 + i; + (*fields)[i].bytes = bytes; + (*fields)[i].offset = offset; + VLOG(1) << "field=" << i << " scope_id=" << (*fields)[i].scope_id + << " bytes=" << (*fields)[i].bytes + << " offset=" << (*fields)[i].offset; + offset += bytes; + size_t overshoot = offset % Allocator::kAllocatorAlignment; + if (overshoot > 0) { + offset += (Allocator::kAllocatorAlignment - overshoot); + } + } +} + +} // namespace tensorflow diff --git a/pool/shard007/C++/0095093_abstractscannode.cpp b/pool/shard007/C++/0095093_abstractscannode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8d805889605a4b451c161464f58ea28e56acf83f --- /dev/null +++ b/pool/shard007/C++/0095093_abstractscannode.cpp @@ -0,0 +1,218 @@ +/* This file is part of VoltDB. + * Copyright (C) 2008-2010 VoltDB L.L.C. + * + * This file contains original code and/or modifications of original code. + * Any modifications made by VoltDB L.L.C. are licensed under the following + * terms and conditions: + * + * VoltDB is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VoltDB is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. + */ +/* Copyright (C) 2008 by H-Store Project + * Brown University + * Massachusetts Institute of Technology + * Yale University + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +#include "abstractscannode.h" + +#include "PlanColumn.h" +#include "storage/table.h" +#include "catalog/table.h" +#include "catalog/column.h" + +using namespace json_spirit; +using namespace std; +using namespace voltdb; + +AbstractScanPlanNode::AbstractScanPlanNode(int32_t id) + : AbstractPlanNode(id), m_predicate(NULL) +{ + m_targetTable = NULL; +} + +AbstractScanPlanNode::AbstractScanPlanNode() + : AbstractPlanNode(), m_predicate(NULL) +{ + m_targetTable = NULL; +} + +AbstractScanPlanNode::~AbstractScanPlanNode() +{ + delete m_predicate; +} + +void +AbstractScanPlanNode::setPredicate(AbstractExpression* predicate) +{ + assert(!m_predicate); + if (m_predicate != predicate) + { + delete m_predicate; + } + m_predicate = predicate; +} + +AbstractExpression* +AbstractScanPlanNode::getPredicate() const +{ + return m_predicate; +} + +Table* +AbstractScanPlanNode::getTargetTable() const +{ + return m_targetTable; +} + +void +AbstractScanPlanNode::setTargetTable(Table* table) +{ + m_targetTable = table; +} + +string +AbstractScanPlanNode::getTargetTableName() const +{ + return m_targetTableName; +} + +void +AbstractScanPlanNode::setTargetTableName(string table_name) +{ + m_targetTableName = table_name; +} + +string +AbstractScanPlanNode::debugInfo(const string &spacer) const +{ + ostringstream buffer; + buffer << spacer << "TargetTable[" << m_targetTableName << "]\n"; + buffer << spacer << "OutputColumns[" << m_outputColumnGuids.size() + << "]:\n"; + for (int ctr = 0, cnt = (int) m_outputColumnGuids.size(); + ctr < cnt; ctr++) + { + buffer << spacer << " [" << ctr << "] " + << m_outputColumnGuids[ctr] << "\n"; + } + return buffer.str(); +} + +int +AbstractScanPlanNode::getColumnIndexFromName(string name, + const catalog::Database* db) const +{ + catalog::Table* table = db->tables().get(m_targetTableName); + assert (table != NULL); + if (NULL == table) + { + return -1; + } + + catalog::CatalogMap<catalog::Column> columns = table->columns(); + catalog::Column* column = columns.get(name); + assert (NULL != column); + if (NULL == column) + { + return -1; + } + return column->index(); +} + +int +AbstractScanPlanNode::getColumnIndexFromGuid(int guid, + const catalog::Database* db) const +{ + // if the scan node has an inlined projection, then we + // want to look up the column index in the projection + AbstractPlanNode* projection = + getInlinePlanNode(PLAN_NODE_TYPE_PROJECTION); + if (projection != NULL) + { + return projection->getColumnIndexFromGuid(guid, db); + } + else + { + string name = ""; + for (int i = 0; i < m_outputColumnGuids.size(); i++) + { + if (guid == m_outputColumnGuids[i]) + { + return getColumnIndexFromName(m_outputColumnNames[i], db); + } + } + } + return -1; +} + +void +AbstractScanPlanNode::loadFromJSONObject(json_spirit::Object& obj, + const catalog::Database* catalog_db) +{ + Value outputColumnsValue = find_value(obj, "OUTPUT_COLUMNS"); + if (outputColumnsValue == Value::null) + { + throw SerializableEEException(VOLT_EE_EXCEPTION_TYPE_EEEXCEPTION, + "AbstractScanPlanNode::loadFromJSONObject:" + " Can't find OUTPUT_COLUMNS value"); + } + Array outputColumnsArray = outputColumnsValue.get_array(); + + for (int ii = 0; ii < outputColumnsArray.size(); ii++) + { + Value outputColumnValue = outputColumnsArray[ii]; + PlanColumn outputColumn = PlanColumn(outputColumnValue.get_obj()); + m_outputColumnGuids.push_back(outputColumn.getGuid()); + m_outputColumnNames.push_back(outputColumn.getName()); + m_outputColumnTypes.push_back(outputColumn.getType()); + m_outputColumnSizes.push_back(outputColumn.getSize()); + } + + json_spirit::Value targetTableNameValue = + json_spirit::find_value(obj, "TARGET_TABLE_NAME"); + if (targetTableNameValue == json_spirit::Value::null) + { + throw SerializableEEException(VOLT_EE_EXCEPTION_TYPE_EEEXCEPTION, + "AbstractScanPlanNode::loadFromJSONObject:" + " Couldn't find TARGET_TABLE_NAME value"); + } + + m_targetTableName = targetTableNameValue.get_str(); + + json_spirit::Value predicateValue = json_spirit::find_value(obj, "PREDICATE"); + if (!(predicateValue == json_spirit::Value::null)) + { + json_spirit::Object predicateObject = predicateValue.get_obj(); + m_predicate = AbstractExpression::buildExpressionTree(predicateObject); + } +} diff --git a/pool/shard007/C++/0095094_Q_circlecol_test.cpp b/pool/shard007/C++/0095094_Q_circlecol_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..93873e136bbb5794aae8b07169b7837545aec7e0 --- /dev/null +++ b/pool/shard007/C++/0095094_Q_circlecol_test.cpp @@ -0,0 +1,67 @@ +/* + Copyright 2016 Ahnaf Siddiqui + + 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 "Q_TestBody.h" +#include "Q_CircleCollider.h" + + +TEST(CircleColTest, OnCollides) { + Quantum2D::BodyList blist; + blist.emplace_back(); + blist.emplace_back(); + std::string name1("Harry"); + std::string name2("Hagrid"); + + QTest::TestBody<Quantum2D::CircleCollider> body1(blist, name1, 0, 1); + QTest::TestBody<Quantum2D::CircleCollider> body2(blist, name2, 1, 1); + + body1.checkInit(body1.name); + body2.checkInit(body2.name); + + body1.mCol->onCollide(body2.mCol); + body2.mCol->onCollide(body1.mCol); + + ASSERT_NE(body1.other, nullptr); + ASSERT_NE(body2.other, nullptr); + + EXPECT_EQ(body1.other->name, body2.name); + EXPECT_EQ(body2.other->name, body1.name); +} + +TEST(CircleColTest, Updates) { + using namespace Diamond; + Quantum2D::BodyList blist; + blist.emplace_back(); + tQ_pos radius = 3; + Vector2<tQ_num> center(2, 2); + + QTest::TestBody<Quantum2D::CircleCollider> harry(blist, "Harry", 0, radius, center); + + harry.checkInit("Harry"); + + ASSERT_EQ(harry.mCol->getRadius(), radius); + ASSERT_EQ(harry.mCol->getCenter(), center); + + Vector2<tQ_num> curpos(5, 5); + harry.getBody().setPosition(curpos); + harry.mCol->update(1); + EXPECT_EQ(harry.mCol->getWorldPos(), curpos + center); + + curpos.set(15, 15); + harry.getBody().setPosition(curpos); + harry.mCol->update(1); + EXPECT_EQ(harry.mCol->getWorldPos(), curpos + center); +} diff --git a/pool/shard007/C++/0095096_floating_textbox.cpp b/pool/shard007/C++/0095096_floating_textbox.cpp new file mode 100644 index 0000000000000000000000000000000000000000..310e791d98b3ee6b73d26bcefeb54be67f497203 --- /dev/null +++ b/pool/shard007/C++/0095096_floating_textbox.cpp @@ -0,0 +1,164 @@ +/* $Id: floating_textbox.cpp 31859 2009-01-01 10:28:26Z mordante $ */ +/* + Copyright (C) 2006 - 2009 by Joerg Hinrichs <joerg.hinrichs@alice-dsl.de> + wesnoth playturn Copyright (C) 2003 by David White <dave@whitevine.net> + Part of the Battle for Wesnoth Project http://www.wesnoth.org/ + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License version 2 + or at your option any later version. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY. + + See the COPYING file for more details. +*/ + +#include "global.hpp" + +#include "floating_textbox.hpp" +#include "game_display.hpp" +#include "game_preferences.hpp" +#include "log.hpp" + +#include <ctime> + +namespace gui{ + floating_textbox::floating_textbox() : + box_(NULL), + check_(NULL), + mode_(TEXTBOX_NONE), + label_string_(), + label_(0) + {} + + void floating_textbox::close(game_display& gui) + { + if(!active()) { + return; + } + if(check_ != NULL) { + if(mode_ == TEXTBOX_MESSAGE) { + preferences::set_message_private(check_->checked()); + } + } + box_.assign(NULL); + check_.assign(NULL); + font::remove_floating_label(label_); + mode_ = TEXTBOX_NONE; + gui.invalidate_all(); + } + + void floating_textbox::update_location(game_display& gui) + { + if (box_ == NULL) + return; + + const SDL_Rect& area = gui.map_outside_area(); + + const int border_size = 10; + + const int ypos = area.y+area.h-30 - (check_ != NULL ? check_->height() + border_size : 0); + + if (label_ != 0) + font::remove_floating_label(label_); + + label_ = font::add_floating_label(label_string_,font::SIZE_NORMAL, + font::YELLOW_COLOUR,area.x+border_size,ypos,0,0,-1, area,font::LEFT_ALIGN); + + if (label_ == 0) + return; + + const SDL_Rect& label_area = font::get_floating_label_rect(label_); + const int textbox_width = area.w - label_area.w - border_size*3; + + if(textbox_width <= 0) { + font::remove_floating_label(label_); + return; + } + + if(box_ != NULL) { + box_->set_volatile(true); + const SDL_Rect rect = { + area.x + label_area.w + border_size*2, ypos, + textbox_width, box_->height() + }; + box_->set_location(rect); + } + + if(check_ != NULL) { + check_->set_volatile(true); + check_->set_location(box_->location().x,box_->location().y + box_->location().h + border_size); + } + } + + void floating_textbox::show(gui::TEXTBOX_MODE mode, const std::string& label, + const std::string& check_label, bool checked, game_display& gui) + { + close(gui); + + label_string_ = label; + mode_ = mode; + + if(check_label != "") { + check_.assign(new gui::button(gui.video(),check_label,gui::button::TYPE_CHECK)); + check_->set_check(checked); + } + + + box_.assign(new gui::textbox(gui.video(),100,"",true,256,0.8,0.6)); + + update_location(gui); + } + + void floating_textbox::tab(std::vector<team>& teams, const unit_map& /*units*/, game_display& gui) + { + if(active() == false) { + return; + } + + switch(mode_) { + case gui::TEXTBOX_SEARCH: + case gui::TEXTBOX_COMMAND: + case gui::TEXTBOX_MESSAGE: + { + std::string text = box_->text(); + std::vector<std::string> matches; + // Add players + for(size_t n = 0; n != teams.size(); ++n) { + if(teams[n].is_empty()) continue; + matches.push_back(teams[n].current_player()); + } + // Add observers + const std::set<std::string>& observers = gui.observers(); + for(std::set<std::string>::const_iterator i = observers.begin(); + i != observers.end(); ++i) + { + matches.push_back(*i); + } + // Remove duplicates. + std::sort<std::vector<std::string>::iterator> + (matches.begin(), matches.end()); + matches.erase(std::unique(matches.begin(), matches.end()), matches.end()); + // Exclude own nick from tab-completion. + if (mode_ == gui::TEXTBOX_MESSAGE) { + matches.erase(std::remove(matches.begin(), matches.end(), + preferences::login()), matches.end()); + } + const bool line_start = utils::word_completion(text, matches); + + if (matches.empty()) return; + if (matches.size() == 1 && mode_ == gui::TEXTBOX_MESSAGE) { + text.append(line_start ? ": " : " "); + } else { + std::string completion_list = utils::join(matches, ' '); + gui.add_chat_message(time(NULL), "", 0, completion_list, + game_display::MESSAGE_PRIVATE, false); + } + box_->set_text(text); + break; + } + default: + LOG_STREAM(err, display) << "unknown textbox mode\n"; + } + } +} diff --git a/pool/shard007/C++/0095101_ApplicationSettings.cpp b/pool/shard007/C++/0095101_ApplicationSettings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..733c1a3bfb0eb57bf29eb65311e583f1ca73f028 --- /dev/null +++ b/pool/shard007/C++/0095101_ApplicationSettings.cpp @@ -0,0 +1,67 @@ +#include "ApplicationSettings.h" +// #include "eepromcontrol.h" +#include "MidiStatus.h" +#include "Storage.h" +#include <string.h> + +// #define APPLICATION_SETTINGS_ADDR ADDR_FLASH_SECTOR_1 +// #define APPLICATION_SETTINGS_SECTOR FLASH_Sector_1 + +void ApplicationSettings::init(){ + checksum = sizeof(*this) ^ 0xf0f0f0f0; + if(settingsInFlash()) + loadFromFlash(); + else + reset(); +} + +void ApplicationSettings::reset(){ + audio_codec_swaplr = false; + audio_codec_bypass = false; + audio_samplingrate = AUDIO_SAMPLINGRATE; + audio_bitdepth = AUDIO_BITDEPTH; + audio_dataformat = AUDIO_DATAFORMAT; + audio_blocksize = AUDIO_BLOCK_SIZE; + audio_input_gain = AUDIO_INPUT_GAIN; + audio_output_gain = AUDIO_OUTPUT_GAIN; + program_index = DEFAULT_PROGRAM; + program_change_button = true; +#ifdef USE_DIGITALBUS + bus_enabled = DIGITAL_BUS_ENABLED; + bus_forward_midi = DIGITAL_BUS_FORWARD_MIDI; +#endif + input_offset = AUDIO_INPUT_OFFSET; + input_scalar = AUDIO_INPUT_SCALAR; + output_offset = AUDIO_OUTPUT_OFFSET; + output_scalar = AUDIO_OUTPUT_SCALAR; + midi_input_channel = MIDI_INPUT_CHANNEL; + midi_output_channel = MIDI_OUTPUT_CHANNEL; +#ifdef USE_TLC5946 + leds_brightness = LEDS_BRIGHTNESS; +#endif +#ifdef OWL_PEDAL + expression_mode = EXPRESSION_MODE; +#endif +} + +bool ApplicationSettings::settingsInFlash(){ + Resource* resource = storage.getResourceByName(APPLICATION_SETTINGS_NAME); + if(resource && resource->isMemoryMapped()){ + ApplicationSettings* data = (ApplicationSettings*)resource->getData(); + return data->checksum == checksum; + } + return false; +} + +void ApplicationSettings::loadFromFlash(){ + Resource* resource = storage.getResourceByName(APPLICATION_SETTINGS_NAME); + if(resource) + storage.readResource(resource, this, 0, sizeof(*this)); +} + +void ApplicationSettings::saveToFlash(){ + uint16_t totalsize = sizeof(ResourceHeader) + sizeof(*this); + uint8_t buffer[totalsize]; + memcpy(buffer+sizeof(ResourceHeader), this, sizeof(*this)); + storage.writeResource(APPLICATION_SETTINGS_NAME, buffer, sizeof(*this), RESOURCE_SYSTEM_RESOURCE|RESOURCE_MEMORY_MAPPED); +} diff --git a/pool/shard007/C++/0095103_CohPoint1.cpp b/pool/shard007/C++/0095103_CohPoint1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6e0acc7bbe0cb2ef8135606958abd896f80eb031 --- /dev/null +++ b/pool/shard007/C++/0095103_CohPoint1.cpp @@ -0,0 +1,46 @@ +/* +################################################################################## + + Written by David Brandyberry, University of Illinois at Urbana-Champaign + All rights reserved + Last Updated February 2017 + +################################################################################## +*/ +#include "CohPoint1.h" + + +id_type CohPoint1::n_q_points(int order) const +{ + return 1; +} +void CohPoint1::q_point(std::vector<double>& coords, double& w, id_type qp, int order) const +{ + coords.clear(); + coords.push_back(0.0); + w = 1.0; +} + +double CohPoint1::compute_shape(const std::vector<double>& coords, int n) const +{ + if(n!=0) + err_message("Shape function number for an Edge2 must be 0"); + + return 1.0; +} + +std::vector<double> CohPoint1::compute_shape_grad(const std::vector<double>& coords, int n) const +{ + if(n!=0) + err_message("Shape function number for an Edge2 must be 0"); + + return std::vector<double>(1); +} + +// void CohPoint1::compute_rotation_general(const std::vector<double>& coords, const std::vector<std::vector<double> >& node_coords, +// DenseMatrix<double>& mat, double& dA) const +// { +// mat.resize(1,1); +// mat(0,0) = 1.0; +// dA = 1; // ????????????????????????????????? +// } diff --git a/pool/shard007/C++/0095104_vpn_provider_resource.cc b/pool/shard007/C++/0095104_vpn_provider_resource.cc new file mode 100644 index 0000000000000000000000000000000000000000..ba0b0c1daebbbee66bc1a81811af79af1cb766cb --- /dev/null +++ b/pool/shard007/C++/0095104_vpn_provider_resource.cc @@ -0,0 +1,267 @@ +// Copyright 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 "ppapi/proxy/vpn_provider_resource.h" + +#include <memory> + +#include "base/bind.h" +#include "base/memory/unsafe_shared_memory_region.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/proxy/dispatch_reply_message.h" +#include "ppapi/proxy/ppapi_messages.h" +#include "ppapi/shared_impl/array_var.h" +#include "ppapi/shared_impl/ppapi_globals.h" +#include "ppapi/shared_impl/var_tracker.h" + +namespace ppapi { +namespace proxy { + +VpnProviderResource::VpnProviderResource(Connection connection, + PP_Instance instance) + : PluginResource(connection, instance), + bind_callback_(nullptr), + send_packet_callback_(nullptr), + receive_packet_callback_(nullptr), + receive_packet_callback_var_(nullptr), + bound_(false) { + SendCreate(BROWSER, PpapiHostMsg_VpnProvider_Create()); +} + +VpnProviderResource::~VpnProviderResource() {} + +thunk::PPB_VpnProvider_API* VpnProviderResource::AsPPB_VpnProvider_API() { + return this; +} + +void VpnProviderResource::OnReplyReceived( + const ResourceMessageReplyParams& params, + const IPC::Message& msg) { + PPAPI_BEGIN_MESSAGE_MAP(VpnProviderResource, msg) + PPAPI_DISPATCH_PLUGIN_RESOURCE_CALL(PpapiPluginMsg_VpnProvider_OnUnbind, + OnPluginMsgOnUnbindReceived) + PPAPI_DISPATCH_PLUGIN_RESOURCE_CALL( + PpapiPluginMsg_VpnProvider_OnPacketReceived, + OnPluginMsgOnPacketReceived) + PPAPI_DISPATCH_PLUGIN_RESOURCE_CALL_UNHANDLED( + PluginResource::OnReplyReceived(params, msg)) + PPAPI_END_MESSAGE_MAP() +} + +int32_t VpnProviderResource::Bind( + const PP_Var& configuration_id, + const PP_Var& configuration_name, + const scoped_refptr<TrackedCallback>& callback) { + if (TrackedCallback::IsPending(bind_callback_)) + return PP_ERROR_INPROGRESS; + + StringVar* configuration_id_var = StringVar::FromPPVar(configuration_id); + if (!configuration_id_var) + return PP_ERROR_BADARGUMENT; + StringVar* configuration_name_var = StringVar::FromPPVar(configuration_name); + if (!configuration_name_var) + return PP_ERROR_BADARGUMENT; + + bind_callback_ = callback; + + Call<PpapiPluginMsg_VpnProvider_BindReply>( + BROWSER, + PpapiHostMsg_VpnProvider_Bind(configuration_id_var->value(), + configuration_name_var->value()), + base::BindOnce(&VpnProviderResource::OnPluginMsgBindReply, this)); + + return PP_OK_COMPLETIONPENDING; +} + +int32_t VpnProviderResource::SendPacket( + const PP_Var& packet, + const scoped_refptr<TrackedCallback>& callback) { + if (!bound_) + return PP_ERROR_FAILED; + if (TrackedCallback::IsPending(send_packet_callback_)) + return PP_ERROR_INPROGRESS; + if (!ArrayBufferVar::FromPPVar(packet)) + return PP_ERROR_BADARGUMENT; + + uint32_t id; + if (send_packet_buffer_.get() && send_packet_buffer_->GetAvailable(&id)) { + // Send packet immediately + send_packet_buffer_->SetAvailable(id, false); + return DoSendPacket(packet, id); + } else { + // Packet will be sent later + send_packet_callback_ = callback; + PpapiGlobals::Get()->GetVarTracker()->AddRefVar(packet); + send_packets_.push(packet); + + return PP_OK_COMPLETIONPENDING; + } +} + +int32_t VpnProviderResource::DoSendPacket(const PP_Var& packet, uint32_t id) { + // Convert packet to std::vector<char>, then send it. + scoped_refptr<ArrayBufferVar> packet_arraybuffer = + ArrayBufferVar::FromPPVar(packet); + if (!packet_arraybuffer.get()) + return PP_ERROR_BADARGUMENT; + + uint32_t packet_size = packet_arraybuffer->ByteLength(); + if (packet_size > send_packet_buffer_->max_packet_size()) + return PP_ERROR_MESSAGE_TOO_BIG; + + char* packet_pointer = static_cast<char*>(packet_arraybuffer->Map()); + memcpy(send_packet_buffer_->GetBuffer(id), packet_pointer, packet_size); + packet_arraybuffer->Unmap(); + + Call<PpapiPluginMsg_VpnProvider_SendPacketReply>( + BROWSER, PpapiHostMsg_VpnProvider_SendPacket(packet_size, id), + base::BindOnce(&VpnProviderResource::OnPluginMsgSendPacketReply, this)); + + return PP_OK; +} + +int32_t VpnProviderResource::ReceivePacket( + PP_Var* packet, + const scoped_refptr<TrackedCallback>& callback) { + if (TrackedCallback::IsPending(receive_packet_callback_)) + return PP_ERROR_INPROGRESS; + + // Return previously received packet. + if (!received_packets_.empty()) { + receive_packet_callback_var_ = packet; + WritePacket(); + return PP_OK; + } + + // Or retain packet var and install callback. + receive_packet_callback_var_ = packet; + receive_packet_callback_ = callback; + + return PP_OK_COMPLETIONPENDING; +} + +void VpnProviderResource::OnPluginMsgOnUnbindReceived( + const ResourceMessageReplyParams& params) { + bound_ = false; + + // Cleanup in-flight packets. + while (!received_packets_.empty()) { + received_packets_.pop(); + } + while (!send_packets_.empty()) { + PpapiGlobals::Get()->GetVarTracker()->ReleaseVar(send_packets_.front()); + send_packets_.pop(); + } + + send_packet_buffer_.reset(); + recv_packet_buffer_.reset(); +} + +void VpnProviderResource::OnPluginMsgOnPacketReceived( + const ResourceMessageReplyParams& params, + uint32_t packet_size, + uint32_t id) { + DCHECK_LE(packet_size, recv_packet_buffer_->max_packet_size()); + if (!bound_) { + // Ignore packet and mark shared memory as available + Post(BROWSER, PpapiHostMsg_VpnProvider_OnPacketReceivedReply(id)); + return; + } + + // Append received packet to queue. + void* packet_pointer = recv_packet_buffer_->GetBuffer(id); + scoped_refptr<Var> packet_var( + PpapiGlobals::Get()->GetVarTracker()->MakeArrayBufferVar(packet_size, + packet_pointer)); + received_packets_.push(packet_var); + + // Mark shared memory as available for next packet + Post(BROWSER, PpapiHostMsg_VpnProvider_OnPacketReceivedReply(id)); + + if (!TrackedCallback::IsPending(receive_packet_callback_) || + TrackedCallback::IsScheduledToRun(receive_packet_callback_)) { + return; + } + + scoped_refptr<TrackedCallback> callback; + callback.swap(receive_packet_callback_); + WritePacket(); + callback->Run(PP_OK); +} + +void VpnProviderResource::OnPluginMsgBindReply( + const ResourceMessageReplyParams& params, + uint32_t queue_size, + uint32_t max_packet_size, + int32_t result) { + if (!TrackedCallback::IsPending(bind_callback_)) + return; + + if (params.result() == PP_OK) { + base::UnsafeSharedMemoryRegion send_shm; + base::UnsafeSharedMemoryRegion recv_shm; + params.TakeUnsafeSharedMemoryRegionAtIndex(0, &send_shm); + params.TakeUnsafeSharedMemoryRegionAtIndex(1, &recv_shm); + if (!send_shm.IsValid() || !recv_shm.IsValid()) { + NOTREACHED(); + return; + } + base::WritableSharedMemoryMapping send_mapping = send_shm.Map(); + base::WritableSharedMemoryMapping recv_mapping = recv_shm.Map(); + if (!send_mapping.IsValid() || !recv_mapping.IsValid()) { + NOTREACHED(); + return; + } + + size_t buffer_size = queue_size * max_packet_size; + if (send_shm.GetSize() < buffer_size || recv_shm.GetSize() < buffer_size) { + NOTREACHED(); + return; + } + send_packet_buffer_ = std::make_unique<ppapi::VpnProviderSharedBuffer>( + queue_size, max_packet_size, std::move(send_shm), + std::move(send_mapping)); + recv_packet_buffer_ = std::make_unique<ppapi::VpnProviderSharedBuffer>( + queue_size, max_packet_size, std::move(recv_shm), + std::move(recv_mapping)); + + bound_ = (result == PP_OK); + } + + scoped_refptr<TrackedCallback> callback; + callback.swap(bind_callback_); + callback->Run(params.result() ? params.result() : result); +} + +void VpnProviderResource::OnPluginMsgSendPacketReply( + const ResourceMessageReplyParams& params, + uint32_t id) { + if (!send_packets_.empty() && bound_) { + // Process remaining packets + DoSendPacket(send_packets_.front(), id); + PpapiGlobals::Get()->GetVarTracker()->ReleaseVar(send_packets_.front()); + send_packets_.pop(); + } else { + send_packet_buffer_->SetAvailable(id, true); + + // Available slots - Run callback to process new packets. + if (TrackedCallback::IsPending(send_packet_callback_)) { + scoped_refptr<TrackedCallback> callback; + callback.swap(send_packet_callback_); + callback->Run(PP_OK); + } + } +} + +void VpnProviderResource::WritePacket() { + if (!receive_packet_callback_var_) + return; + + *receive_packet_callback_var_ = received_packets_.front()->GetPPVar(); + received_packets_.pop(); + receive_packet_callback_var_ = nullptr; +} + +} // namespace proxy +} // namespace ppapi