Upload folder using huggingface_hub (part 82)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- pool/shard007/C++/0090774_completion_stub_factory.ccAdded+67
- pool/shard007/C++/0090781_tutorialswidget.cppAdded+219
- pool/shard007/C++/0090784_main.cppAdded+27
- pool/shard007/C++/0090790_MSResponse.cppAdded+161
- pool/shard007/C++/0090805_cameraClient.cppAdded+79
- pool/shard007/C++/0090814_testMicroStats.cppAdded+88
- pool/shard007/C++/0090817_mbed_pinmap_default.cppAdded+109
- pool/shard007/C++/0090835_database.cppAdded+62
- pool/shard007/C++/0090838_main.cppAdded+109
- pool/shard007/C++/0090839_gtype.cppAdded+236
- pool/shard007/C++/0090840_modifyconstraintteacheractivitytagmaxhourscontinuouslyform.cppAdded+129
- pool/shard007/C++/0090846_LoadFrame.ccAdded+107
- pool/shard007/C++/0090851_References.cppAdded+39
- pool/shard007/C++/0090868_cuoidmap.ccAdded+198
- pool/shard007/C++/0090875_SetSourceRequest.cppAdded+216
- pool/shard007/C++/0090876_align_py.cppAdded+99
- pool/shard007/C++/0090877_read.ccAdded+109
- pool/shard007/C++/0090878_file_system_helper.ccAdded+130
- pool/shard007/C++/0090889_LocalizationManager.cppAdded+192
- pool/shard007/C++/0090896_mkl_batch_matmul_op.ccAdded+252
- pool/shard007/C++/0090899_update_data_provider.ccAdded+172
- pool/shard007/C++/0090904_font.cppAdded+84
- pool/shard007/C++/0090905_bazaarsettings.cppAdded+64
- pool/shard007/C++/0090913_dockey.ccAdded+113
- pool/shard007/C++/0090917_chanfix-misc.ccAdded+87
- pool/shard007/C++/0090925_SurfaceTask.cppAdded+63
- pool/shard007/C++/0090928_Config.cppAdded+134
- pool/shard007/C++/0090936_diargimg.ccAdded+209
- pool/shard007/C++/0090940_HTMLMetaCharsetParser.cppAdded+129
- pool/shard007/C++/0090948_razorfen_downs.cppAdded+85
- pool/shard007/C++/0090956_9.cppAdded+115
- pool/shard007/C++/0090959_run_settings_dialog.cppAdded+98
- pool/shard007/C++/0090960_Log.cppAdded+92
- pool/shard007/C++/0090961_input_ime_api_nonchromeos.ccAdded+73
- pool/shard007/C++/0090965_EigenDiffusion.ccAdded+86
- pool/shard007/C++/0090968_luksan_vlcek_1.cppAdded+123
- pool/shard007/C++/0090977_ActuatorPwm.cppAdded+128
- pool/shard007/C++/0090985_unweightedVisibilityGraph.cppAdded+47
- pool/shard007/C++/0090988_JobManifest.cppAdded+78
- pool/shard007/C++/0091001_group-objects-cmd.cppAdded+162
- pool/shard007/C++/0091004_bmplib.cppAdded+190
- pool/shard007/C++/0091007_SVGFilterPrimitiveStandardAttributes.cppAdded+176
- pool/shard007/C++/0091009_interpl.ccAdded+234
- pool/shard007/C++/0091010_inserter.cppAdded+36
- pool/shard007/C++/0091017_MockSerial.cppAdded+65
- pool/shard007/C++/0091019_dynamic_compressed_row_jacobian_writer.ccAdded+114
- pool/shard007/C++/0091020_IAutomatonContext.cppAdded+261
- pool/shard007/C++/0091025_il2cppGC.cppAdded+154
- pool/shard007/C++/0091026_test_eta3.cppAdded+107
- pool/shard007/C++/0091046_playpenaltyour.cppAdded+159
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667// 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 <google/cloud/retail/v2/completion_service.grpc.pb.h>#include <memory>
namespace google {namespace cloud {namespace retail_internal {GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
std::shared_ptr<CompletionServiceStub> CreateDefaultCompletionServiceStub( google::cloud::CompletionQueue cq, Options const& options) { auto auth = google::cloud::internal::CreateAuthenticationStrategy( std::move(cq), options); auto channel = auth->CreateChannel(options.get<EndpointOption>(), internal::MakeChannelArguments(options)); auto service_grpc_stub = google::cloud::retail::v2::CompletionService::NewStub(channel); std::shared_ptr<CompletionServiceStub> stub = std::make_shared<DefaultCompletionServiceStub>( std::move(service_grpc_stub), google::longrunning::Operations::NewStub(channel));
if (auth->RequiresConfigureContext()) { stub = std::make_shared<CompletionServiceAuth>(std::move(auth), std::move(stub)); } stub = std::make_shared<CompletionServiceMetadata>(std::move(stub)); if (internal::Contains(options.get<TracingComponentsOption>(), "rpc")) { GCP_LOG(INFO) << "Enabled logging for gRPC calls"; stub = std::make_shared<CompletionServiceLogging>( std::move(stub), options.get<GrpcTracingOptionsOption>(), options.get<TracingComponentsOption>()); } return stub;}
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END} // namespace retail_internal} // namespace cloud} // namespace google123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219#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 <QDebug>#include <QHeaderView>#include <QMenu>#include <QTreeView>#include <QVBoxLayout>
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<Action*> m_dockToolBarAction; QList<Action*> m_appToolBarAction;
QTreeView* m_view { nullptr }; QMap<QString, ColumnInfo> 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<tutorials::Tutorial*> selectedTutorials() const { QSet<tutorials::Tutorial*> 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<Action *> TutorialsWidget::dockToolBarActions() const{ Q_D(const TutorialsWidget); return d->m_dockToolBarAction;}
QList<Action *> 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 tc123456789101112131415161718192021222324252627#include <iostream>
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);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161/* $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 <ncbi_pch.hpp>
// generated includes#include <objects/omssa/MSResponse.hpp>
// generated classes
BEGIN_NCBI_SCOPE
BEGIN_objects_SCOPE // namespace ncbi::objects::
// destructorCMSResponse::~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 <CMSModSpecSet> 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 <CMSHitSet> 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 */12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879/* * 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 <aitor.martinez.fernandez@gmail.com> */#include <jderobot/comm/cameraClient.hpp>#include <jderobot/comm/ice/cameraIceClient.hpp>#ifdef JDERROS#include <jderobot/comm/ros/listenerCamera.hpp>#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;
}
}//NS12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788#include "MicroStats.h"#include <iostream>#include <random>
#if defined(__GNUC__) && defined(__x86_64__)#include <x86intrin.h>uint64_t now() { return __rdtsc();}#else#include <chrono>uint64_t now() { using std::chrono; return duration_cast<nanoseconds>( system_clock::now().time_since_epoch()).count();}#endif
template< uint32_t N >void summary( const MicroStats<N>& 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<double> 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 );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109/* 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 <stdlib.h>#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 GPIOMBED_WEAK const PinList *pinmap_gpio_restricted_pins(){ static const PinList pin_list = { 0, 0 }; return &pin_list;}
//*** Default restricted peripherals ***#if DEVICE_SERIALMBED_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;}#endif1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162#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<Metahead>& 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<Id>& 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<Metahead>& metaheads){ Result_ptr res = exec_q(Q_RANDOM_METAHEADS, n); while(res->next()) { metaheads.emplace_back(res->get_id(2), res->get_string(1)); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109/******************************************************************************** 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 <QtWidgets/QApplication>#include <QtWidgets/QMainWindow>#include <QtCharts/QChartView>#include <QtCharts/QLineSeries>#include <QtCore/QDateTime>#include <QtCharts/QDateTimeAxis>#include <QtCore/QFile>#include <QtCore/QTextStream>#include <QtCore/QDebug>#include <QtCharts/QValueAxis>
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();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236/* -*- 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 <config.h>
#include "gtype.h"
#include <gwkjs/gwkjs-module.h>#include <gwkjs/compat.h>#include <util/log.h>#include <girepository.h>
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 GQuarkgwkjs_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 voidgwkjs_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 }//};
JSObjectRefgwkjs_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;}
GTypegwkjs_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;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129/*************************************************************************** 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 <QMessageBox>
#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; k<gt.rules.teachersList.size(); k++, i++){ Teacher* tch=gt.rules.teachersList[k]; teachersComboBox->addItem(tch->name); if(tch->name==this->_ctr->teacherName) j=i; } assert(j>=0); teachersComboBox->setCurrentIndex(j); j=-1; activityTagsComboBox->clear(); for(int k=0; k<gt.rules.activityTagsList.count(); k++){ ActivityTag* at=gt.rules.activityTagsList.at(k); activityTagsComboBox->addItem(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();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107/************************************************************************* * * * 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 "LoadFrame.hh"#include <algorithm>#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 */123456789101112131415161718192021222324252627282930313233343536373839/* * 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 <fb/fbjni/References.h>
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;}
}
}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198/***************************************************************************** (C) 2006 by Sanjay Nair** sanjaysn <at> usc <dot> edu****************************************************************************/
#include "cglobal.h"#include <openssl/sha.h>#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<p.size(); i++) { string val = p.at(i);
if (contains_p(val)) { _uMap.erase(val); //printf("removed %s from umap \n", val.c_str()); } } }}
/*! Clears the map*/void CUoidMap::clear(){ CMutexLocker m(&_mutex); _uMap.clear(); _tMap.clear();}
/*! Error if Item Present*/void CUoidMap::errorIfItemPresent(const string &uoid) const{ if (contains_p(uoid)) { string msg = string("Item ") + uoid + string(" is already in the list"); C_THROW(msg); }}
/*! Error if Item Not Present*/void CUoidMap::errorIfItemNotPresent(const string &uoid) const{ if (! contains_p(uoid)) { string msg = string("Item ") + uoid + string(" is not in the list"); C_THROW(msg); }}
/*! Throws exception if the Buffer is invalid*/void CUoidMap::errorIfInvalidBuffer(const UCharBuffer &b) const{ if (b.size() != SHA_DIGEST_LENGTH) { string msg = string("Invalid uoid size ") + CUtil::getString(b.size()); C_THROW(msg); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */
#include <aws/mediaconnect/model/SetSourceRequest.h>#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
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 Aws123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899#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<size; i++) { xyz1[i] = new float[3]; memset(xyz1[i], 0, 3*sizeof(float)); xyz2[i] = new float[3]; memset(xyz2[i], 0, 3*sizeof(float)); }
for (i=0; i<size; i++){ zeros[i] = PyObject_IsTrue(PyTuple_GET_ITEM(py_zeros, i)); xyz1[i][0] = PyFloat_AS_DOUBLE(PyList_GET_ITEM(py_xs1, i)); xyz1[i][1] = PyFloat_AS_DOUBLE(PyList_GET_ITEM(py_ys1, i)); xyz1[i][2] = PyFloat_AS_DOUBLE(PyList_GET_ITEM(py_zs1, i)); xyz2[i][0] = PyFloat_AS_DOUBLE(PyList_GET_ITEM(py_xs2, i)); xyz2[i][1] = PyFloat_AS_DOUBLE(PyList_GET_ITEM(py_ys2, i)); xyz2[i][2] = PyFloat_AS_DOUBLE(PyList_GET_ITEM(py_zs2, i)); }
align(xyz2, xyz1, zeros, size);
// give it to me PyObject * py_result = NULL; PyObject * py_subresult = NULL; py_result = PyList_New(3); for (int j = 0; j < 3; ++j) { py_subresult = PyList_New(size); for (int i = 0; i < size; ++i) { PyList_SetItem(py_subresult, i, PyFloat_FromDouble(xyz2[i][j])); } PyList_SetItem(py_result, j, py_subresult); } for (int i=0; i<size; i++) { delete[] xyz1[i]; delete[] xyz2[i]; } delete[] xyz1; delete[] xyz2; return py_result;}
static PyMethodDef aligner3dMethods[] = { {"aligner3d_wrapper", aligner3d_wrapper, METH_VARARGS, aligner3d__doc__}, {NULL, NULL, 0, NULL} };
PyMODINIT_FUNC initaligner3d(void){ (void) Py_InitModule3("aligner3d", aligner3dMethods, "Functions to align of a given group of models.");}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109/* *@BEGIN LICENSE * * PSI4: an ab initio quantum chemistry software package * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * *@END LICENSE */
/*! \file \ingroup PSIO */
#include <cstdlib>#include <unistd.h>#include <cstring>#include <boost/shared_ptr.hpp>#include <libpsio/psio.h>#include <libpsio/psio.hpp>
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; }
}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130/* 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, softwaredistributed 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 andlimitations under the License.==============================================================================*/
#include "tensorflow/core/platform/file_system_helper.h"
#include <deque>#include <string>#include <vector>
#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<void(int)>& 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<string>* 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<string> 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<string> 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<Status> children_dir_status; while (!dir_q.empty()) { string current_dir = dir_q.front(); dir_q.pop_front(); std::vector<string> 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 tensorflow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192/**************************************************************************** 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;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252/* 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, softwaredistributed 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 andlimitations 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 <typename Device, typename Scalar, bool v2_bcast>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<Device, Scalar> f; f(ctx->eigen_device<Device>(), out->flat<Scalar>()); return; }
// Compute parameters for DNNL matmul primitive. auto params = CreateMatMulParams(lhs.shape(), rhs.shape(), out_shape); // Create or retrieve matmul primitive from cache. MklMatMulPrimitive<Scalar>* matmul_prim = MklMatMulPrimitiveFactory<Scalar>::Get( *params, false /* value for do_not_cache */); // Execute matmul primitive. std::shared_ptr<stream> cpu_stream; cpu_stream.reset(CreateStream(ctx, matmul_prim->GetEngine())); matmul_prim->Execute(lhs.flat<Scalar>().data(), rhs.flat<Scalar>().data(), out->flat<Scalar>().data(), cpu_stream); }
private: bool adj_x_; bool adj_y_; BatchMatMulV2Op<CPUDevice, Scalar> 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<MklMatMulParams> 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<MklMatMulParams>( 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<TYPE>("T") \ .Label(mkl_op_registry::kMklNameChangeOpLabel), \ BatchMatMulMkl<CPUDevice, TYPE, false>)
#define REGISTER_BATCH_MATMUL_MKL_V2(TYPE) \ REGISTER_KERNEL_BUILDER(Name("_MklBatchMatMulV2") \ .Device(DEVICE_CPU) \ .TypeConstraint<TYPE>("T") \ .Label(mkl_op_registry::kMklNameChangeOpLabel), \ BatchMatMulMkl<CPUDevice, TYPE, true>)#ifdef ENABLE_MKLTF_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#endif123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172// 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 <utility>
#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<CrxInstallError>& 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<int>(error->sandbox_failure_detail()) : static_cast<int>(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<absl::optional<update_client::CrxComponent>>UpdateDataProvider::GetData(bool install_immediately, const ExtensionUpdateDataMap& update_crx_component, const std::vector<std::string>& ids) { std::vector<absl::optional<update_client::CrxComponent>> 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<update_client::CrxComponent>() : 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<ExtensionInstaller>( 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 extensions123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384#include "font.h"
#include <map>
//Local includes#include "json.h"#include "FS.h"
typedef std::string fontName_t;typedef std::string fontPath_t;
typedef std::pair<fontName_t,unsigned int> fontPair_t;
typedef std::map<fontName_t,fontPath_t> fonts_t;typedef std::map<fontPair_t,GE_Font> fontRenders_t;
fonts_t fonts; //font name:font pathfontRenders_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> 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();}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364/****************************************************************************** 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 <QSettings>
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 Bazaar123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113/* -*- 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 <mcbp/protocol/unsigned_leb128.h>#include <memcached/dockey.h>#include <spdlog/fmt/fmt.h>#include <sstream>#include <string_view>
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<CollectionIDType>::decode( {data(), size()});
std::string_view remainingKey{reinterpret_cast<const char*>(key.data()), key.size()}; if (getCollectionID().isSystem()) { // Get the hex value of the type of system event auto [systemEventID, keyWithoutEvent] = cb::mcbp::unsigned_leb128<uint32_t>::decode( {key.data(), key.size()}); // Get the cid or sid of the system event is for auto [cidOrSid, keySuffix] = cb::mcbp::unsigned_leb128<uint32_t>::decode( {keyWithoutEvent.data(), keyWithoutEvent.size()}); // Get the string view to the remaining string part of the key remainingKey = {reinterpret_cast<const char*>(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<CollectionIDType>::decode(buffer) .first; return cid; } return CollectionID::Default;}
// Inspect the leb128 key prefixes without doing a full leb decodebool 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 decodebool DocKey::isInDefaultCollection() const { if (encoding == DocKeyEncodesCollectionId::Yes) { return data()[0] == CollectionID::Default; } return true;}
std::pair<CollectionID, cb::const_byte_buffer> DocKey::getIdAndKey() const { if (encoding == DocKeyEncodesCollectionId::Yes) { return cb::mcbp::unsigned_leb128<CollectionIDType>::decode(buffer); } return {CollectionID::Default, {data(), size()}};}
DocKey DocKey::makeDocKeyWithoutCollectionID() const { if (getEncoding() == DocKeyEncodesCollectionId::Yes) { auto decoded = cb::mcbp::skip_unsigned_leb128<CollectionIDType>(buffer); return {decoded.data(), decoded.size(), DocKeyEncodesCollectionId::No}; } return *this;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687/** * 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 <string>#include <sstream>
#include <cstdarg>
#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 gnuworld123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263/******************************************************************************\
CAMotics is an Open-Source simulation and CAM software. Copyright (C) 2011-2019 Joseph Coffland <joseph@cauldrondevelopment.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 "SurfaceTask.h"
#include <camotics/sim/SimulationRun.h>#include <camotics/contour/Surface.h>
#include <cbang/String.h>#include <cbang/time/Timer.h>#include <cbang/time/TimeInterval.h>#include <cbang/log/Logger.h>
using namespace cb;using namespace CAMotics;
SurfaceTask::SurfaceTask(const Simulation &sim) : simRun(new SimulationRun(sim)) {}
SurfaceTask::SurfaceTask(const SmartPointer<SimulationRun> &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));}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134#include <string>#include <cerrno>#include <cstdio>#include <cstring>
#include "Config.h"
Config::Config(){ this->err_message.clear();}
Config::~Config(){ this->param.clear();}
std::stringConfig::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;}
intConfig::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::stringConfig::get(const char *key){ std::map<std::string, std::string>::iterator itr = param.find(key); if (itr != param.end()) { return itr->second; } else { err_message = "key not found"; return ""; }}
size_tConfig::getParamCount(void){ return this->param.size();}
std::vector<std::string>Config::getKeys(void){ std::vector<std::string> result; std::map<std::string, std::string>::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();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209/* * * 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<Uint8, Uint32, Uint8>(Document, InputData, palette, ImageStatus, planeSize, BitsStored); else InterData = new DiARGBPixelTemplate<Uint8, Uint32, Uint16>(Document, InputData, palette, ImageStatus, planeSize, BitsStored); break; case EPR_Sint8: if (BitsPerSample <= 8) InterData = new DiARGBPixelTemplate<Sint8, Sint32, Uint8>(Document, InputData, palette, ImageStatus, planeSize, BitsStored); else InterData = new DiARGBPixelTemplate<Sint8, Sint32, Uint16>(Document, InputData, palette, ImageStatus, planeSize, BitsStored); break; case EPR_Uint16: if (BitsPerSample <= 8) InterData = new DiARGBPixelTemplate<Uint16, Uint32, Uint8>(Document, InputData, palette, ImageStatus, planeSize, BitsStored); else InterData = new DiARGBPixelTemplate<Uint16, Uint32, Uint16>(Document, InputData, palette, ImageStatus, planeSize, BitsStored); break; case EPR_Sint16: if (BitsPerSample <= 8) InterData = new DiARGBPixelTemplate<Sint16, Sint32, Uint8>(Document, InputData, palette, ImageStatus, planeSize, BitsStored); else InterData = new DiARGBPixelTemplate<Sint16, Sint32, Uint16>(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. * * */123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129/* * 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 <head> 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 <head>: // SCRIPT|STYLE|META|LINK|OBJECT|TITLE|BASE
// We stop scanning when a tag that is not permitted in <head> // is seen, rather when </head> is seen, because that more closely // matches behavior in other browsers; more details in // <http://bugs.webkit.org/show_bug.cgi?id=3590>.
// Additionally, we ignore things that looks like tags in <title>, <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;}
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485/* 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 */
/* ScriptDataSDName: Razorfen_DownsSD%Complete: 100SDComment: Support for Henry Stern(2 recipes)SDCategory: Razorfen DownsEndScriptData */
/* ContentDatanpc_henry_sternEndContentData */
#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();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115#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 returnconst 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;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798/*************************************************************************//* 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");
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192/* * 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 */12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273// 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 extensions1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586//----------------------------------*-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//---------------------------------------------------------------------------//123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123/***************************************************************************** * 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 detectionvoid 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128#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;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647#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);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778/** * 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 Aws123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162// -*- 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);}
} // namespace123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190#ifdef _WIN32#include "boinc_win.h"#else#include "config.h"#endif
#include "bmplib.h"
// Returns true for success -- false otherwisebool 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 memoryvoid 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;}
// DeconstructorDIB_BITMAP::~DIB_BITMAP() { FreeDIB_BMP(); }
const char *BOINC_RCSID_1051ce617a = "$Id: bmplib.cpp 16069 2008-09-26 18:20:24Z davea $";123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176/* * 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 definitionsDEFINE_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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234/********************************************************************* 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 appendsint 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;}123456789101112131415161718192021222324252627282930313233343536#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;
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465/* * 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();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114// 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 ceres123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261#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();}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154#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;
}
#endif123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107/// 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;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159#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;}pool/shard007/C++/0090774_completion_stub_factory.ccAdded+67
pool/shard007/C++/0090781_tutorialswidget.cppAdded+219
pool/shard007/C++/0090784_main.cppAdded+27
pool/shard007/C++/0090790_MSResponse.cppAdded+161
pool/shard007/C++/0090805_cameraClient.cppAdded+79
pool/shard007/C++/0090814_testMicroStats.cppAdded+88
pool/shard007/C++/0090817_mbed_pinmap_default.cppAdded+109
pool/shard007/C++/0090835_database.cppAdded+62
pool/shard007/C++/0090838_main.cppAdded+109
pool/shard007/C++/0090839_gtype.cppAdded+236
pool/shard007/C++/0090840_modifyconstraintteacheractivitytagmaxhourscontinuouslyform.cppAdded+129
pool/shard007/C++/0090846_LoadFrame.ccAdded+107
pool/shard007/C++/0090851_References.cppAdded+39
pool/shard007/C++/0090868_cuoidmap.ccAdded+198
pool/shard007/C++/0090875_SetSourceRequest.cppAdded+216
pool/shard007/C++/0090876_align_py.cppAdded+99
pool/shard007/C++/0090877_read.ccAdded+109
pool/shard007/C++/0090878_file_system_helper.ccAdded+130
pool/shard007/C++/0090889_LocalizationManager.cppAdded+192
pool/shard007/C++/0090896_mkl_batch_matmul_op.ccAdded+252
pool/shard007/C++/0090899_update_data_provider.ccAdded+172
pool/shard007/C++/0090904_font.cppAdded+84
pool/shard007/C++/0090905_bazaarsettings.cppAdded+64
pool/shard007/C++/0090913_dockey.ccAdded+113
pool/shard007/C++/0090917_chanfix-misc.ccAdded+87
pool/shard007/C++/0090925_SurfaceTask.cppAdded+63
pool/shard007/C++/0090928_Config.cppAdded+134
pool/shard007/C++/0090936_diargimg.ccAdded+209
pool/shard007/C++/0090940_HTMLMetaCharsetParser.cppAdded+129
pool/shard007/C++/0090948_razorfen_downs.cppAdded+85
pool/shard007/C++/0090956_9.cppAdded+115
pool/shard007/C++/0090959_run_settings_dialog.cppAdded+98
pool/shard007/C++/0090960_Log.cppAdded+92
pool/shard007/C++/0090961_input_ime_api_nonchromeos.ccAdded+73
pool/shard007/C++/0090965_EigenDiffusion.ccAdded+86
pool/shard007/C++/0090968_luksan_vlcek_1.cppAdded+123
pool/shard007/C++/0090977_ActuatorPwm.cppAdded+128
pool/shard007/C++/0090985_unweightedVisibilityGraph.cppAdded+47
pool/shard007/C++/0090988_JobManifest.cppAdded+78
pool/shard007/C++/0091001_group-objects-cmd.cppAdded+162
pool/shard007/C++/0091004_bmplib.cppAdded+190
pool/shard007/C++/0091007_SVGFilterPrimitiveStandardAttributes.cppAdded+176
pool/shard007/C++/0091009_interpl.ccAdded+234
pool/shard007/C++/0091010_inserter.cppAdded+36
pool/shard007/C++/0091017_MockSerial.cppAdded+65
pool/shard007/C++/0091019_dynamic_compressed_row_jacobian_writer.ccAdded+114
pool/shard007/C++/0091020_IAutomatonContext.cppAdded+261
pool/shard007/C++/0091025_il2cppGC.cppAdded+154
pool/shard007/C++/0091026_test_eta3.cppAdded+107
pool/shard007/C++/0091046_playpenaltyour.cppAdded+159