text
string
size
int64
token_count
int64
/*============================================================================= Library: CTK Copyright (c) 2010 Brigham and Women's Hospital (BWH) All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "ctkModuleParameter.h" #include "QStringList" //---------------------------------------------------------------------------- bool ctkModuleParameter::isReturnParameter() const { // could check for tag == float, int, float-vector, ... return (*this)["Channel"] == "output" && !this->isFlagParameter() && !this->isIndexParameter(); } //---------------------------------------------------------------------------- bool ctkModuleParameter::isFlagParameter() const { return ((*this)["Flag"] != "" || (*this)[ "LongFlag" ] != ""); } //---------------------------------------------------------------------------- bool ctkModuleParameter::isIndexParameter() const { return ((*this)[ "Index" ] != ""); } //----------------------------------------------------------------------------- QTextStream & operator<<(QTextStream &os, const ctkModuleParameter &parameter) { os << " Parameter" << endl; os << " "; os.setFieldWidth(7); os.setFieldAlignment(QTextStream::AlignLeft); os << QHash<QString, QString>( parameter ); os.setFieldWidth(0); os << "Flag aliases: "; os << parameter["FlagAliases"].split( "," ); os << " " << "Deprecated Flag aliases: "; os << parameter["DeprecatedFlagAliases"].split( "," ); os << " " << "LongFlag aliases: "; os << parameter["LongFlagAliases"].split( "," ); os << " " << "Deprecated LongFlag aliases: "; os << parameter["DeprecatedLongFlagAliases"].split( "," ); os << " " << "FileExtensions: "; os << parameter["FileExtensions"].split( "," ); return os; } //---------------------------------------------------------------------------- QTextStream & operator<<(QTextStream &os, const QStringList &list) { os << list.join(", ") << endl; return os; } //---------------------------------------------------------------------------- QTextStream & operator<<(QTextStream &os, const QHash<QString, QString> &hash) { QHash<QString,QString>::const_iterator itProp; for ( itProp = hash.begin( ) ; itProp != hash.end( ) ; itProp++ ) { os << itProp.key( ) << ": " << itProp.value( ) << endl; } return os; }
2,940
826
// Copyright 2019 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////////////// #include "libsxg/sxg_encoded_response.h" #include <string> #include "gtest/gtest.h" #include "test_util.h" namespace { using ::sxg_test::BufferToString; TEST(SxgEncodedResponse, InitializeAndReleaseEmptyRawResponse) { sxg_raw_response_t resp = sxg_empty_raw_response(); sxg_raw_response_release(&resp); } TEST(SxgEncodedResponse, InitializeAndReleaseEmptyEncodedResponse) { sxg_encoded_response_t resp = sxg_empty_encoded_response(); sxg_encoded_response_release(&resp); } std::string HeaderFindKey(const sxg_header_t& header, const char* key) { for (size_t i = 0; i < header.size; ++i) { if (strcasecmp(header.entries[i].key, key) == 0) { return BufferToString(header.entries[i].value); } } return ""; } TEST(SxgEncodedResponse, EncodeMinimum) { // https://tools.ietf.org/html/draft-thomson-http-mice-03#section-2.2 // If 0 octets are available, and "top-proof" is SHA-256("\0") (whose base64 // encoding is "bjQLnP+zepicpUTmu3gKLHiQHT+zNzh2hRGjBhevoB0="), then return a // 0-length decoded payload. sxg_raw_response_t resp = sxg_empty_raw_response(); sxg_encoded_response_t output = sxg_empty_encoded_response(); std::string expected_digest = "mi-sha256-03=bjQLnP+zepicpUTmu3gKLHiQHT+zNzh2hRGjBhevoB0="; EXPECT_TRUE(sxg_encode_response(16, &resp, &output)); EXPECT_EQ(3u, output.header.size); EXPECT_EQ("200", HeaderFindKey(output.header, ":status")); EXPECT_EQ("mi-sha256-03", HeaderFindKey(output.header, "content-encoding")); EXPECT_EQ(expected_digest, HeaderFindKey(output.header, "digest")); EXPECT_EQ(0u, output.payload.size); sxg_raw_response_release(&resp); sxg_encoded_response_release(&output); } TEST(SxgEncodedResponse, IntegrityMinimum) { sxg_raw_response_t resp = sxg_empty_raw_response(); sxg_encoded_response_t enc = sxg_empty_encoded_response(); sxg_buffer_t output = sxg_empty_buffer(); std::string expected = "sha256-4zGVTZ38P1nbTw6MnJfVF21L7qg0pJsfXjIOOfcXIgo="; EXPECT_TRUE(sxg_encode_response(4096, &resp, &enc)); EXPECT_TRUE(sxg_write_header_integrity(&enc, &output)); EXPECT_EQ(expected, BufferToString(output)); sxg_raw_response_release(&resp); sxg_encoded_response_release(&enc); sxg_buffer_release(&output); } TEST(SxgEncodedResponse, SomeHeader) { sxg_raw_response_t resp = sxg_empty_raw_response(); sxg_encoded_response_t enc = sxg_empty_encoded_response(); sxg_encode_response(16, &resp, &enc); sxg_buffer_t output = sxg_empty_buffer(); sxg_header_append_string("foo", "bar", &resp.header); std::string expected = "sha256-CUivwFQMaYG/EfLfL4l4dbde7Xp/+jIzdP6GqttQNTw="; EXPECT_TRUE(sxg_encode_response(4096, &resp, &enc)); EXPECT_EQ(4u, enc.header.size); EXPECT_TRUE(sxg_write_header_integrity(&enc, &output)); EXPECT_EQ(expected, BufferToString(output)); sxg_raw_response_release(&resp); sxg_encoded_response_release(&enc); sxg_buffer_release(&output); } } // namespace
3,602
1,416
/** VD */ #pragma once #include <vd/common.hpp> #include <vd/proto.hpp> #include <QObject> #include <QScrollBar> #include <QGraphicsItem> #include <QGraphicsView> #include <QGraphicsScene> namespace vd { struct StreamConf { double time_base; }; class MediaDecoder { public: MediaDecoder(); virtual ~MediaDecoder() {} DecodingStatePtr decode(MediaPtr media); DecodingStatePtr decode(Media* media); static MediaDecoder& i() { VD_ASSERT2(instance_, "MediaDecoder singleton wasn't created"); return *instance_; } protected: static MediaDecoder* instance_; typedef std::map<AString, DecodingStatePtr> Decoders; typedef std::map<AString, DecodingStatePtr>::iterator DecodersIter; Decoders decoders_; }; class PreviewState; class TimeLineObject { public: TimeLineObject(TimeLineTrack* track); void set_track(TimeLineTrack* track) { track_ = track; } TimeLineTrack* track() { return track_; } const TimeLineTrack* track() const { return track_; } virtual void set_start(time_mark start) { start_ = start; } time_mark start() const { return start_; } virtual void set_length(time_mark length) { length_ = length; } time_mark length() const { return length_; } virtual void set_playing(time_mark playing) { playing_ = playing; } time_mark playing() const { return playing_; } virtual void seek(time_mark t) = 0; virtual IFramePtr show_next() = 0; private: TimeLineTrack* track_; time_mark start_; time_mark length_; time_mark playing_; }; class TimeLineContainer { public: virtual void add(TimeLineRectPtr rect) = 0; }; class MediaClip { public: MediaClip(MediaPtr media); void set_start(time_mark start) { start_ = start; } time_mark start() const { return start_; } void set_length(time_mark length) { length_ = length; } time_mark length() const { return length_; } MediaPtr media() const { return media_; } protected: MediaPtr media_; time_mark start_; time_mark length_; }; class MediaPipelineTransformer; class MediaPipeline { public: }; class FrameFormat; class MediaPipelineTransformer { public: virtual IFramePtr transform(IFramePtr frame) = 0; virtual bool accepts(const FrameFormat& format) = 0; protected: }; class MediaLoader { public: virtual void seek(time_mark t) = 0; virtual IFramePtr load_next() = 0; }; class MediaBackend { protected: struct Node { time_mark start; time_mark end; std::deque<IFramePtr> frames; }; friend class Iter; public: class Iter { public: IFramePtr show_next(); time_mark time() const { return t_; } protected: MediaBackend* backend_; Node* cached_; time_mark t_; }; }; class MediaObject : public TimeLineObject { public: MediaObject(); void setup(MediaClip* clip, int stream_id, PresenterPtr presenter); void seek(time_mark t) VD_OVERRIDE; IFramePtr show_next() VD_OVERRIDE; void set_length(time_mark length) VD_OVERRIDE; time_mark time_base() const; DecodingStatePtr decoder() { return decoder_; } protected: void preload_next(); public: MediaClipUPtr clip_; int stream_id_; /// Pts which corresponds first frame in frames_ queue time_mark ready_pts_; std::deque<IFramePtr> frames_; /// Pts which corresponds last decoded frame in frames_ queue time_mark read_pts_; DecodingStatePtr decoder_; PresenterPtr presenter_; }; struct PreviewPreset { float audio_volume; PreviewPreset() : audio_volume(1.f) {} }; class PreviewState { public: struct Pres { double time_base; }; PreviewState(Project* project); void sync(time_mark t); IFramePtr next_video(); MovieResourcePtr next_audio(); time_mark time_base(); void update_preset(const PreviewPreset& preset); protected: MediaObjectPtr peek_video_clip(time_mark t); MediaObjectPtr peek_audio_clip(time_mark t); protected: Project* project_; Scene* scene_; time_mark time_base_; time_mark playing_; PreviewPreset preset_; MediaObjectPtr video_clip_; MediaObjectPtr audio_clip_; std::vector<MediaObjectPtr> clips_; }; class TimeLineTrack { public: TimeLineTrack(int track) : track_(track) {} int track() const { return track_; } protected: public: int track_; typedef std::vector<MediaObjectPtr> MediaClips; typedef std::vector<MediaObjectPtr>::iterator MediaClipsIter; std::vector<MediaObjectPtr> comps_; }; class TimeLine { public: typedef std::vector<ScenePtr> Scenes; typedef std::vector<ScenePtr>::iterator ScenesIter; public: TimeLine(); void notify_project(Project* project); void _create_test() ; void query(time_mark t); Scene* scene_from_time(time_mark t); protected: public: Scenes scenes_; Project* project_; }; class TimeLineRectWidget : public QGraphicsItem { friend class TimeLineWidget; QRectF boundingRect() const; public: TimeLineRectWidget(MediaObjectPtr composed, QGraphicsItem* parent); void sync(const QPointF& size); void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); void mousePressEvent(QGraphicsSceneMouseEvent* ev); void mouseMoveEvent(QGraphicsSceneMouseEvent* ev); void mouseReleaseEvent(QGraphicsSceneMouseEvent* ev); MediaObjectPtr composed() { return composed_; } protected: MediaObjectPtr composed_; QPointF offset_; QPointF size_; TimeLineTrackWidget* parent_track_; }; class TimeLineTrackWidget : public QGraphicsObject { friend class TimeLineTrack; Q_OBJECT public: typedef std::vector<TimeLineRectPtr> MediaClips; typedef std::vector<TimeLineRectPtr>::iterator MediaClipsIter; public: TimeLineTrackWidget(TimeLineTrack* track, TimeLineWidget* parent_widget); QRectF boundingRect(void) const; void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); void pose_rect(TimeLineRectPtr rect); void add(MediaObjectPtr composed); QPointF transf(const QPointF& p); QPointF scale(const QPointF& p); protected: void sync(); public: TimeLineWidget* parent_widget_; TimeLineTrack* track_; std::vector<TimeLineRectPtr> comps_; }; class TimeLineCursorWidget : public QGraphicsItem { friend class TimeLineWidget; QRectF boundingRect() const; public: TimeLineCursorWidget(QGraphicsView* parent); void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); void mousePressEvent(QGraphicsSceneMouseEvent* ev); void mouseMoveEvent(QGraphicsSceneMouseEvent* ev); void mouseReleaseEvent(QGraphicsSceneMouseEvent* ev); void sync(); int current() const; void set_to(int center); protected: TimeLineWidget* parent_; QPointF offset_; qreal height_; int click_width_div2; }; class TimeLineSceneWidget : public QGraphicsObject, public TimeLineContainer { Q_OBJECT public: typedef std::vector<TimeLineTrackWidgetPtr> Tracks; typedef std::vector<TimeLineTrackWidgetPtr>::iterator TracksIter; public: TimeLineSceneWidget(Scene* scene, TimeLineWidget* time_line); QRectF boundingRect() const { return QRectF(); } void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); QPointF transf(const QPointF& p); QPointF scale(const QPointF& p); void add(TimeLineRectPtr rect) VD_OVERRIDE; protected: void sync(); public: Scene* scene_; TimeLineWidget* time_line_; std::vector<TimeLineTrackWidgetPtr> tracks_; }; class TimeLineWidget : public QGraphicsView, public TimeLineContainer { Q_OBJECT friend class TimeLine; public: typedef std::vector<TimeLineSceneWidgetPtr> Scenes; typedef std::vector<TimeLineSceneWidgetPtr>::iterator ScenesIter; public: TimeLineWidget(QWidget* parent = 0); void bind(TimeLine* tm); //void bind_ctrls(QScrollBar* scroll); void wheelEvent(QWheelEvent* ev); void mouseDoubleClickEvent(QMouseEvent * ev); void add(TimeLineRectPtr rect) VD_OVERRIDE; QPointF transf(const QPointF& p); QPointF scale(const QPointF& p); qreal time2pos(time_mark t); time_mark pos2time(qreal pos); static TimeLineWidget& i() { VD_ASSERT2(instance_, "No TimeLineWidget instance!"); return *instance_; } void notify_current_preview_time(time_mark t); void set_preview(Preview* preview) { preview_ = preview; } signals: void set_playing(bool playing); public slots: void cursor_updated(); public slots: void scroll_moved(int value); int cd(float c); float dc(int d); protected slots: void update_timer(); void setup_timer(bool playing); protected: void sync(TimeLine* tm); void pose_cursor(float current); void update_ctrls(); void update_time_label(); protected: static TimeLineWidget* instance_; TimeLine* tm_; QGraphicsScene scene_; float offset_; float scale_; float current_; float length_; QScrollBar* scroll_; TimeLineCursorWidget* cursor_; Scenes scenes_; QLabel* time_lbl_; time_mark preview_time_; QTimer* timer_; bool playing_; Preview* preview_; }; class Scene { public: typedef std::vector<TimeLineTrackPtr> Tracks; typedef std::vector<TimeLineTrackPtr>::iterator TracksIter; typedef std::vector<CompositorPtr> Compositor; typedef std::vector<CompositorPtr>::iterator CompositorIter; Scene(Project* project); public: void _create_test(); time_mark duration() const; protected: public: Project* project_; Tracks tracks_; Compositor comps_; }; template <typename _T> class VarCtrl { public: virtual ~VarCtrl() = 0; virtual _T value(time_mark t) const = 0; }; class TimeLineParam : public TimeLineObject { public: TimeLineParam(const Name& name) : TimeLineObject(nullptr), name_(name) {} const Name& name() const { return name_; } protected: Name name_; }; template <typename _T> class TimeLineVar : public TimeLineParam { public: TimeLineVar(Name& name) : TimeLineParam(name) {} _T value(time_mark t) { return value_ctrl_->value(t); } _T* ctrl() { return value_ctrl_; } const _T* ctrl() const { return value_ctrl_; } void set_ctrl(_T* ctrl) { value_ctrl_ = ctrl; } protected: Name name_; _T* value_ctrl_; }; class Project { public: Project(PresenterPtr video_presenter, PresenterPtr audio_presenter); ~Project(); void _create_test(); TimeLine* time_line() { return time_line_.get(); } PresenterPtr video_presenter() { return video_presenter_; } PresenterPtr audio_presenter() { return audio_presenter_; } protected: public: AString name_; PresenterPtr video_presenter_; PresenterPtr audio_presenter_; int frame_rate_; TimeLinePtr time_line_; }; }// namespace vd
10,336
3,617
// Copyright 2016-2021 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md #include "ux/ProgressBar.hpp" #include "ux/draw/Rectangle.hpp" using namespace ux::sgfx; using namespace ux;
188
76
// // Created by Aaron Helton on 1/16/2020. // #ifndef JLMG_DEFINES_HPP #define JLMG_DEFINES_HPP #include <cstdint> typedef uint_least8_t uint8; typedef uint_least16_t uint16; typedef uint_least32_t uint32; typedef uint_least64_t uint64; typedef int_least8_t int8; typedef int_least16_t int16; typedef int_least32_t int32; typedef int_least64_t int64; #endif //JLMG_DEFINES_HPP
382
204
/// @file vnix/bit-range.hpp /// @brief Definition of vnix::bit, vnix::bit_range. /// @copyright 2019 Thomas E. Vaughan; all rights reserved. /// @license BSD Three-Clause; see LICENSE. #ifndef VNIX_BIT_HPP #define VNIX_BIT_HPP namespace vnix { /// Word with specified bit set. /// @tparam I Type of integer word. /// @param n Offset of bit in word. template <typename I> constexpr I bit(unsigned n) { return I(1) << n; } /// Word with specified range of bits set. /// @tparam I Type of integer word. /// @param n1 Offset of bit at one end of range. /// @param n2 Offset of bit at other end of range. template <typename I> constexpr I bit_range(unsigned n1, unsigned n2) { if (n1 < n2) { return bit<I>(n1) | bit_range<I>(n1 + 1, n2); } if (n2 < n1) { return bit<I>(n2) | bit_range<I>(n2 + 1, n1); } return bit<I>(n1); } } // namespace vnix #endif // ndef VNIX_BIT_HPP
909
361
///////////////////////////////////////////////// // WdGix-Constants TStr TGixConst::WdGixFNm = "WdGix"; TStr TGixConst::WdGixDatFNm = "WdGix.Dat"; TStr TGixConst::WdGixBsFNm = "WdGixBs.MBlobBs"; TStr TGixConst::WdGixMDSFNm = "WdGixMDS.Dat"; TStr TGixConst::TrGixFNm = "TrGix"; TStr TGixConst::TrGixDatFNm = "TrGix.Dat"; TStr TGixConst::TrGixDocBsFNm = "TrGixDocBs.MBlobBs"; TStr TGixConst::TrGixSentBsFNm = "TrGixSentBs.MBlobBs"; TStr TGixConst::TrGixTrAttrBsFNm = "TrGixTrAttrBs.MBlobBs"; TStr TGixConst::MWdGixFNm = "MWdGix"; TStr TGixConst::MWdGixDatFNm = "MWdGix.Dat"; TStr TGixConst::MWdGixDocBsFNm = "MWdGixDocBs.MBlobBs"; TStr TGixConst::MWdGixBsFNm = "MWdGixBs.Dat"; ///////////////////////////////////////////////// // Word-Inverted-Index-DataField int TWdGixItem::TitleBit = 0; int TWdGixItem::NmObjBit = 1; int TWdGixItem::AnchorBit = 2; int TWdGixItem::EmphBit = 3; TWdGixItem::TWdGixItem(const TBlobPt& BlobPt, const uchar& _Wgt, const uchar& _WdPos, const bool& TitleP, const bool& NmObjP, const bool& AnchorP, const bool& EmphP): Seg(BlobPt.GetSeg()), Addr(BlobPt.GetAddr()), WdPos(_WdPos) { FSet.SetBit(TitleBit, TitleP); FSet.SetBit(NmObjBit, NmObjP); FSet.SetBit(AnchorBit, AnchorP); FSet.SetBit(EmphBit, EmphP); } TWdGixItem::TWdGixItem(const uchar& _Seg, const uint& _Addr, const uchar& _Wgt, const uchar& _WdPos, const bool& TitleP, const bool& NmObjP, const bool& AnchorP, const bool& EmphP): Seg(_Seg), Addr(_Addr), Wgt(_Wgt), WdPos(_WdPos) { FSet.SetBit(TitleBit, TitleP); FSet.SetBit(NmObjBit, NmObjP); FSet.SetBit(AnchorBit, AnchorP); FSet.SetBit(EmphBit, EmphP); } TWdGixItem::TWdGixItem(TSIn& SIn) { SIn.Load(Seg); SIn.Load(Addr); SIn.Load(Wgt); SIn.Load(WdPos); FSet=TB8Set(SIn); } void TWdGixItem::Save(TSOut& SOut) const { SOut.Save(Seg); SOut.Save(Addr); SOut.Save(Wgt); SOut.Save(WdPos); FSet.Save(SOut); } inline bool TWdGixItem::operator==(const TWdGixItem& Item) const { return (Seg == Item.Seg) && (Addr == Item.Addr); // && (WdPos == Item.WdPos); } inline bool TWdGixItem::operator<(const TWdGixItem& Item) const { return (Seg < Item.Seg) || ((Seg == Item.Seg) && (Addr < Item.Addr)); // || //((Seg == Item.Seg) && (Addr == Item.Addr) && (WdPos < Item.WdPos)); } ///////////////////////////////////////////////// // Word-Inverted-Index void TWdGix::LoadTags() { TitleTagH.AddKey("<TITLE>"); NmObjTagH.AddKey("<NMOBJ>"); EmphTagH.AddKey("<EM>"); EmphTagH.AddKey("<A>"); EmphTagH.AddKey("<B>"); EmphTagH.AddKey("<I>"); EmphTagH.AddKey("<H1>"); EmphTagH.AddKey("<H2>"); EmphTagH.AddKey("<H3>"); EmphTagH.AddKey("<H4>"); EmphTagH.AddKey("<H5>"); } TWdGix::TWdGix(const TStr& _FPath, const TFAccess& _FAccess, const int64& CacheSize) { // store policy FPath = _FPath; FAccess = _FAccess; // prepare gix WGix = TWGix::New(TGixConst::WdGixFNm, FPath, FAccess, CacheSize); // load word tables if (FAccess == faCreate) { Stemmer = TStemmer::New(stmtPorter, false); SwSet = TSwSet::New(swstEn523); } else { // prepare file name TStr WdGixDatFNm = TStr::GetNrFPath(FPath) + TGixConst::WdGixDatFNm; // load stuff TFIn FIn(WdGixDatFNm); WordH.Load(FIn); Stemmer = TStemmer::Load(FIn); SwSet = TSwSet::Load(FIn); } // load tags LoadTags(); } TWdGix::~TWdGix() { if ((FAccess == faCreate) || (FAccess == faUpdate)) { // prepare file name TStr WdGixDatFNm = TStr::GetNrFPath(FPath) + TGixConst::WdGixDatFNm; // save word tables TFOut FOut(WdGixDatFNm); WordH.Save(FOut); Stemmer->Save(FOut); SwSet->Save(FOut); } } void TWdGix::AddHtml(const TStr& HtmlStr, const TBlobPt& BlobPt, const uchar& Wgt) { // create html lexical PSIn HtmlSIn = TStrIn::New(HtmlStr); THtmlLx HtmlLx(HtmlSIn); HtmlLx.GetSym(); // prepare word vector, position counter and flags THash<TInt, TWdGixItemV> WIdToItemVH; uchar WdPos = 0; bool TitleP = false, NmObjP = false; int EmphLv = 0; // traverse html string symbols while (HtmlLx.Sym != hsyEof) { if (HtmlLx.Sym == hsyStr) { // get word token TStr WordStr = HtmlLx.UcChA; // should we keep this word? if (!SwSet->IsIn(WordStr)) { // stem the word WordStr=Stemmer->GetStem(WordStr); // get the word id const int WId = WordH.AddKey(WordStr); // increase the position count WdPos++; // add word to vector WIdToItemVH.AddDat(WId).Add( TWdGixItem(BlobPt, Wgt, WdPos, TitleP, NmObjP, false, (EmphLv>0))); } } else if (HtmlLx.Sym == hsyBTag) { // we have a tag, we update flags accordingly TStr TagStr = HtmlLx.UcChA; if (TitleTagH.IsKey(TagStr)) { TitleP = true; } if (NmObjTagH.IsKey(TagStr)) { NmObjP = true; } if (EmphTagH.IsKey(TagStr)) { EmphLv++; } } else if (HtmlLx.Sym == hsyETag) { // we have a tag, we update flags accordingly TStr TagStr = HtmlLx.UcChA; if (TitleTagH.IsKey(TagStr)) { TitleP = false; } if (NmObjTagH.IsKey(TagStr)) { NmObjP = false; } if (EmphTagH.IsKey(TagStr)) { EmphLv--; EmphLv = TInt::GetMx(0, EmphLv); } } // get next symbol HtmlLx.GetSym(); } // load add documents to words in inverted index int WdKeyId = WIdToItemVH.FFirstKeyId(); while (WIdToItemVH.FNextKeyId(WdKeyId)) { const int WId = WIdToItemVH.GetKey(WdKeyId); WordH[WId]++; const TWdGixItemV& ItemV = WIdToItemVH[WdKeyId]; // HACK combine all items into one const uchar Seg = ItemV[0].GetSeg(); const uint Addr = ItemV[0].GetAddr(); const uchar Count = uchar(TInt::GetMn(int(TUCh::Mx), ItemV.Len())); bool TitleP = false, NmObjP = false, EmphP = false, AnchorP = false; for (int ItemN = 0; ItemN < ItemV.Len(); ItemN++) { const TWdGixItem& Item = ItemV[ItemN]; TitleP = TitleP || Item.IsTitle(); NmObjP = NmObjP || Item.IsNmObj(); EmphP = EmphP || Item.IsAnchor(); AnchorP = AnchorP || Item.IsEmph(); } TWdGixItem Item(Seg, Addr, Wgt, Count, TitleP, NmObjP, AnchorP, EmphP); // add ti index WGix->AddItem(WId, Item); } } bool TWdGix::Search(const TStr& QueryStr, TWdGixItemV& ResItemV) { //HACK simple parsing (no operators...) PWGixExpItem WGixExp = TWGixExpItem::NewEmpty(); PSIn HtmlSIn = TStrIn::New(QueryStr); THtmlLx HtmlLx(HtmlSIn); HtmlLx.GetSym(); while (HtmlLx.Sym != hsyEof) { if (HtmlLx.Sym == hsyStr) { // get word token TStr WordStr = HtmlLx.UcChA; // stem the word WordStr=Stemmer->GetStem(WordStr); // check if we have it const int WId = WordH.GetKeyId(WordStr); if (WId != -1) { PWGixExpItem WGixExpItem = TWGixExpItem::NewItem(WId); if (WGixExp->IsEmpty()) { WGixExp = WGixExpItem; } else { WGixExp = TWGixExpItem::NewAnd(WGixExp, WGixExpItem); } } } // get next symbol HtmlLx.GetSym(); } // search return WGixExp->Eval(WGix, ResItemV); } ///////////////////////////////////////////////// // WdGix-Meta-Data-Base void TWdGixMDS::AddDate(const TBlobPt& DocBlobPt, const TTm& DateTime) { TAddrPr AddrPr(DocBlobPt.GetSeg(), DocBlobPt.GetAddr()); const uint64 DateMSecs = TTm::GetMSecsFromTm(DateTime); AddrPrToDateH.AddDat(AddrPr, DateMSecs); } inline uint64 TWdGixMDS::GetDateMSecs(const TBlobPt& DocBlobPt) const { return AddrPrToDateH.GetDat(TAddrPr(DocBlobPt.GetSeg(), DocBlobPt.GetAddr())); } inline TTm TWdGixMDS::GetDateTTm(const TBlobPt& DocBlobPt) const { return TTm::GetTmFromMSecs(GetDateMSecs(DocBlobPt)); } ///////////////////////////////////////////////// // WdGix-Result-Set void TWdGixRSet::AddDoc(const TStr& DocTitle, const TStr& DocStr, const TStrV& CatNmV, const TTm& DateTime) { DocTitleV.Add(DocTitle); DocTitleV.Last().DelChAll('\n'); DocTitleV.Last().DelChAll('\r'); DocStrV.Add(DocStr); CatNmVV.Add(CatNmV); DateTimeV.Add(DateTime); } void TWdGixRSet::SortByDate(const bool& Asc) { // sort hits by date typedef TPair<TUInt64, TInt> TUInt64IntPr; TVec<TUInt64IntPr> TmMSecsDocNV; const int Docs = GetDocs(); for (int DocN = 0; DocN < Docs; DocN++) { uint64 TmMSecs = TTm::GetMSecsFromTm(DateTimeV[DocN]); TmMSecsDocNV.Add(TUInt64IntPr(TmMSecs, DocN)); } TmMSecsDocNV.Sort(Asc); // resort the original vectors TStrV NewDocTitleV(Docs, 0), NewDocStrV(Docs, 0); TVec<TStrV> NewCatNmVV(Docs, 0); TTmV NewDateTimeV(Docs, 0); for (int NewDocN = 0; NewDocN < Docs; NewDocN++) { const int OldDocN = TmMSecsDocNV[NewDocN].Val2; NewDocTitleV.Add(DocTitleV[OldDocN]); NewDocStrV.Add(DocStrV[OldDocN]); NewCatNmVV.Add(CatNmVV[OldDocN]); NewDateTimeV.Add(DateTimeV[OldDocN]); } DocTitleV = NewDocTitleV; DocStrV = NewDocStrV; CatNmVV = NewCatNmVV; DateTimeV = NewDateTimeV; } void TWdGixRSet::PrintRes(PNotify Notify) { const int Docs = GetDocs(); Notify->OnStatus(TStr::Fmt( "All results: %d, Showing results from %d to %d", AllDocs.Val, Docs, Docs + Offset.Val)); for (int DocN = 0; DocN < Docs; DocN++) { TTm DateTime = DateTimeV[DocN]; if (DateTime.IsDef()) { Notify->OnStatus(TStr::Fmt("[%d: %s] %s ...", DocN+1, DateTime.GetWebLogDateStr().CStr(), DocTitleV[DocN].Left(50).CStr())); } else { Notify->OnStatus(TStr::Fmt("[%d] %s ...", DocN+1, DocTitleV[DocN].Left(60).CStr())); } } Notify->OnStatus(TStr::Fmt("All results: %d, Showing results from %d to %d", AllDocs.Val, Docs, Docs + Offset.Val)); } PBowDocBs TWdGixRSet::GenBowDocBs() const { PSwSet SwSet = TSwSet::New(swstEn523); PStemmer Stemmer = TStemmer::New(stmtPorter, true); PBowDocBs BowDocBs = TBowDocBs::New(SwSet, Stemmer, NULL); const int Docs = GetDocs(); for (int DocN = 0; DocN < Docs; DocN++) { const TStr& DocNm = DocTitleV[DocN]; const TStr& DocStr = DocStrV[DocN]; BowDocBs->AddHtmlDoc(DocNm, TStrV(), DocStr, true); } return BowDocBs; } ///////////////////////////////////////////////// // WdGix-Base void TWdGixBs::Filter(const TWgtWdGixItemKdV& InItemV, const TWdGixBsGrouping& Grouping, TWgtWdGixItemKdV& OutItemV) { OutItemV.Clr(); if (Grouping == wgbgName) { // group by name and remember best ranked item for it TStrFltH NameToRankH; TStrH NameToItemNH; const int Items = InItemV.Len(); for (int ItemN = 0; ItemN < Items; ItemN++) { TBlobPt BlobPt = InItemV[ItemN].Dat.GetBlobPt(); TStr Name = GetDocTitle(BlobPt); const double Rank = InItemV[ItemN].Key; if (NameToRankH.IsKey(Name)) { //TODO why? const int KeyId = NameToRankH.GetKeyId(Name); const double OldRank = NameToRankH.GetDat(Name); if (Rank > OldRank) { NameToRankH.GetDat(Name) = Rank; NameToItemNH.GetDat(Name) = ItemN; } } else { NameToRankH.AddDat(Name) = Rank; NameToItemNH.AddDat(Name) = ItemN; } } // load the best items int othe OutItemV int KeyId = NameToItemNH.FFirstKeyId(); while (NameToItemNH.FNextKeyId(KeyId)) { const int ItemN = NameToItemNH[KeyId]; OutItemV.Add(InItemV[ItemN]); } } else if (Grouping == wgbgDate) { Fail; } else if (Grouping == wgbgDateTime) { Fail; } } TWdGixBs::TWdGixBs(const TStr& _FPath, const TFAccess& _FAccess, const int64& CacheSize) { // store policy FPath = _FPath; FAccess = _FAccess; // create blob base TStr WdGixBsFNm = TStr::GetNrFPath(FPath) + TGixConst::WdGixBsFNm; DocBBs = TMBlobBs::New(WdGixBsFNm, FAccess); // load metadata store if (FAccess == faCreate) { WdGixMDS = TWdGixMDS::New(); } else { TStr WdGixMDSFNm = TStr::GetNrFPath(FPath) + TGixConst::WdGixMDSFNm; WdGixMDS = TWdGixMDS::LoadBin(WdGixMDSFNm); } // load inverted index WdGix = TWdGix::New(FPath, FAccess, CacheSize); } TWdGixBs::~TWdGixBs() { if ((FAccess == faCreate) || (FAccess == faUpdate)) { TStr WdGixMDSFNm = TStr::GetNrFPath(FPath) + TGixConst::WdGixMDSFNm; WdGixMDS->SaveBin(WdGixMDSFNm); } } void TWdGixBs::AddDoc(const TStr& DocTitle, const TStr& DocStr, const TStrV& CatNmV, const TTm& DateTime, const uchar& Wgt) { // save to blob base TMOut DocMOut; DocTitle.Save(DocMOut); DocStr.Save(DocMOut); CatNmV.Save(DocMOut); TBlobPt DocBlobPt = DocBBs->PutBlob(DocMOut.GetSIn()); // save to metadata store if (DateTime.IsDef()) { WdGixMDS->AddDate(DocBlobPt, DateTime); } // add to index WdGix->AddHtml(DocStr, DocBlobPt, Wgt); } void TWdGixBs::AddDoc(const TStr& DocTitle, const TStr& DocStoreStr, const TStr& DocIndexStr, const TStrV& CatNmV, const TTm& DateTime, const uchar& Wgt) { // save to blob base TMOut DocMOut; DocTitle.Save(DocMOut); DocStoreStr.Save(DocMOut); CatNmV.Save(DocMOut); TBlobPt DocBlobPt = DocBBs->PutBlob(DocMOut.GetSIn()); // save to metadata store if (DateTime.IsDef()) { WdGixMDS->AddDate(DocBlobPt, DateTime); } // add to index WdGix->AddHtml(DocIndexStr, DocBlobPt, Wgt); } void TWdGixBs::GetDoc(const TBlobPt& BlobPt, TStr& DocTitle, TStr& DocStr, TStrV& CatNmV) const { PSIn SIn = DocBBs->GetBlob(BlobPt); DocTitle.Load(*SIn); DocStr.Load(*SIn); CatNmV.Load(*SIn); } TStr TWdGixBs::GetDocTitle(const TBlobPt& BlobPt) const { PSIn SIn = DocBBs->GetBlob(BlobPt); TStr DocTitle; DocTitle.Load(*SIn); return DocTitle; } TStr TWdGixBs::GetDocStr(const TBlobPt& BlobPt) const { PSIn SIn = DocBBs->GetBlob(BlobPt); {TStr DocTitle; DocTitle.Load(*SIn);} TStr DocStr; DocStr.Load(*SIn); return DocStr; } TStrV TWdGixBs::GetDocCatNmV(const TBlobPt& BlobPt) const { PSIn SIn = DocBBs->GetBlob(BlobPt); {TStr DocTitle; DocTitle.Load(*SIn);} {TStr DocStr; DocStr.Load(*SIn);} TStrV CatNmV; CatNmV.Load(*SIn); return CatNmV; } PWdGixRSet TWdGixBs::SearchDoc(const TStr& QueryStr, const TWdGixBsGrouping& Grouping, TWdGixRankFun& RankFun, const int& Docs, const int& Offset, const TTm& MnDate, const TTm& MxDate) { // retrieve list of matching documents from inverted index printf(" Loading from Gix ...\n"); TWdGixItemV ResItemV; WdGix->Search(QueryStr, ResItemV); // sort and filter by date the documents printf(" Weighting %d hits ...\n", ResItemV.Len()); TWgtWdGixItemKdV FullWgtItemV(ResItemV.Len(), 0); const bool CheckMnDateP = MnDate.IsDef(); const bool CheckMxDateP = MxDate.IsDef(); for (int ItemN = 0; ItemN < ResItemV.Len(); ItemN++) { const TWdGixItem& Item = ResItemV[ItemN]; TTm DateTime = WdGixMDS->GetDateTTm(Item.GetBlobPt()); // check if document in time range if (CheckMnDateP && DateTime < MnDate) { continue; } if (CheckMxDateP && DateTime > MxDate) { continue; } // calculate the ranking weight of the document const double Wgt = RankFun(DateTime, Item.GetWgt(), Item.GetWdPos(), Item.IsTitle(), Item.IsNmObj(), Item.IsAnchor(), Item.IsEmph()); // add to the full result list FullWgtItemV.Add(TWgtWdGixItemKd(Wgt, Item)); } // filter the result list printf(" Filtering ...\n"); if (Grouping != wgbgNone) { TWgtWdGixItemKdV TmpWgtItemV; Filter(FullWgtItemV, Grouping, TmpWgtItemV); FullWgtItemV = TmpWgtItemV; } // select the correct portion of documents printf(" Sorting %d hits ...\n", FullWgtItemV.Len()); TWgtWdGixItemKdV WgtItemV; if (Docs == -1) { // return all resuts WgtItemV = FullWgtItemV; } else if (ResItemV.Len() >= (Docs + Offset)) { // get a subset of results from perticular sub-page WgtItemV = FullWgtItemV; WgtItemV.Sort(false); WgtItemV.Trunc(Docs + Offset); WgtItemV.Sort(true); WgtItemV.Trunc(Docs); } else if (ResItemV.Len() > Offset) { // last page ... WgtItemV = FullWgtItemV; WgtItemV.Sort(true); WgtItemV.Trunc(FullWgtItemV.Len() - Offset); } else { // out of range, leave empty } // sort according to the rank WgtItemV.Sort(false); // feed them to the result set printf(" Loading content for %d hits ...\n", WgtItemV.Len()); PWdGixRSet RSet = TWdGixRSet::New( QueryStr, FullWgtItemV.Len(), Offset); for (int ItemN = 0; ItemN < WgtItemV.Len(); ItemN++) { const TWdGixItem& Item = WgtItemV[ItemN].Dat; TBlobPt DocBlobPt = Item.GetBlobPt(); TStr DocTitle, DocStr; TStrV CatNmV; GetDoc(DocBlobPt, DocTitle, DocStr, CatNmV); TTm DateTime = WdGixMDS->GetDateTTm(DocBlobPt); RSet->AddDoc(DocTitle, DocStr, CatNmV, DateTime); } printf(" Done\n"); return RSet; } void TWdGixBs::AddReuters(const TStr& XmlFNm) { // parse reuters articles PXmlDoc Doc=TXmlDoc::LoadTxt(XmlFNm); // parse date TStr DateStr = Doc->GetTagTok("newsitem")->GetArgVal("date"); TTm DateTm = TTm::GetTmFromWebLogDateTimeStr(DateStr, '-'); // parse content TChA DocChA; DocChA += "<doc>"; TStr DocTitle = Doc->GetTagTok("newsitem|title")->GetTokStr(false); DocChA += "<title>"; DocChA += TXmlDoc::GetXmlStr(DocTitle); DocChA += "</title>"; DocChA += "<body>"; // get headline as emphesised text TStr DocHeadline = Doc->GetTagTok("newsitem|headline")->GetTokStr(false); DocChA += "<p><em>"; DocChA += TXmlDoc::GetXmlStr(DocHeadline); DocChA += "</em></p>\n"; // document content TXmlTokV ParTokV; Doc->GetTagTokV("newsitem|text|p", ParTokV); for (int ParTokN = 0; ParTokN < ParTokV.Len(); ParTokN++){ TStr ParStr = TXmlDoc::GetXmlStr(ParTokV[ParTokN]->GetTokStr(false)); TXmlTokV NmObjTokV; ParTokV[ParTokN]->GetTagTokV("enamex", NmObjTokV); // mark name entities for (int NmObjTokN = 0; NmObjTokN < NmObjTokV.Len(); NmObjTokN++) { TStr NmObjStr = TXmlDoc::GetXmlStr(NmObjTokV[NmObjTokN]->GetTokStr(false)); ParStr.ChangeStrAll(NmObjStr, "<nmobj>" + NmObjStr + "</nmobj>"); } DocChA += "<p>"; DocChA += ParStr; DocChA += "</p>"; } DocChA += "</body></doc>"; // categories TStrV CatNmV; TXmlTokV CdsTokV; Doc->GetTagTokV("newsitem|metadata|codes", CdsTokV); for (int CdsTokN = 0; CdsTokN < CdsTokV.Len(); CdsTokN++){ PXmlTok CdsTok = CdsTokV[CdsTokN]; TXmlTokV CdTokV; CdsTok->GetTagTokV("code", CdTokV); if (CdsTok->GetArgVal("class") == "bip:topics:1.0"){ for (int CdTokN = 0; CdTokN < CdTokV.Len(); CdTokN++){ TStr CdNm = CdTokV[CdTokN]->GetArgVal("code"); CatNmV.AddMerged(CdNm); } } else if (CdsTok->GetArgVal("class")=="bip:countries:1.0"){ for (int CdTokN = 0; CdTokN < CdTokV.Len(); CdTokN++){ TStr CdNm=CdTokV[CdTokN]->GetArgVal("code"); CatNmV.AddMerged(CdNm); } } else if (CdsTok->GetArgVal("class")=="bip:industries:1.0"){ for (int CdTokN = 0; CdTokN < CdTokV.Len(); CdTokN++){ TStr CdNm=CdTokV[CdTokN]->GetArgVal("code"); CatNmV.AddMerged(CdNm); } } else { Fail; } } // store the news article to the search base AddDoc(DocTitle, DocChA, CatNmV, DateTm); } void TWdGixBs::IndexReuters(const TStr& FPath) { PNotify Notify = TStdNotify::New(); Notify->OnStatus("Loading Reuters documents from " + FPath + " ...\n"); TFFile FFile(FPath, ".xml", true); TStr XmlFNm; int Files = 0; while (FFile.Next(XmlFNm)) { //if (Files > 10000) { break; } // load document if (TFile::Exists(XmlFNm)) { AddReuters(XmlFNm); Files++; } // print statistics if (Files % 1000 == 0) { Notify->OnStatus(TStr::Fmt("F:%d\r", Files)); } } Notify->OnStatus(TStr::Fmt("F:%d\n", Files)); } void TWdGixBs::IndexNmEnBs(const TStr& FNm) { PNotify Notify = TStdNotify::New(); Notify->OnStatus("Loading name-entitites from " + FNm + " ...\n"); // load name-entity base together with contexts PNmEnBs NmEnBs = TNmEnBs::LoadBin(FNm, true); // add name-entities to int NmEnKeyId = NmEnBs->GetFFirstNmEn(); int NmEnN = 0; const int NmEns = NmEnBs->GetNmEns(); while (NmEnBs->GetFNextNmEn(NmEnKeyId)) { if (NmEnN > 100000) { break; } // print statistics if (NmEnN % 1000 == 0) { Notify->OnStatus(TStr::Fmt("N:%d/%d\r", NmEnN, NmEns)); } // get name-entity name TStr NmEnStr = NmEnBs->GetNmEnStr(NmEnKeyId); IAssertR(NmEnBs->IsNmEn(NmEnStr), NmEnStr); // iterate over all the mentions of the name-entity // and concatenate them accross days THash<TUInt, TChA> DateIntToCtxH; THash<TUInt, TInt> DateIntToCountH; const TIntV& NmEnCtxIdV = NmEnBs->GetCtxIdV(NmEnKeyId); for (int CtxIdN = 0; CtxIdN < NmEnCtxIdV.Len(); CtxIdN++) { const int CtxId = NmEnCtxIdV[CtxIdN]; TStr NmEnCtxStr = NmEnBs->GetCtxStr(CtxId); TTm NmEnCtxTm = NmEnBs->GetCtxTm(CtxId); const uint DateInt = TTm::GetDateIntFromTm(NmEnCtxTm); DateIntToCtxH.AddDat(DateInt) += NmEnCtxStr; DateIntToCountH.AddDat(DateInt)++; } // store the name-entity to the search base per day int CtxKeyId = DateIntToCtxH.FFirstKeyId(); while (DateIntToCtxH.FNextKeyId(CtxKeyId)) { const int DateInt = DateIntToCtxH.GetKey(CtxKeyId); TTm CtxDate = TTm::GetTmFromDateTimeInt(DateInt); TStr CtxStr = DateIntToCtxH[CtxKeyId]; const uchar Wgt = uchar(DateIntToCountH.GetDat(DateInt).Val); AddDoc(NmEnStr, CtxStr, TStrV(), CtxDate, Wgt); } // next NmEnN++; } Notify->OnStatus(TStr::Fmt("N:%d/%d", NmEnN, NmEns)); } void TWdGixBs::IndexNyt(const TStr& XmlFNm) { PNotify Notify = TStdNotify::New(); Notify->OnStatus("Loading NYT documents from " + XmlFNm + " ...\n"); PSIn SIn = TFIn::New(XmlFNm); int Docs = 0; TStr LastTitle = ""; forever { if (Docs % 1000 == 0) { Notify->OnStatus(TStr::Fmt("Docs: %d\r", Docs)); } PXmlDoc Doc = TXmlDoc::LoadTxt(SIn); Docs++; if (!Doc->IsOk()) { printf("%s - %s\n", LastTitle.CStr(), Doc->GetMsgStr().CStr()); break; } // parse date TStr DateStr = Doc->GetTagTok("newsitem")->GetArgVal("date"); TTm DateTm = TTm::GetTmFromWebLogDateTimeStr(DateStr, '-'); // parse content TChA DocChA; DocChA += "<doc>"; TStr DocTitle = Doc->GetTagTok("newsitem|title")->GetTokStr(false); DocChA += "<title>"; DocChA += TXmlDoc::GetXmlStr(DocTitle); DocChA += "</title>"; DocChA += "<body>"; // document content TXmlTokV ParTokV; Doc->GetTagTokV("newsitem|text|p", ParTokV); for (int ParTokN = 0; ParTokN < ParTokV.Len(); ParTokN++){ TStr ParStr = TXmlDoc::GetXmlStr(ParTokV[ParTokN]->GetTokStr(false)); TXmlTokV NmObjTokV; ParTokV[ParTokN]->GetTagTokV("ent", NmObjTokV); // mark name entities for (int NmObjTokN = 0; NmObjTokN < NmObjTokV.Len(); NmObjTokN++) { TStr NmObjStr = TXmlDoc::GetXmlStr(NmObjTokV[NmObjTokN]->GetTokStr(false)); ParStr.ChangeStrAll(NmObjStr, "<nmobj>" + NmObjStr + "</nmobj>"); } DocChA += "<p>"; DocChA += ParStr; DocChA += "</p>"; } DocChA += "</body></doc>"; // store the news article to the search base AddDoc(DocTitle, DocChA, TStrV(), DateTm); LastTitle = DocTitle; } Notify->OnStatus(TStr::Fmt("Docs: %d", Docs)); } ///////////////////////////////////////////////// // Search-Topics TSearchTopics::TSearchTopics(PWdGixRSet RSet, const int& Topics) { PBowDocBs BowDocBs = RSet->GenBowDocBs(); TRnd Rnd(1); PBowDocPart BowDocPart = TBowClust::GetKMeansPart( TNullNotify::New(), BowDocBs, TBowSim::New(bstCos), Rnd, Topics, 1, 10, 1, bwwtLogDFNrmTFIDF, 0.0, 0); TopicV.Gen(Topics, 0); TIntH FrameH; THash<TInt, TIntH> FrameTopicHH; for (int ClustN = 0; ClustN < BowDocPart->GetClusts(); ClustN++) { PBowDocPartClust Clust = BowDocPart->GetClust(ClustN); TStr TopicNm = Clust->GetConceptSpV()->GetStr(BowDocBs, 3, 1, ", ", false, false); TopicV.Add(TopicNm); for (int DocN = 0; DocN < Clust->GetDocs(); DocN++) { const int DocId = Clust->GetDId(DocN); TTm DocDate = RSet->GetDocDateTime(DocId); //const uint FrameId = TTm::GetMonthIntFromTm(DocDate); const uint FrameId = TTm::GetYearIntFromTm(DocDate); FrameH.AddDat(FrameId)++; FrameTopicHH.AddDat(FrameId).AddDat(ClustN)++; } } const int Frames = FrameH.Len(); FrameV.Gen(Frames, 0); TopicFrameFqVV.Gen(Topics, Frames); TopicFrameFqVV.PutAll(0.0); FrameH.SortByKey(); int FrameKeyId = FrameH.FFirstKeyId(); while (FrameH.FNextKeyId(FrameKeyId)) { int FrameId = FrameH.GetKey(FrameKeyId); // load name TTm FrameDate = TTm::GetTmFromDateTimeInt(FrameId); //TStr FrameNm = TStr::Fmt("%4d-%2d", FrameDate.GetYear(), FrameDate.GetMonth()); TStr FrameNm = TStr::Fmt("%4d", FrameDate.GetYear()); const int FrameN = FrameV.Add(FrameNm); // load counts //const int FrameCounts = FrameH.GetDat(FrameId); const TIntH& TopicH = FrameTopicHH.GetDat(FrameId); int TopicKeyId = TopicH.FFirstKeyId(); int CountSum = 0; while (TopicH.FNextKeyId(TopicKeyId)) { const int TopicN = TopicH.GetKey(TopicKeyId); int TopicCount = TInt::Abs(TopicH.GetDat(TopicKeyId)) > 1000 ? 0 : TopicH.GetDat(TopicKeyId)(); CountSum += TopicCount; const double Fq = double(CountSum); // / double(FrameCounts); TopicFrameFqVV(TopicN, FrameN) = Fq; } } } ///////////////////////////////////////////////// // Triplet-Inverted-Index-Item TTrGixItem::TTrGixItem(const TBlobPt& BlobPt, const int& _SubjectId, const int& _PredicatId, const int& _ObjectId, const int& _WdId, const uchar& Type, const uchar& Pos, const bool& Full, const bool& Stem, const uchar& Hyper): Seg(BlobPt.GetSeg()), Addr(BlobPt.GetAddr()), SubjectId(_SubjectId), PredicatId(_PredicatId), ObjectId(_ObjectId), WdId(_WdId) { SetWordInfo(Type, Pos, Full, Stem, Hyper); ClrMergeInfo(); } TTrGixItem::TTrGixItem(TSIn& SIn) { SIn.Load(Seg); SIn.Load(Addr); SIn.Load(SubjectId); SIn.Load(PredicatId); SIn.Load(ObjectId); SIn.Load(WdId); SIn.Load(WdInfo); ClrMergeInfo(); } void TTrGixItem::Save(TSOut& SOut) const { SOut.Save(Seg); SOut.Save(Addr); SOut.Save(SubjectId); SOut.Save(PredicatId); SOut.Save(ObjectId); SOut.Save(WdId); SOut.Save(WdInfo); } bool TTrGixItem::operator==(const TTrGixItem& Item) const { return ((Seg==Item.Seg)&&(Addr==Item.Addr)&& (SubjectId==Item.SubjectId)&& (PredicatId==Item.PredicatId)&& (ObjectId==Item.ObjectId)); } bool TTrGixItem::operator<(const TTrGixItem& Item) const { return (Seg<Item.Seg) || ((Seg==Item.Seg)&&(Addr<Item.Addr)) || ((Seg==Item.Seg)&&(Addr==Item.Addr)&&(SubjectId<Item.SubjectId)) || ((Seg==Item.Seg)&&(Addr==Item.Addr)&&(SubjectId==Item.SubjectId)&&(PredicatId<Item.PredicatId)) || ((Seg==Item.Seg)&&(Addr==Item.Addr)&&(SubjectId==Item.SubjectId)&&(PredicatId==Item.PredicatId)&&(ObjectId<Item.ObjectId)); } void TTrGixItem::SetWordInfo(const uchar& Type, const uchar& Pos, const bool& Full, const bool& Stem, const uchar& Hyper) { TTrGixItemWdInfo Info; Info.Short = 0; Info.Bits.Type = Type; Info.Bits.Pos = Type; Info.Bits.Full = Full ? 1 : 0; Info.Bits.Stem = Stem ? 1 : 0; Info.Bits.Hyper = Hyper; WdInfo = Info.Short; } ///////////////////////////////////////////////// // Triplet-Inverted-Index char TTrGix::SubjectType = 0; char TTrGix::SubjectWdType = 1; char TTrGix::SubjectAttrWdType = 2; char TTrGix::SubjectStemType = 3; char TTrGix::SubjectAttrStemType = 4; char TTrGix::PredicatType = 5; char TTrGix::PredicatWdType = 6; char TTrGix::PredicatAttrWdType = 7; char TTrGix::PredicatStemType = 8; char TTrGix::PredicatAttrStemType = 9; char TTrGix::ObjectType = 10; char TTrGix::ObjectWdType = 11; char TTrGix::ObjectAttrWdType = 12; char TTrGix::ObjectStemType = 13; char TTrGix::ObjectAttrStemType = 14; void TTrGix::AddTrPart(const int& FullId, const char& Type, const int& SubjectId, const int& PredicatId, const int& ObjectId, const TBlobPt& BlobPt) { // add to the index Gix->AddItem(TTrGixKey(FullId, Type), TTrGixItem(BlobPt, SubjectId, PredicatId, ObjectId, FullId, Type, 0, true, false, 0)); } void TTrGix::AddTrPart(const TIntPrV& IdPrV, const char& WdType, const char& StemType, const int& SubjectId, const int& PredicatId, const int& ObjectId, const TBlobPt& BlobPt) { for (int IdPrN = 0; IdPrN < IdPrV.Len(); IdPrN++) { // add word to the index const int WdId = IdPrV[IdPrN].Val1; Gix->AddItem(TTrGixKey(WdId, WdType), TTrGixItem(BlobPt, SubjectId, PredicatId, ObjectId, WdId, WdType, IdPrN, false, false, 0)); // add stem to the index const int StemId = IdPrV[IdPrN].Val2; Gix->AddItem(TTrGixKey(StemId, StemType), TTrGixItem(BlobPt, SubjectId, PredicatId, ObjectId, StemId, StemType, IdPrN, false, true, 0)); } } TTrGix::PTGixExpItem TTrGix::GetExactExp(const TStr& Str, const char& Type) { TTrGixKey FullTrKey = TTrGixKey(GetWordId(Str, false), Type); return TTGixExpItem::NewItem(FullTrKey); } TTrGix::PTGixExpItem TTrGix::GetPartExp(const TStr& Str, const char& WdType, const char& StemType) { // get word/stem ids from the string TIntPrV WordStemIdV; GetWordIdV(Str, WordStemIdV, false); // prepare the expresion for these words/stems PTGixExpItem Exp = TTGixExpItem::NewEmpty(); for (int WordStemIdN = 0; WordStemIdN < WordStemIdV.Len(); WordStemIdN++) { // prepare the search keys for both word and for the stem TTrGixKey WdKey(WordStemIdV[WordStemIdN].Val1, WdType); TTrGixKey StemKey(WordStemIdV[WordStemIdN].Val2, StemType); // either of the two should appear PTGixExpItem ExpItem = TTGixExpItem::NewOr( TTGixExpItem::NewItem(WdKey), TTGixExpItem::NewItem(StemKey)); // update the expresion with the new word/stem if (Exp->IsEmpty()) { Exp = ExpItem; } else { Exp = TTGixExpItem::NewAnd(Exp, ExpItem); } } return Exp; } TTrGix::TTrGix(const TStr& _FPath, const TFAccess& _FAccess, const int64& CacheSize) { // store policy FPath = _FPath; FAccess = _FAccess; // prepare gix Gix = TTGix::New(TGixConst::TrGixFNm, FPath, FAccess, CacheSize); // load word tables if (FAccess == faCreate) { Stemmer = TStemmer::New(stmtPorter, true); } else { // prepare file name TStr TrGixDatFNm = TStr::GetNrFPath(FPath) + TGixConst::TrGixDatFNm; // load stuff TFIn FIn(TrGixDatFNm); WordH.Load(FIn); Stemmer = TStemmer::Load(FIn); } } TTrGix::~TTrGix() { if ((FAccess == faCreate) || (FAccess == faUpdate)) { // prepare file name TStr TrGixDatFNm = TStr::GetNrFPath(FPath) + TGixConst::TrGixDatFNm; // save word tables TFOut FOut(TrGixDatFNm); WordH.Save(FOut); Stemmer->Save(FOut); } } int TTrGix::GetWordId(const TStr& WordStr, const bool& AddIfNotExistP) { if (WordStr.Empty()) { return -1; } // should we just do a look-up or add the word if not exist if (AddIfNotExistP) { return WordH.AddKey(WordStr.GetUc()); } else { return WordH.GetKeyId(WordStr.GetUc()); } } inline TStr TTrGix::GetWordStr(const int& WId) const { return WId != -1 ? WordH.GetKey(WId) : ""; } void TTrGix::GetWordIdV(const TStr& Str, TIntPrV& WordStemIdV, const bool& AddIfNotExistP) { // tokenize the phrase PSIn HtmlSIn = TStrIn::New(Str); THtmlLx HtmlLx(HtmlSIn); HtmlLx.GetSym(); while (HtmlLx.Sym != hsyEof) { if (HtmlLx.Sym == hsyStr) { const TStr WordStr = HtmlLx.UcChA; // get the word id const int WordId = GetWordId(WordStr, AddIfNotExistP); // get the stem id const int StemId = GetWordId(Stemmer->GetStem(WordStr), AddIfNotExistP); // store it WordStemIdV.Add(TIntPr(WordId, StemId)); } HtmlLx.GetSym(); } } void TTrGix::GetWordIdV(const TStrV& WordStrV, TIntPrV& WordStemIdV, const bool& AddIfNotExistP) { // just iterate over all the elements and get their word-stem pairs for (int WordStrN = 0; WordStrN < WordStrV.Len(); WordStrN++) { GetWordIdV(WordStrV[WordStrN], WordStemIdV, AddIfNotExistP); } } void TTrGix::AddTr(const TStr& SubjectStr, const TStrV& SubjectAttrV, const TStr& PredicatStr, const TStrV& PredicatAttrV, const TStr& ObjectStr, const TStrV& ObjectAttrV, const TBlobPt& BlobPt) { // store full strings const int SubjectId = GetWordId(SubjectStr, true); const int PredicatId = GetWordId(PredicatStr, true); const int ObjectId = GetWordId(ObjectStr, true); // add them to the index AddTrPart(SubjectId, SubjectType, SubjectId, PredicatId, ObjectId, BlobPt); AddTrPart(PredicatId, PredicatType, SubjectId, PredicatId, ObjectId, BlobPt); AddTrPart(ObjectId, ObjectType, SubjectId, PredicatId, ObjectId, BlobPt); // get ids of separate words and their stems, including from attributes TIntPrV SubjectWIdSIdV; GetWordIdV(SubjectStr, SubjectWIdSIdV, true); TIntPrV SubjectAttrWIdSIdV; GetWordIdV(SubjectAttrV, SubjectAttrWIdSIdV, true); TIntPrV PredicatWIdSIdV; GetWordIdV(PredicatStr, PredicatWIdSIdV, true); TIntPrV PredicatAttrWIdSIdV; GetWordIdV(PredicatAttrV, PredicatAttrWIdSIdV, true); TIntPrV ObjectWIdSIdV; GetWordIdV(ObjectStr, ObjectWIdSIdV, true); TIntPrV ObjectAttrWIdSIdV; GetWordIdV(ObjectAttrV, ObjectAttrWIdSIdV, true); // add them to the index AddTrPart(SubjectWIdSIdV, SubjectWdType, SubjectStemType, SubjectId, PredicatId, ObjectId, BlobPt); AddTrPart(SubjectAttrWIdSIdV, SubjectAttrWdType, SubjectAttrStemType, SubjectId, PredicatId, ObjectId, BlobPt); AddTrPart(PredicatWIdSIdV, PredicatWdType, PredicatStemType, SubjectId, PredicatId, ObjectId, BlobPt); AddTrPart(PredicatAttrWIdSIdV, PredicatAttrWdType, PredicatAttrStemType, SubjectId, PredicatId, ObjectId, BlobPt); AddTrPart(ObjectWIdSIdV, ObjectWdType, ObjectStemType, SubjectId, PredicatId, ObjectId, BlobPt); AddTrPart(ObjectAttrWIdSIdV, ObjectAttrWdType, ObjectAttrStemType, SubjectId, PredicatId, ObjectId, BlobPt); } bool TTrGix::SearchExact(const TStr& SubjectStr, const TStr& PredicatStr, const TStr& ObjectStr, TTrGixItemV& ResItemV) { // generate exprasion PTGixExpItem Exp = TTGixExpItem::NewEmpty(); if (!SubjectStr.Empty()) { PTGixExpItem ExpItem = GetExactExp(SubjectStr, SubjectType); if (Exp->IsEmpty()) { Exp = ExpItem; } else { Exp = TTGixExpItem::NewAnd(Exp, ExpItem); } } if (!PredicatStr.Empty()) { PTGixExpItem ExpItem = GetExactExp(PredicatStr, PredicatType); if (Exp->IsEmpty()) { Exp = ExpItem; } else { Exp = TTGixExpItem::NewAnd(Exp, ExpItem); } } if (!ObjectStr.Empty()) { PTGixExpItem ExpItem = GetExactExp(ObjectStr, ObjectType); if (Exp->IsEmpty()) { Exp = ExpItem; } else { Exp = TTGixExpItem::NewAnd(Exp, ExpItem); } } // evaluate the expresion return Exp->Eval(Gix, ResItemV); } bool TTrGix::SearchPart(const TStr& SubjectStr, const TStr& PredicatStr, const TStr& ObjectStr, TTrGixItemV& ResItemV, const bool& IncExactP) { // generate exprasion PTGixExpItem Exp = TTGixExpItem::NewEmpty(); if (!SubjectStr.Empty()) { PTGixExpItem ExpItem = GetPartExp(SubjectStr, SubjectWdType, SubjectStemType); if (IncExactP) { TTGixExpItem::NewOr(GetExactExp(SubjectStr, SubjectType), ExpItem); } if (Exp->IsEmpty()) { Exp = ExpItem; } else { Exp = TTGixExpItem::NewAnd(Exp, ExpItem); } } if (!PredicatStr.Empty()) { PTGixExpItem ExpItem = GetPartExp(PredicatStr, PredicatWdType, PredicatStemType); if (IncExactP) { TTGixExpItem::NewOr(GetExactExp(PredicatStr, PredicatType), ExpItem); } if (Exp->IsEmpty()) { Exp = ExpItem; } else { Exp = TTGixExpItem::NewAnd(Exp, ExpItem); } } if (!ObjectStr.Empty()) { PTGixExpItem ExpItem = GetPartExp(ObjectStr, ObjectWdType, ObjectStemType); if (IncExactP) { TTGixExpItem::NewOr(GetExactExp(ObjectStr, ObjectType), ExpItem); } if (Exp->IsEmpty()) { Exp = ExpItem; } else { Exp = TTGixExpItem::NewAnd(Exp, ExpItem); } } // evaluate the expresion return Exp->Eval(Gix, ResItemV); } ///////////////////////////////////////////////// // TrGix-Result-Set void TTrGixRSet::AddTr(const TStrTr& TrStr, const TBlobPtV& TrAttrBlobPtV) { TrStrV.Add(TrStr); TrAttrBlobPtVV.Add(TrAttrBlobPtV); } void TTrGixRSet::GetSubjectV(TStrIntKdV& SubjectStrWgtV) { TIntStrKdV SubjectWgtStrV; for (int TrN = 0; TrN < GetTrs(); TrN++) { const TStr& SubjectStr = TrStrV[TrN].Val1; const int Wgt = GetTrCount(TrN); SubjectWgtStrV.Add(TIntStrKd(Wgt, SubjectStr)); } SubjectWgtStrV.Sort(false); GetSwitchedKdV<TInt, TStr>(SubjectWgtStrV, SubjectStrWgtV); } void TTrGixRSet::GetPredicatV(TStrIntKdV& PredicatStrWgtV) { TIntStrKdV PredicatWgtStrV; for (int TrN = 0; TrN < GetTrs(); TrN++) { const TStr& PredicatStr = TrStrV[TrN].Val2; const int Wgt = GetTrCount(TrN); PredicatWgtStrV.Add(TIntStrKd(Wgt, PredicatStr)); } PredicatWgtStrV.Sort(false); GetSwitchedKdV<TInt, TStr>(PredicatWgtStrV, PredicatStrWgtV); } void TTrGixRSet::GetObjectV(TStrIntKdV& ObjectStrWgtV) { TIntStrKdV ObjectWgtStrV; for (int TrN = 0; TrN < GetTrs(); TrN++) { const TStr& ObjectStr = TrStrV[TrN].Val3; const int Wgt = GetTrCount(TrN); ObjectWgtStrV.Add(TIntStrKd(Wgt, ObjectStr)); } ObjectWgtStrV.Sort(false); GetSwitchedKdV<TInt, TStr>(ObjectWgtStrV, ObjectStrWgtV); } void TTrGixRSet::PrintRes(const bool& PrintSentsP, PNotify Notify) const { // result set stats printf("Query:\n"); printf(" Subject: '%s'\n", GetSubjectStr().CStr()); printf(" Predicat: '%s'\n", GetPredicatStr().CStr()); printf(" Object: '%s'\n", GetObjectStr().CStr()); printf("Displaying: %d - %d (All hits: %d)\n", GetOffset()+1, Offset.Val+GetTrs()+1, GetAllTrs()); // hits for (int TrN = 0; TrN < GetTrs(); TrN++) { printf("%d. [%s <- %s -> %s], (Support:%d)\n", TrN+GetOffset()+1, GetTrSubjectStr(TrN).CStr(), GetTrPredicatStr(TrN).CStr(), GetTrObjectStr(TrN).CStr(), GetTrCount(TrN)); //if (PrintSentsP) { // for (int SentN = 0; SentN < GetTrSents(TrN); SentN++) { // const TStr& SentStr = GetTrSentStr(TrN, SentN); // if (SentStr.Len() < 110) { printf(" %s\n", SentStr.CStr()); } // else { printf(" %s...\n", SentStr.Left(110).CStr()); } // } //} } } ///////////////////////////////////////////////// // TrGix-Merger ///////////////////////////////////////////////// // TrGix-Base void TTrGixBs::GetAttrV(PXmlTok XmlTok, TStrV& AttrV) { TXmlTokV AttrTokV; XmlTok->GetTagTokV("attrib", AttrTokV); for (int AttrTokN = 0; AttrTokN < AttrTokV.Len(); AttrTokN++) { PXmlTok AttrTok = AttrTokV[AttrTokN]; AttrV.Add(AttrTok->GetStrArgVal("word")); GetAttrV(AttrTok, AttrV); } } TTrGixBs::TTrGixBs(const TStr& _FPath, const TFAccess& _FAccess, const int64& CacheSize) { // store policy FPath = _FPath; FAccess = _FAccess; // create document blob base TStr TrGixDocBsFNm = TStr::GetNrFPath(FPath) + TGixConst::TrGixDocBsFNm; DocBBs = TMBlobBs::New(TrGixDocBsFNm, FAccess); // create sentence blob base TStr TrGixSentBsFNm = TStr::GetNrFPath(FPath) + TGixConst::TrGixSentBsFNm; SentBBs = TMBlobBs::New(TrGixSentBsFNm, FAccess); // create triplet attribute blob base TStr TrGixTrAttrBsFNm = TStr::GetNrFPath(FPath) + TGixConst::TrGixTrAttrBsFNm; TrAttrBBs = TMBlobBs::New(TrGixTrAttrBsFNm, FAccess); // load inverted index TrGix = TTrGix::New(FPath, FAccess, CacheSize); } TTrGixBs::~TTrGixBs() { if ((FAccess == faCreate) || (FAccess == faUpdate)) { // save whatever doesnt save itself automaticaly in destructor } } TBlobPt TTrGixBs::AddDoc(const TStr& DocTitle, const TStr& DocStr, const TStrV& CatNmV) { // save to blob base TMOut DocMOut; DocTitle.Save(DocMOut); DocStr.Save(DocMOut); CatNmV.Save(DocMOut); TBlobPt DocBlobPt = DocBBs->PutBlob(DocMOut.GetSIn()); return DocBlobPt; } TBlobPt TTrGixBs::AddSent(const TStr& SentStr) { TMOut SentMOut; SentStr.Save(SentMOut); TBlobPt SentBlobPt = SentBBs->PutBlob(SentMOut.GetSIn()); return SentBlobPt; } TBlobPt TTrGixBs::AddTrAttr(const TStr& SubjectStr, const TStrV& SubjectAttrV, const TStr& PredicatStr, const TStrV& PredicatAttrV, const TStr& ObjectStr, const TStrV& ObjectAttrV, const TBlobPt& SentBlobPt, const TBlobPt& DocBlobPt) { TMOut TrAttrMOut; SubjectStr.Save(TrAttrMOut); SubjectAttrV.Save(TrAttrMOut); PredicatStr.Save(TrAttrMOut); PredicatAttrV.Save(TrAttrMOut); ObjectStr.Save(TrAttrMOut); ObjectAttrV.Save(TrAttrMOut); SentBlobPt.Save(TrAttrMOut); DocBlobPt.Save(TrAttrMOut); TBlobPt TrAttrBlobPt = TrAttrBBs->PutBlob(TrAttrMOut.GetSIn()); return TrAttrBlobPt; } void TTrGixBs::AddTr(const TStr& SubjectStr, const TStrV& SubjectAttrV, const TStr& PredicatStr, const TStrV& PredicatAttrV, const TStr& ObjectStr, const TStrV& ObjectAttrV, const TBlobPt& TrAttrBlobPt) { TrGix->AddTr(SubjectStr, SubjectAttrV, PredicatStr, PredicatAttrV, ObjectStr, ObjectAttrV, TrAttrBlobPt); } void TTrGixBs::GetDoc(const TBlobPt& DocBlobPt, TStr& DocTitle, TStr& DocStr, TStrV& CatNmV) const { PSIn SIn = DocBBs->GetBlob(DocBlobPt); DocTitle.Load(*SIn); DocStr.Load(*SIn); CatNmV.Load(*SIn); } TStr TTrGixBs::GetDocTitle(const TBlobPt& BlobPt) const { PSIn SIn = DocBBs->GetBlob(BlobPt); TStr DocTitle; DocTitle.Load(*SIn); return DocTitle; } TStr TTrGixBs::GetDocStr(const TBlobPt& BlobPt) const { PSIn SIn = DocBBs->GetBlob(BlobPt); {TStr DocTitle; DocTitle.Load(*SIn);} TStr DocStr; DocStr.Load(*SIn); return DocStr; } TStrV TTrGixBs::GetDocCatNmV(const TBlobPt& BlobPt) const { PSIn SIn = DocBBs->GetBlob(BlobPt); {TStr DocTitle; DocTitle.Load(*SIn);} {TStr DocStr; DocStr.Load(*SIn);} TStrV CatNmV; CatNmV.Load(*SIn); return CatNmV; } TStr TTrGixBs::GetSentStr(const TBlobPt& SentBlobPt) { PSIn SIn = SentBBs->GetBlob(SentBlobPt); return TStr(*SIn); } void TTrGixBs::GetTrAttr(const TBlobPt& TrAttrBlobPt, TStr& SubjectStr, TStrV& SubjectAttrV, TStr& PredicatStr, TStrV& PredicatAttrV, TStr& ObjectStr, TStrV& ObjectAttrV, TBlobPt& SentBlobPt, TBlobPt& DocBlobPt) { PSIn SIn = TrAttrBBs->GetBlob(TrAttrBlobPt); SubjectStr.Load(*SIn); SubjectAttrV.Load(*SIn); PredicatStr.Load(*SIn); PredicatAttrV.Load(*SIn); ObjectStr.Load(*SIn); ObjectAttrV.Load(*SIn); SentBlobPt = TBlobPt(*SIn); DocBlobPt = TBlobPt(*SIn); } PTrGixRSet TTrGixBs::SearchTr(const TStr& SubjectStr, const TStr& PredicatStr, const TStr& ObjectStr, TTrGixRankFun& RankFun, const int& Docs, const int& Offset, const bool& ExactP) { // get all hits from index //printf(" Loading from Gix ...\n"); TTrGixItemV ResItemV; if (ExactP) { TrGix->SearchExact(SubjectStr, PredicatStr, ObjectStr, ResItemV); } else { TrGix->SearchPart(SubjectStr, PredicatStr, ObjectStr, ResItemV, true); } // grouping the hits by triplets //printf(" Grouping %d hits ...\n", ResItemV.Len()); THash<TIntTr, TIntV> TrToItemVH; for (int ItemN = 0; ItemN < ResItemV.Len(); ItemN++) { const TTrGixItem& Item = ResItemV[ItemN]; TrToItemVH.AddDat(Item.GetIdTr()).Add(ItemN); } // rank the triplets //printf(" Ranking %d triplets ...\n", TrToItemVH.Len()); TFltIntKdV FullWgtTrKeyIdV; int TrKeyId = TrToItemVH.FFirstKeyId(); while (TrToItemVH.FNextKeyId(TrKeyId)) { const double Wgt = RankFun(TrToItemVH[TrKeyId].Len()); FullWgtTrKeyIdV.Add(TFltIntKd(Wgt, TrKeyId)); } // select the correct portion of documents //printf(" Sorting %d triplets ...\n", TrToItemVH.Len()); TFltIntKdV WgtTrKeyIdV; if (Docs == -1) { // return all resuts WgtTrKeyIdV = FullWgtTrKeyIdV; } else if (ResItemV.Len() >= (Docs + Offset)) { // get a subset of results from perticular sub-page WgtTrKeyIdV = FullWgtTrKeyIdV; WgtTrKeyIdV.Sort(false); WgtTrKeyIdV.Trunc(Docs + Offset); WgtTrKeyIdV.Sort(true); WgtTrKeyIdV.Trunc(Docs); } else if (ResItemV.Len() > Offset) { // last page ... WgtTrKeyIdV = FullWgtTrKeyIdV; WgtTrKeyIdV.Sort(true); WgtTrKeyIdV.Trunc(FullWgtTrKeyIdV.Len() - Offset); } else { // out of range, leave empty } // sort according to the rank WgtTrKeyIdV.Sort(false); // feed them to the result set //printf(" Loading content for %d triplets ...\n", WgtTrKeyIdV.Len()); PTrGixRSet RSet = TTrGixRSet::New(SubjectStr, PredicatStr, ObjectStr, FullWgtTrKeyIdV.Len(), Offset); for (int TrN = 0; TrN < WgtTrKeyIdV.Len(); TrN++) { const int TrKeyId = WgtTrKeyIdV[TrN].Dat; const TIntTr& WIdTr = TrToItemVH.GetKey(TrKeyId); const TIntV& ItemV = TrToItemVH[TrKeyId]; TStr SubjectStr = TrGix->GetWordStr(WIdTr.Val1); TStr PredicatStr = TrGix->GetWordStr(WIdTr.Val2); TStr ObjectStr = TrGix->GetWordStr(WIdTr.Val3); TStrTr TrStr(SubjectStr, PredicatStr, ObjectStr); // load triplet attribute blob pointers TBlobPtV TrAttrBlobPtV; for (int ItemN = 0; ItemN < ItemV.Len(); ItemN++) { const TTrGixItem& Item = ResItemV[ItemV[ItemN]]; TBlobPt TrAttrBlobPt = Item.GetBlobPt(); TrAttrBlobPtV.Add(TrAttrBlobPt); } // add the triplet to the RSet RSet->AddTr(TrStr, TrAttrBlobPtV); } //printf(" Done\n"); return RSet; } void TTrGixBs::AddReuters(const TStr& XmlFNm, int& Trs, const PSOut& CsvOut) { PNotify Notify = TStdNotify::New(); // create empty document TBlobPt EmptyDocBlobPt = AddDoc("No full document text!"); // we skip the top tak so we only parse one sentence at a time PSIn XmlSIn = TFIn::New(XmlFNm); TXmlDoc::SkipTopTag(XmlSIn); PXmlDoc XmlDoc; int XmlDocs = 0; forever{ // print count if (Trs % 100 == 0) { Notify->OnStatus(TStr::Fmt("%d\r", Trs)); } // load xml tree XmlDocs++; XmlDoc = TXmlDoc::LoadTxt(XmlSIn); // stop if at the last tag if (!XmlDoc->IsOk()) { break; } // extract documents from xml-trees PXmlTok TopTok = XmlDoc->GetTok(); if (TopTok->IsTag("sentence")){ // read and store the document from which the sentence comes TStr DocStr = ""; TBlobPt DocBlobPt = EmptyDocBlobPt; // read and store the sentence from where the triplet comes TStr SentStr = TopTok->GetTagTok("originalSentence")->GetTokStr(false); TBlobPt SentBlobPt = AddSent(SentStr); // iterate over all the triplets and add them to the index TXmlTokV TrTokV; TopTok->GetTagTokV("triplet", TrTokV); for (int TrTokN = 0; TrTokN < TrTokV.Len(); TrTokN++) { PXmlTok TrTok = TrTokV[TrTokN]; TStr SubjectStr = TrTok->GetTagTok("subject")->GetStrArgVal("word"); TStr PredicatStr = TrTok->GetTagTok("verb")->GetStrArgVal("word"); TStr ObjectStr = TrTok->GetTagTok("object")->GetStrArgVal("word"); TStrV SubjectAttrV; GetAttrV(TrTok->GetTagTok("subject"), SubjectAttrV); TStrV PredicatAttrV; GetAttrV(TrTok->GetTagTok("verb"), PredicatAttrV); TStrV ObjectAttrV; GetAttrV(TrTok->GetTagTok("object"), ObjectAttrV); TBlobPt TrAttrBlobPt = AddTrAttr(SubjectStr, SubjectAttrV, PredicatStr, PredicatAttrV, ObjectStr, ObjectAttrV, SentBlobPt, DocBlobPt); AddTr(SubjectStr, SubjectAttrV, PredicatStr, PredicatAttrV, ObjectStr, ObjectAttrV, TrAttrBlobPt); Trs++; // we should also output CSV file if (!CsvOut.Empty()) { // make sure no ',' in the strings and dump the triplet SubjectStr.DelChAll(','); CsvOut->PutStr(SubjectStr + ","); PredicatStr.DelChAll(','); CsvOut->PutStr(PredicatStr + ","); ObjectStr.DelChAll(','); CsvOut->PutStr(ObjectStr + ","); // dump the document blob pointer CsvOut->PutStr(TStr::Fmt("%u,", uint(SentBlobPt.GetSeg()))); CsvOut->PutStr(TStr::Fmt("%u,", SentBlobPt.GetAddr())); // dump the adjectives CsvOut->PutStr(TStr::Fmt("%d,", SubjectAttrV.Len())); for (int AttrN = 0; AttrN < SubjectAttrV.Len(); AttrN++) { SubjectAttrV[AttrN].DelChAll(','); CsvOut->PutStr(SubjectAttrV[AttrN]); CsvOut->PutStr(","); } CsvOut->PutStr(TStr::Fmt("%d,", PredicatAttrV.Len())); for (int AttrN = 0; AttrN < PredicatAttrV.Len(); AttrN++) { PredicatAttrV[AttrN].DelChAll(','); CsvOut->PutStr(PredicatAttrV[AttrN]); CsvOut->PutStr(","); } CsvOut->PutStr(TStr::Fmt("%d,", ObjectAttrV.Len())); for (int AttrN = 0; AttrN < ObjectAttrV.Len(); AttrN++) { ObjectAttrV[AttrN].DelChAll(','); CsvOut->PutStr(ObjectAttrV[AttrN]); CsvOut->PutStr(","); } CsvOut->PutStr("-1"); CsvOut->PutLn(); } } } } CsvOut->Flush(); } void TTrGixBs::IndexReuters(const TStr& XmlFPath, const TStr& CsvFNm, const int& MxTrs) { PNotify Notify = TStdNotify::New(); Notify->OnStatus("Loading Reuters documents from " + XmlFPath + " ...\n"); TFFile FFile(XmlFPath, ".xml", true); TStr XmlFNm; int Files = 0, Trs = 0; PSOut CsvOut; if (!CsvFNm.Empty()) { CsvOut = TFOut::New(CsvFNm); } while (FFile.Next(XmlFNm) && ((MxTrs == -11)||(MxTrs > Trs))) { // load document Notify->OnStatus(TStr::Fmt("Loading %3d : %s ...", Files+1, XmlFNm.CStr())); if (TFile::Exists(XmlFNm)) { AddReuters(XmlFNm, Trs, CsvOut); Files++; } } Notify->OnStatus(TStr::Fmt("Triplets loaded: %d", Trs)); } ///////////////////////////////////////////////// // Multilingual-Word-Inverted-Index-Item TMWdGixItem::TMWdGixItem(TSIn& SIn) { SIn.Load(Seg); SIn.Load(Addr); SIn.Load(WdFq); SIn.Load(DocWds); } void TMWdGixItem::Save(TSOut& SOut) const { SOut.Save(Seg); SOut.Save(Addr); SOut.Save(WdFq); SOut.Save(DocWds); } inline bool TMWdGixItem::operator==(const TMWdGixItem& Item) const { return (Seg == Item.Seg) && (Addr == Item.Addr); } inline bool TMWdGixItem::operator<(const TMWdGixItem& Item) const { return (Seg < Item.Seg) || ((Seg == Item.Seg) && (Addr < Item.Addr)); } ///////////////////////////////////////////////// // General-Inverted-Index-Default-Merger void TMWdGixDefMerger::Union(TMWdGixItemV& DstV, const TMWdGixItemV& SrcV) const { TMWdGixItemV DstValV(TInt::GetMx(DstV.Len(), SrcV.Len()), 0); int ValN1 = 0; int ValN2 = 0; while ((ValN1<DstV.Len()) && (ValN2<SrcV.Len())){ const TMWdGixItem& Val1 = DstV.GetVal(ValN1); const TMWdGixItem& Val2 = SrcV.GetVal(ValN2); if (Val1 < Val2) { DstValV.Add(Val1); ValN1++; } else if (Val1>Val2) { DstValV.Add(Val2); ValN2++; } else { DstValV.Add(TMWdGixItem(Val1, Val2)); ValN1++; ValN2++; } } for (int RestValN1=ValN1; RestValN1<DstV.Len(); RestValN1++){ DstValV.Add(DstV.GetVal(RestValN1));} for (int RestValN2=ValN2; RestValN2<SrcV.Len(); RestValN2++){ DstValV.Add(SrcV.GetVal(RestValN2));} DstV = DstValV; } void TMWdGixDefMerger::Def(const TInt& Key, TMWdGixItemV& ItemV) const { const int WdDocFq = MWdGix->GetWdFq(Key); const int Docs = MWdGix->GetAllDocs(); const double AvgDocWds = MWdGix->GetAvgDocWds(); const int Items = ItemV.Len(); for (int ItemN = 0; ItemN < Items; ItemN++) { TMWdGixItem& Item = ItemV[ItemN]; const int WdFq = Item.GetWdFq(); const int DocWds = Item.GetDocWds(); const double Wgt = RankFun->WdRank(WdFq, DocWds, WdDocFq, Docs, AvgDocWds); Item.PutWgt(Wgt); } } ///////////////////////////////////////////////// // Multilingual-Word-Inverted-Index TMWdGix::TMWdGix(const TStr& _FPath, const TFAccess& _FAccess, const int64& CacheSize) { // store policy FPath = _FPath; FAccess = _FAccess; printf("Loading '%s' .. ", FPath.CStr()); if (FAccess == faCreate) { printf("create .. "); } if (FAccess == faRdOnly) { printf("read-only .. "); } printf("Cache[%s]\n", TUInt64::GetMegaStr(CacheSize).CStr()); // prepare gix MWGix = TMWGix::New(TGixConst::MWdGixFNm, FPath, FAccess, CacheSize); // load word tables if (FAccess != faCreate) { // prepare file name TStr MWdGixDatFNm = TStr::GetNrFPath(FPath) + TGixConst::MWdGixDatFNm; // load stuff TFIn FIn(MWdGixDatFNm); WordH.Load(FIn); AllDocs.Load(FIn); AllWords.Load(FIn); } } TMWdGix::~TMWdGix() { if ((FAccess == faCreate) || (FAccess == faUpdate)) { printf("Closing %s: docs=%d, words=%d\n", FPath.CStr(), AllDocs.Val, AllWords.Val); // prepare file name TStr MWdGixDatFNm = TStr::GetNrFPath(FPath) + TGixConst::MWdGixDatFNm; // save word tables TFOut FOut(MWdGixDatFNm); WordH.Save(FOut); AllDocs.Save(FOut); AllWords.Save(FOut); } } void TMWdGix::AddHtml(const TStr& DocStr, const TBlobPt& BlobPt) { // create html lexical PSIn HtmlSIn = TStrIn::New(DocStr); THtmlLx HtmlLx(HtmlSIn); HtmlLx.GetSym(); // prepare word vector, position counter and flags TIntH DocWIdH; int DocWds = 0; // traverse html string symbols while (HtmlLx.Sym != hsyEof) { if (HtmlLx.Sym == hsyStr) { // get word token TStr WordStr = HtmlLx.UcChA; // get the word id const int WId = WordH.AddKey(WordStr); // increas the frequency count DocWIdH.AddDat(WId)++; // increase document word count DocWds++; } // get next symbol HtmlLx.GetSym(); } // load add documents to words in inverted index int WdKeyId = DocWIdH.FFirstKeyId(); while (DocWIdH.FNextKeyId(WdKeyId)) { const int WId = DocWIdH.GetKey(WdKeyId); const int WdFq = DocWIdH[WdKeyId]; WordH[WId]++; // count for document frequency TMWdGixKey Key(WId); TMWdGixItem Item(BlobPt, WdFq, DocWds); // add to index MWGix->AddItem(Key, Item); } // increase counters AllDocs++; AllWords += DocWds; } bool TMWdGix::Search(const TStr& QueryStr, TMWdGixItemV& ResItemV, const TMWdGixDefMerger& Merger) { // first we prepare the query just for current language PMWGixExpItem MWGixExp = TMWGixExpItem::NewEmpty(); PSIn HtmlSIn = TStrIn::New(QueryStr); THtmlLx HtmlLx(HtmlSIn); HtmlLx.GetSym(); while (HtmlLx.Sym != hsyEof) { if (HtmlLx.Sym == hsyStr) { // get word token TStr WordStr = HtmlLx.UcChA; // check if we have it const int WId = WordH.GetKeyId(WordStr); if (WId != -1) { PMWGixExpItem MWGixExpItem = TMWGixExpItem::NewItem(TMWdGixKey(WId)); if (MWGixExp->IsEmpty()) { MWGixExp = MWGixExpItem; } else { MWGixExp = TMWGixExpItem::NewOr(MWGixExp, MWGixExpItem); } } } // get next symbol HtmlLx.GetSym(); } // search return MWGixExp->Eval(MWGix, ResItemV, Merger); } ///////////////////////////////////////////////// // MWdGix-Result-Set TStr TMWdGixRSet::GetMainPara(const TStr& QueryStr, const TStr& FullStr) { PBowDocBs BowDocBs = TBowDocBs::New(); BowDocBs->AddHtmlDoc("Query", TStrV(), QueryStr, false); TStrV ParaV; FullStr.SplitOnAllCh('\n', ParaV); if (ParaV.Empty()) { return ""; } for (int ParaN = 0; ParaN < ParaV.Len(); ParaN++) { BowDocBs->AddHtmlDoc("Doc" + TInt::GetStr(ParaN), TStrV(), ParaV[ParaN], false); } PBowDocWgtBs BowDocWgtBs = TBowDocWgtBs::New(BowDocBs, bwwtNrmTFIDF); PBowSpV QuerySpV = BowDocWgtBs->GetSpV(0); int MxParaN = 0; double MxParaSim = TBowSim::GetCosSim(QuerySpV, BowDocWgtBs->GetSpV(1)); for (int ParaN = 1; ParaN < ParaV.Len(); ParaN++) { const double ParaSim = TBowSim::GetCosSim(QuerySpV, BowDocWgtBs->GetSpV(ParaN+1)); if (ParaSim > MxParaSim) { MxParaSim = ParaSim; MxParaN = ParaN; } } return ParaV[MxParaN]; } void TMWdGixRSet::AddDoc(const TStr& DocTitle, const TStr& DocStr, const TStr& DocLang, const TStrV& KeyWdV) { DocTitleV.Add(DocTitle); DocTitleV.Last().DelChAll('\n'); DocTitleV.Last().DelChAll('\r'); DocStrV.Add(GetMainPara(LangQueryH.GetDat(DocLang), DocStr)); DocLangV.Add(DocLang); KeyWdVV.Add(KeyWdV); } void TMWdGixRSet::PrintRes(PNotify Notify) { const int Docs = GetDocs(); Notify->OnStatus(TStr::Fmt("All results: %d, Showing results from %d to %d", AllDocs.Val, Docs, Docs + Offset.Val)); for (int DocN = 0; DocN < Docs; DocN++) { TStr DocStr = DocTitleV[DocN] + " - " + DocStrV[DocN]; DocStr.DelChAll('\n'); DocStr.DelChAll('\r'); Notify->OnStatus(TStr::Fmt("[%d:%s] %s ...", DocN+1, DocLangV[DocN].CStr(), DocStr.Left(60).CStr())); } Notify->OnStatus(TStr::Fmt("All results: %d, Showing results from %d to %d", AllDocs.Val, Docs, Docs + Offset.Val)); } TStr TMWdGixRSet::GetWsXml(const TStrPrStrH& EurovocH) const { PXmlTok TopTok = TXmlTok::New("cca"); TopTok->AddArg("allhits", GetAllDocs()); for (int DocN = 0; DocN < GetDocs(); DocN++) { PXmlTok HitTok = TXmlTok::New("hit"); HitTok->AddArg("rank", DocN+1); HitTok->AddArg("lang", DocLangV[DocN]); TStr Title = DocTitleV[DocN]; if (Title.Len() > 100) { Title = Title.Left(100) + "..."; } TStr Snipet = DocStrV[DocN].Left(800); if (Snipet.Len() > 800) { Snipet = Snipet.Left(800) + "..."; } HitTok->AddSubTok(TXmlTok::New("title", Title)); HitTok->AddSubTok(TXmlTok::New("snipet", Snipet)); PXmlTok KeyWdTok = TXmlTok::New("keywords"); const TStrV& KeyWdV = KeyWdVV[DocN]; int GoodKeyWds = 0; for (int KeyWdN = 0; KeyWdN < KeyWdV.Len(); KeyWdN++) { TStrPr KeyWd(QueryLang, KeyWdV[KeyWdN]); //printf("'%s' - '%s'\n", KeyWd.Val1.CStr(), KeyWd.Val2.CStr()); if (EurovocH.IsKey(KeyWd)) { KeyWdTok->AddSubTok(TXmlTok::New("keyword", EurovocH.GetDat(KeyWd))); GoodKeyWds++; } } HitTok->AddSubTok(KeyWdTok); if (GoodKeyWds == 0) { continue; } TopTok->AddSubTok(HitTok); } return TopTok->GetTokStr(); } ///////////////////////////////////////////////// // MWdGix-Base TMWdGixBs::TMWdGixBs(const TStr& _FPath, const TFAccess& _FAccess, const int64& _CacheSize) { // store policy FPath = _FPath; FAccess = _FAccess; CacheSize = _CacheSize; // create blob base TStr MWdGixDocBsFNm = TStr::GetNrFPath(FPath) + TGixConst::MWdGixDocBsFNm; DocBBs = TMBlobBs::New(MWdGixDocBsFNm, FAccess); // load AlignPairBs if (FAccess != faCreate) { TStr MWdGixBsFNm = TStr::GetNrFPath(FPath) + TGixConst::MWdGixBsFNm; AlignPairBs = TAlignPairBs::LoadBin(MWdGixBsFNm); InitGixs(FAccess); } } TMWdGixBs::~TMWdGixBs() { if ((FAccess == faCreate) || (FAccess == faUpdate)) { TStr MWdGixBsFNm = TStr::GetNrFPath(FPath) + TGixConst::MWdGixBsFNm; AlignPairBs->SaveBin(MWdGixBsFNm); } } void TMWdGixBs::AddDoc(const TStr& DocTitle, const TStr& DocStr, const TStr& DocLang, const TStrV& KeyWdV) { // save to blob base TMOut DocMOut; DocTitle.Save(DocMOut); DocStr.Save(DocMOut); DocLang.Save(DocMOut); KeyWdV.Save(DocMOut); TBlobPt DocBlobPt = DocBBs->PutBlob(DocMOut.GetSIn()); // add to index LangMWdGixH.GetDat(DocLang)->AddHtml(DocStr, DocBlobPt); } void TMWdGixBs::GetDoc(const TBlobPt& BlobPt, TStr& DocTitle, TStr& DocStr, TStr& DocLang, TStrV& KeyWdV) const { PSIn SIn = DocBBs->GetBlob(BlobPt); DocTitle.Load(*SIn); DocStr.Load(*SIn); DocLang.Load(*SIn); KeyWdV.Load(*SIn); } PMWdGixRSet TMWdGixBs::SearchDoc(const TStr& QueryStr, const TStr& QueryLang, const TStrV& TargetLangV, const int& Docs, const int& Offset, PMWdGixRankFun& RankFun) { // check if language is good if (!AlignPairBs->IsLang(QueryLang)) { return TMWdGixRSet::New(QueryStr, "", TStrStrH(), 0, 0); } // translate queries to target languages const int Queries = TargetLangV.Len(); printf(" Translationg %d queries ...\n", Queries); const int QueryLangId = AlignPairBs->GetLangId(QueryLang); TStrStrH LangQueryH; TWgtMWdGixIntItemKdV FullWgtLangItemV; for (int TargetLangN = 0; TargetLangN < Queries; TargetLangN++) { if (!AlignPairBs->IsLang(TargetLangV[TargetLangN])) { continue; } // first we translate the query const TStr& TargetLang = TargetLangV[TargetLangN]; const int TargetLangId = AlignPairBs->GetLangId(TargetLang); if (TargetLangId == QueryLangId) { continue; } TStr TargetQueryStr = AlignPairBs->MapQuery( AlignPairMap, QueryStr, QueryLangId, TargetLangId); LangQueryH.AddDat(TargetLang, TargetQueryStr); printf(" Query: '%s' -> '%s'\n", QueryStr.CStr(), TargetQueryStr.CStr()); // then we fire it against the inverted index printf(" Loading from Gix ...\n"); TMWdGixItemV LangResItemV; PMWdGix LangMWdGix = LangMWdGixH.GetDat(TargetLang); TMWdGixDefMerger LangMerger(LangMWdGix, RankFun); LangMWdGix->Search(TargetQueryStr, LangResItemV, LangMerger); // get max weight double MxWgt = 0.0; for (int ItemN = 0; ItemN < LangResItemV.Len(); ItemN++) { const TMWdGixItem& Item = LangResItemV[ItemN]; MxWgt = TFlt::GetMx(Item.GetWgt(), MxWgt); } // reweight so max is 1.0 printf(" MxWgt: %g\n", MxWgt); for (int ItemN = 0; ItemN < LangResItemV.Len(); ItemN++) { const TMWdGixItem& Item = LangResItemV[ItemN]; const double Wgt = MxWgt > 0.0 ? Item.GetWgt() / MxWgt : 0.0; TMWdGixIntItemPr LangItemPr(TargetLangId, Item); FullWgtLangItemV.Add(TWgtMWdGixIntItemKd(Wgt, LangItemPr)); } } // sort the results FullWgtLangItemV.Sort(false); // select the correct portion of documents printf(" Sorting %d hits ...\n", FullWgtLangItemV.Len()); TWgtMWdGixIntItemKdV WgtLangItemV; if (Docs == -1) { // return all resuts WgtLangItemV = FullWgtLangItemV; } else if (FullWgtLangItemV.Len() >= (Docs + Offset)) { // get a subset of results from perticular sub-page WgtLangItemV = FullWgtLangItemV; WgtLangItemV.Sort(false); WgtLangItemV.Trunc(Docs + Offset); WgtLangItemV.Sort(true); WgtLangItemV.Trunc(Docs); } else if (FullWgtLangItemV.Len() > Offset) { // last page ... WgtLangItemV = FullWgtLangItemV; WgtLangItemV.Sort(true); WgtLangItemV.Trunc(FullWgtLangItemV.Len() - Offset); } else { // out of range, leave empty } // sort according to the rank WgtLangItemV.Sort(false); // feed them to the result set printf(" Loading content for %d hits ...\n", WgtLangItemV.Len()); PMWdGixRSet RSet = TMWdGixRSet::New(QueryStr, QueryLang, LangQueryH, FullWgtLangItemV.Len(), Offset); for (int ItemN = 0; ItemN < WgtLangItemV.Len(); ItemN++) { const TMWdGixIntItemPr& LangItem = WgtLangItemV[ItemN].Dat; const TMWdGixItem& Item = LangItem.Val2; TBlobPt DocBlobPt = Item.GetBlobPt(); TStr DocTitle, DocStr, DocLang; TStrV KeyWdV; GetDoc(DocBlobPt, DocTitle, DocStr, DocLang, KeyWdV); RSet->AddDoc(DocTitle, DocStr, DocLang, KeyWdV); } printf(" Done\n"); return RSet; } void TMWdGixBs::AddAcquis(const TStr& XmlFNm, const TStr& Lang) { PXmlDoc XmlDoc = TXmlDoc::LoadTxt(XmlFNm); if (!XmlDoc->IsOk()) { return; } PXmlTok TopTok = XmlDoc->GetTok(); // title & body PXmlTok TextTok = TopTok->GetTagTok("text|body"); if (TextTok.Empty()) { printf(" Bad file '%s'\n", XmlFNm.CStr()); return; } TStr DocTitle; TChA DocChA; for (int SubTokN = 0; SubTokN < TextTok->GetSubToks(); SubTokN++) { PXmlTok SubTok = TextTok->GetSubTok(SubTokN); if (!SubTok->IsTag()) { continue; } if (SubTok->GetTagNm() == "head") { DocTitle = SubTok->GetTokStr(false); } else if (SubTok->GetTagNm() == "div") { // iterate over paragraphs for (int ParaN = 0; ParaN < SubTok->GetSubToks(); ParaN++) { if (SubTok->IsTag()) { DocChA += SubTok->GetSubTok(ParaN)->GetTokStr(false); DocChA += '\n'; } } DocChA += '\n'; } } // keywords TStrV KeyWdV; PXmlTok KeyWdTok = TopTok->GetTagTok("teiHeader|profileDesc|textClass"); if (!KeyWdTok.Empty()) { for (int SubTokN = 0; SubTokN < KeyWdTok->GetSubToks(); SubTokN++) { PXmlTok SubTok = KeyWdTok->GetSubTok(SubTokN); if (!SubTok->IsTag()) { continue; } if (SubTok->IsArg("scheme")) { KeyWdV.Add(SubTok->GetStrArgVal("scheme") + "-" + SubTok->GetTokStr(false)); } } } // index if (!KeyWdV.Empty()) { AddDoc(DocTitle, DocChA, Lang, KeyWdV); } } void TMWdGixBs::IndexAcquis(const TStr& InFPath, PAlignPairBs _AlignPairBs, const int& MxDocs, const int64& IndexCacheSize) { AlignPairBs = _AlignPairBs; // iterate over all the lanugages int LangId = AlignPairBs->FFirstLangId(); while (AlignPairBs->FNextLangId(LangId)) { const TStr& Lang = AlignPairBs->GetLang(LangId); TStr LangFPath = InFPath + "/" + Lang; printf("Indexing %s ...\n", LangFPath.CStr()); // prepare index for this language LangMWdGixH.AddDat(Lang) = TMWdGix::New(FPath + "/" + Lang, FAccess, IndexCacheSize); // iterate over all the files for this language and index them TFFile FFile(LangFPath, ".xml", true); TStr XmlFNm; int XmlFNms = 0; while (FFile.Next(XmlFNm)) { if (XmlFNms == MxDocs) { break; } if (XmlFNms % 100 == 0) { printf(" %d\r", XmlFNms); } try { AddAcquis(XmlFNm, Lang); } catch (...) { } XmlFNms++; } printf("\n"); // clear the index to disk LangMWdGixH.Clr(); } // fin :-) InitGixs(faRdOnly); }
69,374
27,434
// -*- C++ -*- // // Package: PhysicsTools/NanoAOD // Class: IsoValueMapProducer // /**\class IsoValueMapProducer IsoValueMapProducer.cc PhysicsTools/NanoAOD/plugins/IsoValueMapProducer.cc Description: [one line class summary] Implementation: [Notes on implementation] */ // // Original Author: Marco Peruzzi // Created: Mon, 04 Sep 2017 22:43:53 GMT // // // system include files #include <memory> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/global/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/StreamID.h" #include "CommonTools/Egamma/interface/EffectiveAreas.h" #include "DataFormats/PatCandidates/interface/Muon.h" #include "DataFormats/PatCandidates/interface/Electron.h" #include "DataFormats/PatCandidates/interface/Photon.h" #include "DataFormats/PatCandidates/interface/IsolatedTrack.h" // // class declaration // template <typename T> class IsoValueMapProducer : public edm::global::EDProducer<> { public: explicit IsoValueMapProducer(const edm::ParameterSet& iConfig) : src_(consumes<edm::View<T>>(iConfig.getParameter<edm::InputTag>("src"))), relative_(iConfig.getParameter<bool>("relative")) { if ((typeid(T) == typeid(pat::Muon)) || (typeid(T) == typeid(pat::Electron)) || typeid(T) == typeid(pat::IsolatedTrack)) { produces<edm::ValueMap<float>>("miniIsoChg"); produces<edm::ValueMap<float>>("miniIsoAll"); ea_miniiso_.reset(new EffectiveAreas((iConfig.getParameter<edm::FileInPath>("EAFile_MiniIso")).fullPath())); rho_miniiso_ = consumes<double>(iConfig.getParameter<edm::InputTag>("rho_MiniIso")); } if ((typeid(T) == typeid(pat::Electron))) { produces<edm::ValueMap<float>>("PFIsoChg"); produces<edm::ValueMap<float>>("PFIsoAll"); produces<edm::ValueMap<float>>("PFIsoAll04"); ea_pfiso_.reset(new EffectiveAreas((iConfig.getParameter<edm::FileInPath>("EAFile_PFIso")).fullPath())); rho_pfiso_ = consumes<double>(iConfig.getParameter<edm::InputTag>("rho_PFIso")); } else if ((typeid(T) == typeid(pat::Photon))) { produces<edm::ValueMap<float>>("PFIsoChg"); produces<edm::ValueMap<float>>("PFIsoAll"); ea_pfiso_chg_.reset(new EffectiveAreas((iConfig.getParameter<edm::FileInPath>("EAFile_PFIso_Chg")).fullPath())); ea_pfiso_neu_.reset(new EffectiveAreas((iConfig.getParameter<edm::FileInPath>("EAFile_PFIso_Neu")).fullPath())); ea_pfiso_pho_.reset(new EffectiveAreas((iConfig.getParameter<edm::FileInPath>("EAFile_PFIso_Pho")).fullPath())); rho_pfiso_ = consumes<double>(iConfig.getParameter<edm::InputTag>("rho_PFIso")); } } ~IsoValueMapProducer() override {} static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: void produce(edm::StreamID, edm::Event&, const edm::EventSetup&) const override; // ----------member data --------------------------- edm::EDGetTokenT<edm::View<T>> src_; bool relative_; edm::EDGetTokenT<double> rho_miniiso_; edm::EDGetTokenT<double> rho_pfiso_; std::unique_ptr<EffectiveAreas> ea_miniiso_; std::unique_ptr<EffectiveAreas> ea_pfiso_; std::unique_ptr<EffectiveAreas> ea_pfiso_chg_; std::unique_ptr<EffectiveAreas> ea_pfiso_neu_; std::unique_ptr<EffectiveAreas> ea_pfiso_pho_; float getEtaForEA(const T*) const; void doMiniIso(edm::Event&) const; void doPFIsoEle(edm::Event&) const; void doPFIsoPho(edm::Event&) const; }; // // constants, enums and typedefs // // // static data member definitions // template <typename T> float IsoValueMapProducer<T>::getEtaForEA(const T* obj) const { return obj->eta(); } template <> float IsoValueMapProducer<pat::Electron>::getEtaForEA(const pat::Electron* el) const { return el->superCluster()->eta(); } template <> float IsoValueMapProducer<pat::Photon>::getEtaForEA(const pat::Photon* ph) const { return ph->superCluster()->eta(); } template <typename T> void IsoValueMapProducer<T>::produce(edm::StreamID streamID, edm::Event& iEvent, const edm::EventSetup& iSetup) const { if ((typeid(T) == typeid(pat::Muon)) || (typeid(T) == typeid(pat::Electron)) || typeid(T) == typeid(pat::IsolatedTrack)) { doMiniIso(iEvent); }; if ((typeid(T) == typeid(pat::Electron))) { doPFIsoEle(iEvent); } if ((typeid(T) == typeid(pat::Photon))) { doPFIsoPho(iEvent); } } template <typename T> void IsoValueMapProducer<T>::doMiniIso(edm::Event& iEvent) const { edm::Handle<edm::View<T>> src; iEvent.getByToken(src_, src); edm::Handle<double> rho; iEvent.getByToken(rho_miniiso_, rho); unsigned int nInput = src->size(); std::vector<float> miniIsoChg, miniIsoAll; miniIsoChg.reserve(nInput); miniIsoAll.reserve(nInput); for (const auto& obj : *src) { auto iso = obj.miniPFIsolation(); auto chg = iso.chargedHadronIso(); auto neu = iso.neutralHadronIso(); auto pho = iso.photonIso(); auto ea = ea_miniiso_->getEffectiveArea(fabs(getEtaForEA(&obj))); float R = 10.0 / std::min(std::max(obj.pt(), 50.0), 200.0); ea *= std::pow(R / 0.3, 2); float scale = relative_ ? 1.0 / obj.pt() : 1; miniIsoChg.push_back(scale * chg); miniIsoAll.push_back(scale * (chg + std::max(0.0, neu + pho - (*rho) * ea))); } std::unique_ptr<edm::ValueMap<float>> miniIsoChgV(new edm::ValueMap<float>()); edm::ValueMap<float>::Filler fillerChg(*miniIsoChgV); fillerChg.insert(src, miniIsoChg.begin(), miniIsoChg.end()); fillerChg.fill(); std::unique_ptr<edm::ValueMap<float>> miniIsoAllV(new edm::ValueMap<float>()); edm::ValueMap<float>::Filler fillerAll(*miniIsoAllV); fillerAll.insert(src, miniIsoAll.begin(), miniIsoAll.end()); fillerAll.fill(); iEvent.put(std::move(miniIsoChgV), "miniIsoChg"); iEvent.put(std::move(miniIsoAllV), "miniIsoAll"); } template <> void IsoValueMapProducer<pat::Photon>::doMiniIso(edm::Event& iEvent) const {} template <typename T> void IsoValueMapProducer<T>::doPFIsoEle(edm::Event& iEvent) const {} template <> void IsoValueMapProducer<pat::Electron>::doPFIsoEle(edm::Event& iEvent) const { edm::Handle<edm::View<pat::Electron>> src; iEvent.getByToken(src_, src); edm::Handle<double> rho; iEvent.getByToken(rho_pfiso_, rho); unsigned int nInput = src->size(); std::vector<float> PFIsoChg, PFIsoAll, PFIsoAll04; PFIsoChg.reserve(nInput); PFIsoAll.reserve(nInput); PFIsoAll04.reserve(nInput); for (const auto& obj : *src) { auto iso = obj.pfIsolationVariables(); auto chg = iso.sumChargedHadronPt; auto neu = iso.sumNeutralHadronEt; auto pho = iso.sumPhotonEt; auto ea = ea_pfiso_->getEffectiveArea(fabs(getEtaForEA(&obj))); float scale = relative_ ? 1.0 / obj.pt() : 1; PFIsoChg.push_back(scale * chg); PFIsoAll.push_back(scale * (chg + std::max(0.0, neu + pho - (*rho) * ea))); PFIsoAll04.push_back(scale * (obj.chargedHadronIso() + std::max(0.0, obj.neutralHadronIso() + obj.photonIso() - (*rho) * ea * 16. / 9.))); } std::unique_ptr<edm::ValueMap<float>> PFIsoChgV(new edm::ValueMap<float>()); edm::ValueMap<float>::Filler fillerChg(*PFIsoChgV); fillerChg.insert(src, PFIsoChg.begin(), PFIsoChg.end()); fillerChg.fill(); std::unique_ptr<edm::ValueMap<float>> PFIsoAllV(new edm::ValueMap<float>()); edm::ValueMap<float>::Filler fillerAll(*PFIsoAllV); fillerAll.insert(src, PFIsoAll.begin(), PFIsoAll.end()); fillerAll.fill(); std::unique_ptr<edm::ValueMap<float>> PFIsoAll04V(new edm::ValueMap<float>()); edm::ValueMap<float>::Filler fillerAll04(*PFIsoAll04V); fillerAll04.insert(src, PFIsoAll04.begin(), PFIsoAll04.end()); fillerAll04.fill(); iEvent.put(std::move(PFIsoChgV), "PFIsoChg"); iEvent.put(std::move(PFIsoAllV), "PFIsoAll"); iEvent.put(std::move(PFIsoAll04V), "PFIsoAll04"); } template <typename T> void IsoValueMapProducer<T>::doPFIsoPho(edm::Event& iEvent) const {} template <> void IsoValueMapProducer<pat::Photon>::doPFIsoPho(edm::Event& iEvent) const { edm::Handle<edm::View<pat::Photon>> src; iEvent.getByToken(src_, src); edm::Handle<double> rho; iEvent.getByToken(rho_pfiso_, rho); unsigned int nInput = src->size(); std::vector<float> PFIsoChg, PFIsoAll; PFIsoChg.reserve(nInput); PFIsoAll.reserve(nInput); for (const auto& obj : *src) { auto chg = obj.chargedHadronIso(); auto neu = obj.neutralHadronIso(); auto pho = obj.photonIso(); auto ea_chg = ea_pfiso_chg_->getEffectiveArea(fabs(getEtaForEA(&obj))); auto ea_neu = ea_pfiso_neu_->getEffectiveArea(fabs(getEtaForEA(&obj))); auto ea_pho = ea_pfiso_pho_->getEffectiveArea(fabs(getEtaForEA(&obj))); float scale = relative_ ? 1.0 / obj.pt() : 1; PFIsoChg.push_back(scale * std::max(0.0, chg - (*rho) * ea_chg)); PFIsoAll.push_back(PFIsoChg.back() + scale * (std::max(0.0, neu - (*rho) * ea_neu) + std::max(0.0, pho - (*rho) * ea_pho))); } std::unique_ptr<edm::ValueMap<float>> PFIsoChgV(new edm::ValueMap<float>()); edm::ValueMap<float>::Filler fillerChg(*PFIsoChgV); fillerChg.insert(src, PFIsoChg.begin(), PFIsoChg.end()); fillerChg.fill(); std::unique_ptr<edm::ValueMap<float>> PFIsoAllV(new edm::ValueMap<float>()); edm::ValueMap<float>::Filler fillerAll(*PFIsoAllV); fillerAll.insert(src, PFIsoAll.begin(), PFIsoAll.end()); fillerAll.fill(); iEvent.put(std::move(PFIsoChgV), "PFIsoChg"); iEvent.put(std::move(PFIsoAllV), "PFIsoAll"); } // ------------ method fills 'descriptions' with the allowed parameters for the module ------------ template <typename T> void IsoValueMapProducer<T>::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; desc.add<edm::InputTag>("src")->setComment("input physics object collection"); desc.add<bool>("relative")->setComment("compute relative isolation instead of absolute one"); if ((typeid(T) == typeid(pat::Muon)) || (typeid(T) == typeid(pat::Electron)) || typeid(T) == typeid(pat::IsolatedTrack)) { desc.add<edm::FileInPath>("EAFile_MiniIso") ->setComment("txt file containing effective areas to be used for mini-isolation pileup subtraction"); desc.add<edm::InputTag>("rho_MiniIso") ->setComment("rho to be used for effective-area based mini-isolation pileup subtraction"); } if ((typeid(T) == typeid(pat::Electron))) { desc.add<edm::FileInPath>("EAFile_PFIso") ->setComment( "txt file containing effective areas to be used for PF-isolation pileup subtraction for electrons"); desc.add<edm::InputTag>("rho_PFIso") ->setComment("rho to be used for effective-area based PF-isolation pileup subtraction for electrons"); } if ((typeid(T) == typeid(pat::Photon))) { desc.add<edm::InputTag>("mapIsoChg")->setComment("input charged PF isolation calculated in VID for photons"); desc.add<edm::InputTag>("mapIsoNeu")->setComment("input neutral PF isolation calculated in VID for photons"); desc.add<edm::InputTag>("mapIsoPho")->setComment("input photon PF isolation calculated in VID for photons"); desc.add<edm::FileInPath>("EAFile_PFIso_Chg") ->setComment( "txt file containing effective areas to be used for charged PF-isolation pileup subtraction for photons"); desc.add<edm::FileInPath>("EAFile_PFIso_Neu") ->setComment( "txt file containing effective areas to be used for neutral PF-isolation pileup subtraction for photons"); desc.add<edm::FileInPath>("EAFile_PFIso_Pho") ->setComment( "txt file containing effective areas to be used for photon PF-isolation pileup subtraction for photons"); desc.add<edm::InputTag>("rho_PFIso") ->setComment("rho to be used for effective-area based PF-isolation pileup subtraction for photons"); } std::string modname; if (typeid(T) == typeid(pat::Muon)) modname += "Muon"; else if (typeid(T) == typeid(pat::Electron)) modname += "Ele"; else if (typeid(T) == typeid(pat::Photon)) modname += "Pho"; else if (typeid(T) == typeid(pat::IsolatedTrack)) modname += "IsoTrack"; modname += "IsoValueMapProducer"; descriptions.add(modname, desc); } typedef IsoValueMapProducer<pat::Muon> MuonIsoValueMapProducer; typedef IsoValueMapProducer<pat::Electron> EleIsoValueMapProducer; typedef IsoValueMapProducer<pat::Photon> PhoIsoValueMapProducer; typedef IsoValueMapProducer<pat::IsolatedTrack> IsoTrackIsoValueMapProducer; //define this as a plug-in DEFINE_FWK_MODULE(MuonIsoValueMapProducer); DEFINE_FWK_MODULE(EleIsoValueMapProducer); DEFINE_FWK_MODULE(PhoIsoValueMapProducer); DEFINE_FWK_MODULE(IsoTrackIsoValueMapProducer);
12,829
5,057
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/pten/core/convert_utils.h" // See Note [ Why still include the fluid headers? ] #include "paddle/fluid/platform/gpu_info.h" namespace pten { // TODO(chenweihang): Add other place trans cases later Backend TransToPtenBackend(const paddle::platform::Place& place) { if (paddle::platform::is_cpu_place(place)) { return Backend::CPU; } else if (paddle::platform::is_gpu_place(place)) { return Backend::CUDA; } else { return Backend::UNDEFINED; } } paddle::experimental::DataType TransToPtenDataType( const paddle::framework::proto::VarType::Type& dtype) { // Set the order of case branches according to the frequency with // the data type is used switch (dtype) { case paddle::framework::proto::VarType::FP32: return DataType::FLOAT32; case paddle::framework::proto::VarType::FP64: return DataType::FLOAT64; case paddle::framework::proto::VarType::INT64: return DataType::INT64; case paddle::framework::proto::VarType::INT32: return DataType::INT32; case paddle::framework::proto::VarType::INT8: return DataType::INT8; case paddle::framework::proto::VarType::UINT8: return DataType::UINT8; case paddle::framework::proto::VarType::INT16: return DataType::INT16; case paddle::framework::proto::VarType::COMPLEX64: return DataType::COMPLEX64; case paddle::framework::proto::VarType::COMPLEX128: return DataType::COMPLEX128; case paddle::framework::proto::VarType::FP16: return DataType::FLOAT16; case paddle::framework::proto::VarType::BF16: return DataType::BFLOAT16; case paddle::framework::proto::VarType::BOOL: return DataType::BOOL; default: return DataType::UNDEFINED; } } DataLayout TransToPtenDataLayout(const paddle::framework::DataLayout& layout) { switch (layout) { case paddle::framework::DataLayout::kNHWC: return DataLayout::NHWC; case paddle::framework::DataLayout::kNCHW: return DataLayout::NCHW; case paddle::framework::DataLayout::kAnyLayout: return DataLayout::ANY; case paddle::framework::DataLayout::kMKLDNN: return DataLayout::MKLDNN; default: return DataLayout::UNDEFINED; } } paddle::platform::Place TransToFluidPlace(const Backend& backend) { // TODO(chenweihang): add other trans cases later switch (backend) { case pten::Backend::CPU: return paddle::platform::CPUPlace(); #if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) case pten::Backend::CUDA: return paddle::platform::CUDAPlace( paddle::platform::GetCurrentDeviceId()); #endif #ifdef PADDLE_WITH_MKLDNN case pten::Backend::MKLDNN: return paddle::platform::CPUPlace(); #endif #if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) case pten::Backend::CUDNN: return paddle::platform::CUDAPlace( paddle::platform::GetCurrentDeviceId()); #endif default: PADDLE_THROW(paddle::platform::errors::Unimplemented( "Unsupported backend `%s` when casting it to paddle place type.", backend)); } } paddle::framework::proto::VarType::Type TransToProtoVarType( const paddle::experimental::DataType& dtype) { // Set the order of case branches according to the frequency with // the data type is used switch (dtype) { case DataType::FLOAT32: return paddle::framework::proto::VarType::FP32; case DataType::FLOAT64: return paddle::framework::proto::VarType::FP64; case DataType::INT64: return paddle::framework::proto::VarType::INT64; case DataType::INT32: return paddle::framework::proto::VarType::INT32; case DataType::INT8: return paddle::framework::proto::VarType::INT8; case DataType::UINT8: return paddle::framework::proto::VarType::UINT8; case DataType::INT16: return paddle::framework::proto::VarType::INT16; case DataType::COMPLEX64: return paddle::framework::proto::VarType::COMPLEX64; case DataType::COMPLEX128: return paddle::framework::proto::VarType::COMPLEX128; case DataType::FLOAT16: return paddle::framework::proto::VarType::FP16; case DataType::BFLOAT16: return paddle::framework::proto::VarType::BF16; case DataType::BOOL: return paddle::framework::proto::VarType::BOOL; default: PADDLE_THROW(paddle::platform::errors::Unimplemented( "Unsupported data type `%s` when casting it into " "paddle data type.", dtype)); } } paddle::framework::DataLayout TransToFluidDataLayout(const DataLayout& layout) { switch (layout) { case DataLayout::NHWC: return paddle::framework::DataLayout::kNHWC; case DataLayout::NCHW: return paddle::framework::DataLayout::kNCHW; case DataLayout::ANY: return paddle::framework::DataLayout::kAnyLayout; case DataLayout::MKLDNN: return paddle::framework::DataLayout::kMKLDNN; default: PADDLE_THROW(paddle::platform::errors::Unimplemented( "Unsupported data layout `%s` when casting it into " "paddle data layout.", layout)); } } paddle::framework::LoD TransToFluidLoD(const pten::LoD& lod) { paddle::framework::LoD out; out.reserve(lod.size()); for (auto& elem : lod) { out.emplace_back(elem); } return out; } pten::LoD TransToPtenLoD(const paddle::framework::LoD& lod) { pten::LoD out; out.reserve(lod.size()); for (auto& elem : lod) { out.emplace_back(elem); } return out; } } // namespace pten
6,127
2,054
#include <alloy.hpp> #include "test.hpp" template<auto X, auto Y, auto Z> struct matrix { constexpr matrix() { auto f = [](auto&& sink) { return values<X, Y, Z>()(FWD(sink)); }; static_assert(qualify<X>(alloy::source{callable<X>(f)}) >> expect(values<X, Y, Z>())); } }; int main() { return test<matrix>; }
358
132
// <Snippet1> using namespace System; using namespace System::Runtime::InteropServices; public ref class LibWrap { public: // CallingConvention.Cdecl must be used since the stack is // cleaned up by the caller. // int printf( const char *format [, argument]... ) [DllImport("msvcrt.dll",CharSet=CharSet::Unicode, CallingConvention=CallingConvention::Cdecl)] static int printf( String^ format, int i, double d ); [DllImport("msvcrt.dll",CharSet=CharSet::Unicode, CallingConvention=CallingConvention::Cdecl)] static int printf( String^ format, int i, String^ s ); }; int main() { LibWrap::printf( "\nPrint params: %i %f", 99, 99.99 ); LibWrap::printf( "\nPrint params: %i %s", 99, "abcd" ); } // </Snippet1>
740
265
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_BOOLEAN_HPP #define MAPNIK_BOOLEAN_HPP // mapnik #include <mapnik/config.hpp> #include <mapnik/util/conversions.hpp> // std #include <iosfwd> #include <string> namespace mapnik { class MAPNIK_DECL boolean_type { public: boolean_type() : b_(false) {} boolean_type(bool b) : b_(b) {} boolean_type(boolean_type const& b) : b_(b.b_) {} operator bool() const { return b_; } boolean_type & operator =(boolean_type const& other) { if (this == &other) return *this; b_ = other.b_; return *this; } private: bool b_; }; // Special stream input operator for boolean_type values template <typename charT, typename traits> std::basic_istream<charT, traits> & operator >> ( std::basic_istream<charT, traits> & s, boolean_type & b ) { if ( s ) { std::string word; s >> word; bool result; if (util::string2bool(word,result)) b = result; } return s; } template <typename charT, typename traits> std::basic_ostream<charT, traits> & operator << ( std::basic_ostream<charT, traits> & s, boolean_type const& b ) { s << ( b ? "true" : "false" ); return s; } } #endif // MAPNIK_BOOLEAN_HPP
2,256
733
#include<iostream> using namespace std; int main(){ float add(float x,float y);//声明add函数 float a,b,c; cout<<"Please enter a&b:";//输出语句 cin>>a>>b; //输入语句 c=add(a,b); //调用add函数 cout<<"sum="<<c<<endl; //输出语句 return 0; } float add(float x,float y){ //定义add函数 float z; z=x+y; return(z); }
326
159
#include <cmath> #include <cstdio> #include "elevator_door_status.h" using std::vector; ElevatorDoorStatus::ElevatorDoorStatus() { } ElevatorDoorStatus::~ElevatorDoorStatus() { } void ElevatorDoorStatus::set_reference(vector<float> scan) { ref = scan; } ElevatorDoorStatus::DoorState ElevatorDoorStatus::detect(vector<float> scan) { static int scan_count = 0; scan_count++; if (!ref.size() || ref.size() != scan.size()) return INVALID_DATA; vector<float> diff = ref; // find sum of differences on the right and left sides of the scan float left_sum = 0, left_idx_sum = 0; float right_sum = 0, right_idx_sum = 0; for (size_t i = 0; i < scan.size(); i++) { diff[i] -= scan[i]; if (diff[i] > 0) continue; // we're only looking for holes, not filled space if (i < scan.size() / 2) { left_sum += diff[i]; left_idx_sum++; } else { right_sum += diff[i]; right_idx_sum++; } } //if (left_sum < -3 || right_sum < -3) // depends on how far away you are // printf("%.05f %.05f\n", left_sum, right_sum); if (left_sum < -3) return LEFT_OPEN; else if (right_sum < -3) return RIGHT_OPEN; else return ALL_CLOSED; }
1,215
482
#include "UNITARY_MAT.h" #include "TREE.h" #include "STRINGY.h" #include "OPTIMIZATIONS.h" #include "PERMUTATION.h" #include "CENTRAL_MAT.h" #include "W_SPEC.h" //This global is a string that denotes the //matrix being decomposed. The global will //be used as a prefix in file names. STRINGY g_mat_name; VOID pmut_opt1_grow_one_tree( UNITARY_MAT * u_p, W_SPEC & w_spec, BOOLEAN keep_identity_pmut, const PERMUTATION & desired_pmut); VOID pmut_opt1_grow_many_trees( UNITARY_MAT * u_p, W_SPEC & w_spec, BOOLEAN keep_identity_pmut, const PERMUTATION & desired_pmut); //****************************************** //VOID main(VOID) int main(VOID) { SetDebugThrow_(debugAction_Alert); SetDebugSignal_(debugAction_Alert); //params = parameters //comp = components //engl = english //pict = picture //i(o)strm = in(out) stream //opt = optimization //pmut = permutation IFSTREAM param_strm; USHORT do_compilation, do_decompilation; USHORT do_light_right_opt; USHORT do_complex_d_mat_opt; USHORT pmut_opt_level; USHORT do_all_bit_pmuts, keep_identity_pmut; PERMUTATION desired_pmut; USHORT pmut_len, i; param_strm.open("qbtr-params.in"); if(!param_strm.is_open()) { cerr<<"'qbtr-params.in' file is missing."; exit(-1); } param_strm.exceptions(ios::badbit | ios::failbit); try{ param_strm.ignore(500, k_endline); param_strm>>g_mat_name; param_strm.ignore(500, k_endline); param_strm.ignore(500, k_endline); param_strm>>do_compilation; param_strm.ignore(500, k_endline); param_strm.ignore(500, k_endline); param_strm>>do_decompilation; param_strm.ignore(500, k_endline); param_strm.ignore(500, k_endline); param_strm>>do_light_right_opt; param_strm.ignore(500, k_endline); param_strm.ignore(500, k_endline); param_strm>>do_complex_d_mat_opt; param_strm.ignore(500, k_endline); param_strm.ignore(500, k_endline); param_strm>>pmut_opt_level; param_strm.ignore(500, k_endline); param_strm.ignore(500, k_endline); if(pmut_opt_level==1){ param_strm>>do_all_bit_pmuts; param_strm.ignore(500, k_endline); }else{ param_strm.ignore(500, k_endline); } param_strm.ignore(500, k_endline); if(pmut_opt_level==1){ param_strm>>keep_identity_pmut; param_strm.ignore(500, k_endline); }else{ param_strm.ignore(500, k_endline); } param_strm.ignore(500, k_endline); param_strm.ignore(500, k_endline); if(pmut_opt_level==1 && !keep_identity_pmut){ param_strm>>pmut_len; desired_pmut.resize(0, pmut_len); for(i=0; i<pmut_len; i++){ param_strm>>desired_pmut[i]; } param_strm.ignore(500, k_endline); }else{ param_strm.ignore(500, k_endline); param_strm.ignore(500, k_endline); } } catch(const ios::failure & io_exc){ cerr<<"'qbtr-params.in' file is illegal."; exit(-1); } param_strm.close(); OPTIMIZATIONS::its_lighten_right_mats = do_light_right_opt; OPTIMIZATIONS::its_extract_d_mat_phases = do_complex_d_mat_opt; OPTIMIZATIONS::its_pmut_opt_level = pmut_opt_level; //pmut_opt_level>1 not yet implemented ThrowIf_(pmut_opt_level>1); if(do_compilation){ IFSTREAM comp_strm; comp_strm.open((g_mat_name && ".in").get_string()); if( !comp_strm.is_open() ) { cerr<<"'mat_name.in' file is missing."; exit(-1); } UNITARY_MAT * u_p = new UNITARY_MAT(); //u_p is destroyed by TREE()->NODE() //if choose destroy option in TREE(). u_p->read_components_file(&comp_strm); comp_strm.close(); if(u_p->get_num_of_bits()==0){ OPTIMIZATIONS::its_pmut_opt_level = pmut_opt_level = 0; } if(pmut_opt_level==1){ if(!keep_identity_pmut){ ThrowIf_(u_p->get_num_of_bits()!=pmut_len); }else{ pmut_len = u_p->get_num_of_bits(); desired_pmut.set_to_identity(pmut_len); } } OFSTREAM engl_strm; OFSTREAM pict_strm; W_SPEC w_spec; engl_strm.open((g_mat_name && "-engl.out").get_string()); pict_strm.open((g_mat_name && "-pict.out").get_string()); engl_strm<<fixed<<showpoint<<setprecision(9); w_spec.its_engl_strm_p = &engl_strm; w_spec.its_pict_strm_p = &pict_strm; if(pmut_opt_level!=1){ TREE tree(u_p, true);//destroys u_p w_spec.its_pmut_p = 0; tree.write(w_spec); }else{//pmut_opt_level==1 if(!do_all_bit_pmuts){ //destroys u_p pmut_opt1_grow_one_tree(u_p, w_spec, keep_identity_pmut, desired_pmut); }else{//do all bit permutations //destroys u_p pmut_opt1_grow_many_trees(u_p, w_spec, keep_identity_pmut, desired_pmut); } }//pmut_opt_level engl_strm.close(); pict_strm.close(); }//do compilation if(do_decompilation){ UNITARY_MAT v; IFSTREAM engl_strm; engl_strm.open((g_mat_name && "-engl.out").get_string()); if(!engl_strm.is_open()) { cerr<<"'mat_name-engl.out' file is missing."; exit(-1); } v.read_english_file(&engl_strm); engl_strm.close(); OFSTREAM comp_strm; comp_strm.open((g_mat_name && "-chk.out").get_string());//chk = check comp_strm<<fixed<<showpoint; v.write_components_file(&comp_strm); comp_strm.close(); if(do_compilation){ IFSTREAM decr_strm;//decr = decrement decr_strm.open((g_mat_name && ".in").get_string()); if( !decr_strm.is_open() ) { cerr<<"'mat_name.in' file is missing."; exit(-1); } v.read_decrements_file(&decr_strm); decr_strm.close(); OFSTREAM err_strm;//err = error err_strm.open((g_mat_name && "-err.out").get_string()); err_strm<<fixed<<showpoint; v.write_components_file(&err_strm); err_strm.close(); } } } //****************************************** VOID pmut_opt1_grow_one_tree( UNITARY_MAT * u_p, //io W_SPEC & w_spec, //io BOOLEAN keep_identity_pmut, //in const PERMUTATION & desired_pmut) //in { if(!keep_identity_pmut){ u_p->permute_bits(desired_pmut); } TREE tree(u_p, true); PERMUTATION inv_pmut(desired_pmut.get_len()); if(!keep_identity_pmut){ desired_pmut.get_inverse(inv_pmut); w_spec.its_pmut_p = &inv_pmut; }else{ w_spec.its_pmut_p = 0; } tree.write(w_spec); } //****************************************** VOID pmut_opt1_grow_many_trees( UNITARY_MAT * u_p, //io W_SPEC & w_spec, //io BOOLEAN keep_identity_pmut, //in const PERMUTATION & desired_pmut) //in { //save the ostream pointers OFSTREAM * engl_strm_p = w_spec.its_engl_strm_p; OFSTREAM * pict_strm_p = w_spec.its_pict_strm_p; OFSTREAM pmut_strm;//permutation log pmut_strm.open((g_mat_name && "-pmut.out").get_string()); TRANSPOSITION transp;//identity by default USHORT p_counter=1; BOOLEAN more_pmuts; USHORT pmut_len = desired_pmut.get_len(); PERMUTATION pmut(pmut_len); PERMUTATION inv_pmut(pmut_len); pmut.prepare_for_lazy_advance(); do{ more_pmuts = pmut.lazy_advance(transp); u_p->transpose_bits(transp); TREE tree(u_p, false);//destroy u_p at the end of this method //In write: //If engl_strm_p = 0, then no actual //writing is done in english file. //Same for pict_strm_p. //If pmut_p = 0, no permutation is done when writing english file. if(pmut!=desired_pmut){ w_spec.its_engl_strm_p = 0; w_spec.its_pict_strm_p = 0; w_spec.its_pmut_p = 0; }else{ w_spec.its_engl_strm_p = engl_strm_p; w_spec.its_pict_strm_p = pict_strm_p; if(!keep_identity_pmut){ desired_pmut.get_inverse(inv_pmut); w_spec.its_pmut_p = &inv_pmut; }else{ w_spec.its_pmut_p = 0; } } CENTRAL_MAT::set_cum_num_of_elem_ops(0); tree.write(w_spec); pmut_strm<< '(' << p_counter << ')'; for(USHORT i=0; i<pmut_len; i++){ pmut_strm<<'\t'<<pmut[i]; } pmut_strm<< k_endline <<'\t'<<"number of steps = "; pmut_strm<<CENTRAL_MAT::get_cum_num_of_elem_ops()<<k_endline; p_counter++; }while(more_pmuts); delete u_p; pmut_strm.close(); }
7,821
3,966
// // Created by Vetle Wegner Ingeberg on 30/04/2021. // #include "meshreader/incbin.h" #ifndef SRC_PATH #define SRC_PATH "../" #endif // SRC_PATH #ifndef PLY_PATH #define PLY_PATH SRC_PATH"Mesh-Models" #endif // PLY_PATH #ifndef DETECTOR_PATH #define DETECTOR_PATH PLY_PATH"/DETECTORS" #endif // DETECTOR_PATH #ifndef CLOVER_PATH #define CLOVER_PATH DETECTOR_PATH"/CLOVER" #endif // CLOVER_PATH // Including all the CLOVER HPGe mesh models INCBIN(CLOVER_VACCUM, CLOVER_PATH"/CLOVER-InternalVacuum/CloverInternalVacuum_approx.ply"); INCBIN(CLOVER_ENCASEMENT, CLOVER_PATH"/CloverEncasement/CloverEncasement_new_approx.ply"); INCBIN(HPGeCrystalA, CLOVER_PATH"/HPGeCrystals/HPGe-RoundedCrystal1_10umTolerance.ply"); INCBIN(HPGeCrystalB, CLOVER_PATH"/HPGeCrystals/HPGe-RoundedCrystal2_10umTolerance.ply"); INCBIN(HPGeCrystalC, CLOVER_PATH"/HPGeCrystals/HPGe-RoundedCrystal3_10umTolerance.ply"); INCBIN(HPGeCrystalD, CLOVER_PATH"/HPGeCrystals/HPGe-RoundedCrystal4_10umTolerance.ply"); INCBIN(HPGeContactA, CLOVER_PATH"/HPGeCrystals/HPGe_pureCylindricalBorehole_LithiumContact1_10um.ply"); INCBIN(HPGeContactB, CLOVER_PATH"/HPGeCrystals/HPGe_pureCylindricalBorehole_LithiumContact2_10um.ply"); INCBIN(HPGeContactC, CLOVER_PATH"/HPGeCrystals/HPGe_pureCylindricalBorehole_LithiumContact3_10um.ply"); INCBIN(HPGeContactD, CLOVER_PATH"/HPGeCrystals/HPGe_pureCylindricalBorehole_LithiumContact4_10um.ply");
1,403
656
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> edge; typedef pair<int, int> item; // https://cp-algorithms.com/graph/dijkstra_sparse.html // O(E*log(V)) time and O(E) memory tuple<vector<int>, vector<int>> dijkstra_heap(const vector<vector<edge>> &g, int s) { size_t n = g.size(); vector<int> prio(n, numeric_limits<int>::max()); vector<int> pred(n, -1); priority_queue<item, vector<item>, greater<>> q; q.emplace(prio[s] = 0, s); while (!q.empty()) { auto [d, u] = q.top(); q.pop(); if (d != prio[u]) continue; for (auto [v, len] : g[u]) { int nprio = prio[u] + len; if (prio[v] > nprio) { prio[v] = nprio; pred[v] = u; q.emplace(nprio, v); } } } return {prio, pred}; } // O(E*log(V)) time and O(V) memory tuple<vector<int>, vector<int>> dijkstra_set(const vector<vector<edge>> &g, int s) { size_t n = g.size(); vector<int> prio(n, numeric_limits<int>::max()); vector<int> pred(n, -1); set<item> q; q.emplace(prio[s] = 0, s); while (!q.empty()) { int u = q.begin()->second; q.erase(q.begin()); for (auto [v, len] : g[u]) { int nprio = prio[u] + len; if (prio[v] > nprio) { q.erase({prio[v], v}); prio[v] = nprio; pred[v] = u; q.emplace(prio[v], v); } } } return {prio, pred}; } int main() { vector<vector<edge>> g(3); g[0].emplace_back(1, 10); g[1].emplace_back(2, -5); g[0].emplace_back(2, 8); auto [prio1, pred1] = dijkstra_heap(g, 0); auto [prio2, pred2] = dijkstra_set(g, 0); for (int x : prio1) cout << x << " "; cout << endl; for (int x : prio2) cout << x << " "; cout << endl; }
1,913
770
#include "helpers.h" #include "catch.hpp" #include <lsl_cpp.h> #include <iostream> namespace { TEST_CASE("simple timesync", "[timesync][basic]") { auto sp = create_streampair(lsl::stream_info("timesync", "Test")); double offset = sp.in_.time_correction(5.) * 1000; CHECK(offset < 1); CAPTURE(offset); double remote_time, uncertainty; offset = sp.in_.time_correction(&remote_time, &uncertainty, 5.) * 1000; CHECK(offset < 1); CHECK(uncertainty * 1000 < 1); CHECK(remote_time < lsl::local_clock()); } } // namespace
527
218
#include "specialguildquestion.hpp" #include "scene/activityshadow/activityshadow.hpp" #include "obj/character/role.h" #include "obj/otherobj/gatherobj.h" #include "servercommon/activitydef.hpp" #include "config/logicconfigmanager.hpp" #include "servercommon/string/gameworldstr.h" #include "scene/scenemanager.h" #include "other/event/eventhandler.hpp" #include "global/guild/guild.hpp" #include "global/guild/guildmanager.hpp" #include "protocal/msgchatmsg.h" #include "config/activityconfig/guildquestionconfig.hpp" SpecialGuildQuestion::SpecialGuildQuestion(Scene *scene) : SpecialLogic(scene), m_is_init(false), m_is_open(true), m_is_first(false) { } SpecialGuildQuestion::~SpecialGuildQuestion() { } void SpecialGuildQuestion::Update(unsigned long interval, time_t now_second) { SpecialLogic::Update(interval, now_second); if (!m_is_open) { this->DelayKickOutAllRole(); } } void SpecialGuildQuestion::OnRoleEnterScene(Role *role) { if (NULL == role || !m_is_open) { return; } if (!m_is_first && ActivityShadow::Instance().IsActivtyOpen(ACTIVITY_TYPE_GUILD_QUESTION)) { m_is_first = true; this->RefreshGatherItem(); } ActivityShadow::Instance().OnJoinGuildQuestionActivity(role); } void SpecialGuildQuestion::OnRoleLeaveScene(Role *role, bool is_logout) { } void SpecialGuildQuestion::NotifySystemMsg(char *str_buff, int str_len) { } void SpecialGuildQuestion::OnActivityStart() { if (!m_is_first) { m_is_first = true; this->RefreshGatherItem(); } } void SpecialGuildQuestion::OnActivityClose() { m_is_open = false; } void SpecialGuildQuestion::RefreshGatherItem() { const GuildQuestionOtherConfig &other_cfg = LOGIC_CONFIG->GetGuildQuestionConfig().GetOtherCfg(); int pos_count = LOGIC_CONFIG->GetGuildQuestionConfig().GetGatherPosCount(); for (int i = 0; i < pos_count; i ++) { Posi gather_pos(0, 0); if (!LOGIC_CONFIG->GetGuildQuestionConfig().GetGatherPos(i, &gather_pos)) { continue; } if (m_scene->GetMap()->Validate(Obj::OBJ_TYPE_ROLE, gather_pos.x, gather_pos.y)) { GatherObj *gather_obj = new GatherObj(); gather_obj->SetPos(gather_pos); gather_obj->Init(NULL, other_cfg.gather_id, other_cfg.gather_time_s * 1000, 0, false); m_scene->AddObj(gather_obj); } } } bool SpecialGuildQuestion::SpecialCanGather(Role *role, GatherObj *gather) { if (NULL == role || NULL == gather) { return false; } if (gather->GatherId() != LOGIC_CONFIG->GetGuildQuestionConfig().GetOtherCfg().gather_id) { return false; } if (!ActivityShadow::Instance().IsCanGatherGuildQuestion(role)) { return false; } return true; }
2,613
1,013
#include <CGAL/Exact_predicates_exact_constructions_kernel.h> //#include <CGAL/Exact_predicates_exact_constructions_kernel_with_sqrt.h> #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Projection_traits_xy_3.h> #include <CGAL/Delaunay_triangulation_2.h> #include <CGAL/Triangulation_vertex_base_with_info_2.h> #include <CGAL/Triangulation_face_base_with_info_2.h> #include <CGAL/Triangulation_vertex_base_with_id_2.h> #include <CGAL/Min_circle_2.h> #include <CGAL/Min_circle_2_traits_2.h> #include <CGAL/basic.h> #include <CGAL/QP_models.h> #include <CGAL/QP_functions.h> #include <CGAL/Gmpz.h> #include "UnionFind.h" #include <boost/graph/adjacency_list.hpp> #include <boost/graph/bipartite.hpp> #include <boost/graph/connected_components.hpp> #include <boost/graph/kruskal_min_spanning_tree.hpp> #include <iostream> #include <cassert> #include <vector> #include <queue> #include <stack> #include <cmath> #include <valarray> // LP/QP typedef CGAL::Gmpq ET; // program and solution types typedef CGAL::Quadratic_program<ET> Program; typedef CGAL::Quadratic_program_solution<ET> Solution; // General CGAL typedef CGAL::Exact_predicates_exact_constructions_kernel EK; //typedef CGAL::Exact_predicates_exact_constructions_kernel_with_sqrt KR; typedef CGAL::Exact_predicates_inexact_constructions_kernel IK; //typedef CGAL::Min_circle_2_traits_2<KR> Traits; //typedef CGAL::Min_circle_2<Traits> Min_circle; // Change when use different kernels! typedef long long lint; typedef IK::Point_2 Pt; typedef IK::Point_3 Pt3; typedef IK::Ray_2 Ray; typedef IK::Vector_2 Vec; typedef IK::Segment_2 Seg; // Triangulation typedef int ind_t; // not a good one... //typedef CGAL::Triangulation_vertex_base_with_info_2<ind_t, IK> Vb; //typedef CGAL::Triangulation_data_structure_2<Vb> Tds; //typedef CGAL::Delaunay_triangulation_2<IK> Delaunay; //typedef Delaunay::Finite_faces_iterator Face_iterator; //typedef Delaunay::Finite_edges_iterator Edge_iterator; //typedef Delaunay::Vertex_handle Vertex_handle; //typedef Delaunay::Point DPt; // Boost typedef boost::adjacency_list < boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property < boost::edge_weight_t, lint > > Graph; typedef boost::property_map < Graph, boost::edge_weight_t >::type WeightMap; typedef boost::graph_traits < Graph >::edge_descriptor Edge; typedef boost::graph_traits < Graph >::edge_iterator EdgeIt; typedef boost::graph_traits < Graph >::out_edge_iterator OutEdgeIt; typedef boost::graph_traits < Graph >::vertex_descriptor Vertex; //typedef std::pair<int, int> E; #define _o std::cout #define _l std::endl #define _i std::cin #define _e std::cerr double floor_to_double(const CGAL::Quotient<ET>& x) { double a = std::floor(CGAL::to_double(x)); while (a > x) a -= 1; while (a + 1 <= x) a += 1; return a; } double ceil_to_double(const CGAL::Quotient<ET>& x) { double a = std::ceil(CGAL::to_double(x)); while (a < x) a += 1; while (a - 1 >= x) a -= 1; return a; } struct MyRay { Ray r; int idx; MyRay(Ray r=Ray(), int i=0):r(r),idx(i){} MyRay(Pt src, Pt next, int i) { r = Ray(src, next); idx = i; } }; bool CompareRayByY0(const MyRay& r1, const MyRay& r2) { return r1.r.source().y() > r2.r.source().y(); } int whoWins(const std::vector<MyRay>& rays, int oldone, int newone) { Vec vo = rays[oldone].r.to_vector(); Vec vn = rays[newone].r.to_vector(); if (vo.y() >= 0 && vn.y() >= 0) { return oldone; } if (vo.y() < 0 && vn.y() < 0) { return newone; } if (vo.y() >= 0 && vn.y() < 0) { return (vo.y() * vn.x() + vo.x() * vn.y() > 0) ? newone : oldone; } if (vo.y() < 0 && vn.y() >= 0) { return (vo.y() * vn.x() + vo.x() * vn.y() > 0) ? oldone : newone; } return -1; } int rayChallenge(Ray& rold, Ray& rnew) { // rold.y0 > rnew.y0 // return 0 if old one wins // return 1 if new one wins Vec vo = rold.to_vector(); Vec vn = rnew.to_vector(); if (vo.y() >= 0 && vn.y() >= 0) { return 0; } if (vo.y() < 0 && vn.y() < 0) { return 1; } if (vo.y() >= 0 && vn.y() < 0) { Seg so(rold.source(), rold.source() + vo); Seg sn(rnew.source(), Pt(rnew.source().x() + vn.x(), rnew.source().y() - vn.y())); CGAL::Comparison_result cr = CGAL::compare_slopes(so, sn); //_e << " _" << cr << "_ "; return (cr == CGAL::LARGER ? 1 : 0); //return (vo.y() * vn.x() + vo.x() * vn.y() > 0) ? 1 : 0; } if (vo.y() < 0 && vn.y() >= 0) { Seg so(rold.source(), Pt(rold.source().x() + vo.x(), rold.source().y() - vo.y())); Seg sn(rnew.source(), rnew.source() + vn); CGAL::Comparison_result cr = CGAL::compare_slopes(sn, so); //_e << " _" << cr << "_ "; return (cr == CGAL::LARGER ? 0 : 1); } return 0; } void Motorcycles() { int n; _i >> n; _e << n << _l; std::vector<MyRay> rays(n); for (int i = 0; i < n; i++) { lint y0, x1, y1; _i >> y0 >> x1 >> y1; rays[i] = MyRay(Pt(0, y0), Pt(x1, y1), i); } std::sort(rays.begin(), rays.end(), CompareRayByY0); std::stack<MyRay> st_rays; st_rays.push(rays[0]); for (int i = 1; i < n; i++) { MyRay ray = rays[i]; while (!st_rays.empty()) { MyRay topray = st_rays.top(); if (!CGAL::do_intersect(ray.r, topray.r)) { st_rays.push(ray); //_e << ray.idx << " in stack\n"; break; } else { //_e << topray.idx << ":" << topray.r.to_vector() << "---" << ray.idx << ":" << ray.r.to_vector(); int who = rayChallenge(topray.r, ray.r); //_e << " \twinner:" << ((who==0)?topray.idx:ray.idx) << _l; if (who == 0) break; else { //_e << topray.idx << " out of stack\n"; st_rays.pop(); } } } if (st_rays.empty()) { st_rays.push(ray); //_e << ray.idx << " in empty stack\n"; } } //_e << _l; std::vector<int> alives; while (!st_rays.empty()) { alives.push_back(st_rays.top().idx); st_rays.pop(); } std::sort(alives.begin(), alives.end()); std::vector<int>::iterator ait = alives.begin(); for (; ait != alives.end(); ++ait) { _o << *ait << " "; } _o << _l; return; } void testUnionFind(); int main(int argc, char** argv) { std::ios_base::sync_with_stdio(false); if (argc > 1) { std::string str("C:\\M.K.S.H\\ETH\\AlgoLab\\week6\\potw\\motorcycles\\"); str += std::string(argv[1]) + ".in"; freopen(str.c_str(), "r", stdin); } else freopen("C:\\M.K.S.H\\ETH\\AlgoLab\\week6\\potw\\motorcycles\\test1.in", "r", stdin); freopen("C:\\M.K.S.H\\ETH\\AlgoLab\\week6\\potw\\motorcycles\\out_my.out", "w", stdout); freopen("C:\\M.K.S.H\\ETH\\AlgoLab\\week6\\potw\\motorcycles\\err_my.out", "w", stderr); int t; _i >> t; while (t--) { Motorcycles(); } return 0; } void testUnionFind() { UnionFind uf(9); uf.unionSets(1, 3); uf.unionSets(1, 9); uf.unionSets(5, 6); uf.unionSets(8, 9); uf.unionSets(7, 8); uf.unionSets(5, 8); _e << uf.toString() << _l; return; } // Week 8: Germs / 100 pts // Nearest neighbor void Germs(int n) { typedef CGAL::Triangulation_vertex_base_with_info_2<int, IK> Vb; typedef CGAL::Triangulation_data_structure_2<Vb> Tds; typedef CGAL::Delaunay_triangulation_2<IK, Tds> Delaunay; typedef Delaunay::Finite_faces_iterator Face_iterator; typedef Delaunay::Finite_edges_iterator Edge_iterator; typedef Delaunay::Finite_vertices_iterator Vertex_iterator; typedef Delaunay::Vertex_handle Vertex_handle; typedef Delaunay::Point DPt; typedef Delaunay::Vertex_circulator Vertex_circulator; int l, b, r, t; _i >> l >> b >> r >> t; std::vector< std::pair<Pt, int> > pts(n); std::vector<lint> mind2(n); for (int i = 0; i < n; i++) { int x, y; _i >> x >> y; lint dl = std::abs(x - l); lint dr = std::abs(x - r); lint db = std::abs(y - b); lint dt = std::abs(y - t); lint md = std::min(std::min(dl, dr), std::min(db, dt)); mind2[i] = md*md * 4; pts[i] = std::make_pair(Pt(x, y), i); } lint fd2, md2, ld2; if (n > 1) { Delaunay D; D.insert(pts.begin(), pts.end()); Vertex_iterator vit = D.finite_vertices_begin(), vend = D.finite_vertices_end(); for (; vit != vend; ++vit) { int uind = vit->info(); Pt up = vit->point(); lint md2 = mind2[uind]; Vertex_circulator vc(D.incident_vertices(vit)), done(vc); do { if (D.is_infinite(vc)) continue; Pt vp = vc->point(); lint d2 = CGAL::squared_distance(vp, up); md2 = std::min(d2, md2); } while (++vc != done); mind2[uind] = md2; } std::sort(mind2.begin(), mind2.end()); } fd2 = mind2[0], md2 = mind2[n / 2], ld2 = mind2[n - 1]; double tf = std::sqrt((std::sqrt(fd2) - 1) / 2); double tm = std::sqrt((std::sqrt(md2) - 1) / 2); double tl = std::sqrt((std::sqrt(ld2) - 1) / 2); int tfi = std::ceil(tf); int tmi = std::ceil(tm); int tli = std::ceil(tl); _o << tfi << " " << tmi << " " << tli << _l; return; } // Week 8: H1N1 / incorrect 100pts? // Find the maximum width of the path from outside to the vertex void H1N1(int n) { // Boost typedef boost::adjacency_list < boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property < boost::edge_weight_t, long > > Graph; typedef boost::property_map < Graph, boost::edge_weight_t >::type WeightMap; typedef boost::graph_traits < Graph >::edge_descriptor Edge; typedef boost::graph_traits < Graph >::edge_iterator EdgeIt; typedef boost::graph_traits < Graph >::out_edge_iterator OutEdgeIt; typedef boost::graph_traits < Graph >::vertex_descriptor Vertex; // CGAL typedef CGAL::Triangulation_vertex_base_2<IK> Vb; typedef CGAL::Triangulation_face_base_with_info_2<int, IK> Fb; typedef CGAL::Triangulation_data_structure_2<Vb, Fb> Tds; typedef CGAL::Delaunay_triangulation_2<IK, Tds> Delaunay; typedef Delaunay::Finite_faces_iterator Face_iterator; typedef Delaunay::Face_handle Face_handle; typedef Delaunay::Finite_edges_iterator Edge_iterator; typedef Delaunay::Edge_circulator Edge_circulator; typedef Delaunay::Finite_vertices_iterator Vertex_iterator; typedef Delaunay::Vertex_handle Vertex_handle; typedef Delaunay::Point DPt; typedef Delaunay::Vertex_circulator Vertex_circulator; int m; std::vector<Pt> infected(n); for (int i = 0; i < n; i++) { int x, y; _i >> x >> y; infected[i] = Pt(x, y); } Delaunay D; D.insert(infected.begin(), infected.end()); Graph G(1); // only infinite face WeightMap wmap = boost::get(boost::edge_weight, G); // weight = width^2 = r^2*4 int newind = 1; // gradually add faces Face_iterator fit = D.finite_faces_begin(), fend = D.finite_faces_end(); for (; fit != fend; ++fit) { fit->info() = 0; // or it could be anything } fit = D.finite_faces_begin(), fend = D.finite_faces_end(); for (; fit != fend; ++fit) { Vertex u; if (!fit->info()) { u = boost::add_vertex(G); fit->info() = newind++; } else u = fit->info(); // circulate its 3 neighbors to add edges to the graph for (int nb = 0; nb < 3; nb++) { Face_handle fh = fit->neighbor(nb); if (D.is_infinite(fh)) { // infinite face: add edge to vertex 0 Vertex v = 0; Edge e; bool su; Vertex_handle vh1 = fit->vertex(fit->cw(nb)), vh2 = fit->vertex(fit->ccw(nb)); lint d2 = CGAL::squared_distance(vh1->point(), vh2->point()); boost::tie(e, su) = boost::add_edge(u, v, G); wmap[e] = d2; } else { // if the face hasn't been visited, add a new vertex and fill fh->info() Vertex v; if (!fh->info()) { fh->info() = newind++; v = boost::add_vertex(G); } else v = fh->info(); // continue if the edge already exists Edge e; bool su; boost::tie(e, su) = boost::edge(u, v, G); if (su) continue; Vertex_handle vh1 = fit->vertex(fit->cw(nb)), vh2 = fit->vertex(fit->ccw(nb)); lint d2 = CGAL::squared_distance(vh1->point(), vh2->point()); boost::tie(e, su) = boost::add_edge(u, v, G); wmap[e] = d2; } } } const lint BIG = 10000000000000000; typedef std::pair<lint, Vertex> DistV; int nv = boost::num_vertices(G); std::vector<DistV> vdist(nv); for (int i = 0; i < nv; i++) vdist[i] = std::make_pair(-1, i); std::vector<bool> selected(nv, false); // whether the width of a vertex has been optimized std::vector<lint> distmap(nv, -1); // the maximum width towards each vertex OutEdgeIt eit, eend; for (boost::tie(eit, eend) = boost::out_edges(0, G); eit != eend; eit++) { Vertex v = boost::target(*eit, G); vdist[v].first = std::max(vdist[v].first, (lint)wmap[*eit]); distmap[v] = std::max(distmap[v], (lint)wmap[*eit]); } vdist[0].first = 0; _e << "BFS " << _l; // BFS for max min edge std::priority_queue < DistV > pq(vdist.begin(), vdist.end()); selected[0] = true; distmap[0] = BIG; while (!pq.empty()) { DistV dv = pq.top(); pq.pop(); lint d = dv.first; Vertex u = dv.second; if (selected[u]) continue; // see the pq.push() below, one vertex could be pushed multiple times OutEdgeIt eit, eend; for (boost::tie(eit, eend) = boost::out_edges(u, G); eit != eend; eit++) { Vertex v = boost::target(*eit, G); if (!selected[v]) { // the updating rule: d[v] = max(d[v], min(w[e], d[u])) lint curw = std::max((long)distmap[v], std::min(wmap[*eit], (long)distmap[u])); distmap[v] = curw; pq.push(std::make_pair(distmap[v], v)); } } selected[u] = true; } _i >> m; for (int j = 0; j < m; j++) { int x, y; lint r2; _i >> x >> y >> r2; Pt person(x, y); Vertex_handle vh = D.nearest_vertex(person); if (CGAL::squared_distance(person, vh->point()) < r2) { _o << "n"; continue; } Face_handle fh = D.locate(person); if (D.is_infinite(fh)) { _o << "y"; continue; } Vertex u = fh->info(); if (r2 * 4 > distmap[u]) _o << "n"; else _o << "y"; } _o << _l; } // Week 8: Graypes / 50->50->50->100 // Delaunay, find shortest edge // Use Vertex_iterator to iterate through the vertices -> O(1) // rather than nearest_vertex() -> O(log n) // Tho I didn't they would kill an O(nlogn) algo.. // Don't play with constant when there is a method to improve asymptotic void Graypes(int n) { typedef CGAL::Triangulation_vertex_base_with_info_2<int, IK> Vb; typedef CGAL::Triangulation_data_structure_2<Vb> Tds; typedef CGAL::Delaunay_triangulation_2<IK, Tds> Delaunay; typedef Delaunay::Finite_faces_iterator Face_iterator; typedef Delaunay::Finite_edges_iterator Edge_iterator; typedef Delaunay::Finite_vertices_iterator Vertex_iterator; typedef Delaunay::Vertex_handle Vertex_handle; typedef Delaunay::Point DPt; typedef Delaunay::Vertex_circulator Vertex_circulator; std::vector< std::pair<Pt, int> > apes(n); for (int i = 0; i < n; i++) { int x, y; _i >> x >> y; apes[i] = std::make_pair(Pt(x, y), i); } //std::random_shuffle(apes.begin(), apes.end()); Delaunay D; D.insert(apes.begin(), apes.end()); const lint BIG = 10000000000000000; //std::vector<int> runto(n, -1); //std::vector<lint> d2runto(n, BIG); lint totalmind2 = BIG; Vertex_iterator vit = D.finite_vertices_begin(), vend = D.finite_vertices_end(); for (; vit != vend; ++vit) { Pt p = vit->point(); Vertex_circulator vc = D.incident_vertices(vit), done(vc); do { if (D.is_infinite(vc))continue; Pt q = vc->point(); lint d2pq = CGAL::squared_distance(p, q); totalmind2 = std::min(totalmind2, d2pq); } while (++vc != done); } /* O(nlogn) because of nearest_vertex() for (int i = 0; i < n; i++) { //lint mind2 = d2runto[i]; //int prunto = runto[i]; lint mind2 = BIG; Pt p = apes[i].first; int pind = apes[i].second; Vertex_handle vh = D.nearest_vertex(p); Vertex_circulator vc = D.incident_vertices(vh), done(vc); do { if (D.is_infinite(vc)) continue; Pt q = vc->point(); int qind = vc->info(); if (qind < pind) continue; lint d2pq = CGAL::squared_distance(p, q); if (d2pq < mind2) { mind2 = d2pq; //prunto = qind; } //else if (d2pq == mind2) { // Pt prevbest = apes[prunto].first; // if (q.x() < prevbest.x() || (q.x() == prevbest.x() && q.y() < prevbest.y())) { // prunto = qind; // } //} } while (++vc != done); //if (prunto != runto[i]) { // runto[i] = prunto; // d2runto[i] = mind2; // if (mind2 < d2runto[prunto]) { // runto[prunto] = i; // d2runto[prunto] = mind2; // } // else if (mind2 == d2runto[prunto]) { // Pt p2 = apes[runto[prunto]].first; // if (p.x() < p2.x() || (p.x() == p2.x() && p.y() < p2.y())) { // runto[prunto] = i; // } // } //} totalmind2 = std::min(totalmind2, mind2); } */ lint time = std::ceil(50 * std::sqrt((double)(totalmind2))); _o << time << _l; return; } // Week 11 PotW: Sith / 25->50->100pts // Delaunay + find connected components // Update connected components: Union Find int calcBiggestComponent(const std::vector<int>& comp, int ncomp) { int n = comp.size(); std::vector<int> counter(ncomp); for (int i = 0; i < n; i++) { counter[comp[i]]++; } int largest = 0; for (int j = 0; j < ncomp; j++) { largest = std::max(largest, counter[j]); } return largest; } void Comp2Par(const std::vector<int>& comp, int ncomp, std::vector<int>& par) { int n = comp.size(); std::vector<int> first(ncomp, -1); for (int i = 0; i < n; i++) { if (first[comp[i]] == -1) first[comp[i]] = i; par[i] = first[comp[i]]; } } void Sith() { typedef CGAL::Triangulation_vertex_base_with_info_2<int, IK> Vb; typedef CGAL::Triangulation_data_structure_2<Vb> Tds; typedef CGAL::Delaunay_triangulation_2<IK, Tds> Delaunay; typedef Delaunay::Finite_faces_iterator Face_iterator; typedef Delaunay::Finite_edges_iterator Edge_iterator; typedef Delaunay::Finite_vertices_iterator Vertex_iterator; typedef Delaunay::Vertex_handle Vertex_handle; typedef Delaunay::Point DPt; typedef Delaunay::Vertex_circulator Vertex_circulator; typedef boost::adjacency_list < boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property < boost::edge_weight_t, double > > Graph; typedef boost::property_map < Graph, boost::edge_weight_t >::type WeightMap; typedef boost::graph_traits < Graph >::edge_descriptor Edge; typedef boost::graph_traits < Graph >::vertex_descriptor Vertex; int n, r; _i >> n >> r; _e << "testcase: " << n << " " << r << _l; lint r2 = (lint)r*r; std::vector< std::pair<Pt, int> > p(n); // invert the input // so I choose planets [0, k) rather than [k, end) for (int i = 0; i < n; i++) { int x, y; _i >> x >> y; p[n - 1 - i] = std::make_pair(Pt(x, y), n - 1 - i); } Delaunay D; int nv = n / 2; D.insert(p.begin(), p.begin() + nv); Graph G(nv); for (int i = 0; i < nv; i++) { Vertex_handle vh = D.nearest_vertex(p[i].first); Pt pt = vh->point(); int ipt = vh->info(); Vertex_circulator vc = D.incident_vertices(vh), done(vc); do { if (D.is_infinite(vc)) continue; Pt pin = vc->point(); int ipin = vc->info(); if (ipin < ipt) continue; // i --> j, add edge when i < j lint d2 = CGAL::squared_distance(pt, pin); if (d2 <= r2) { boost::add_edge(ipt, ipin, G); } } while (++vc != done); } std::vector<int> comp(nv), par(nv); int ncomp = boost::connected_components(G, &comp[0]); int biggestComp = calcBiggestComponent(comp, ncomp); Comp2Par(comp, ncomp, par); UnionFind uf(par); for (int last = nv; last < n; last++) { int largestPossible = n - last - 1; if (biggestComp >= largestPossible) break; Vertex vlast = boost::add_vertex(G); Pt plast = p[last].first; // p[last].second == last D.insert(p.begin() + last, p.begin() + last + 1); int ipt = last; Vertex_handle vh = D.nearest_vertex(plast); Vertex_circulator vc = D.incident_vertices(vh), done(vc); uf.append(); do { if (D.is_infinite(vc)) continue; Pt pin = vc->point(); int ipin = vc->info(); lint d2 = CGAL::squared_distance(plast, pin); if (d2 <= r2) { boost::add_edge(ipt, ipin, G); uf.unionSets(ipt, ipin); } } while (++vc != done); //std::vector<int> ccomp(last+1); //int nccomp = boost::connected_components(G, &ccomp[0]); //int largest = calcBiggestComponent(ccomp, nccomp); int largest = uf.getMaxSize(); largest = std::min(largest, largestPossible); biggestComp = std::max(biggestComp, largest); } _e << "result: " << biggestComp << _l; _o << biggestComp << _l; return; } // Week 12: Radiation / 60->80->100 // LP + bin_search?? 2^300?? // LP (with Gmpz not Gmpq) + exp_search+bin_search // they are exact number types and don't worry about 2^300 struct PolyTerm { int xd; int yd; int zd; int idx; PolyTerm(int x = 0, int y = 0, int z = 0, int idx = 0) :xd(x), yd(y), zd(z), idx(idx) {} }; void calcPolyTerm(int deg, std::vector<PolyTerm> &terms) { //int balls = deg + 2; terms.clear(); int idx = 0; int d = deg; for (int d = 0; d <= deg; d++) { int balls = d + 2; for (int i = 0; i < balls - 1; i++) { for (int j = i + 1; j < balls; j++) { PolyTerm pt(i, j - i - 1, d + 1 - j, idx); terms.push_back(pt); idx++; } } } return; } typedef CGAL::Gmpz ETZ; typedef CGAL::Quadratic_program<ETZ> ProgramZ; typedef CGAL::Quadratic_program_solution<ETZ> SolutionZ; ETZ findPoly(int deg, std::vector<Pt3> &hcell, std::vector<Pt3> &tcell, std::vector< std::vector<ETZ> >& hpowers, std::vector< std::vector<ETZ> >& tpowers) { ProgramZ lp(CGAL::SMALLER, false, 0, false, 0); std::vector<PolyTerm> terms; calcPolyTerm(deg, terms); int h = hcell.size(), t = tcell.size(); int nterms = terms.size(); const int delta = nterms; for (int j = 0; j < nterms; j++) { //lp.set_c(j, 1); int xind = terms[j].xd, yind = 31 + terms[j].yd, zind = 62 + terms[j].zd; for (int i = 0; i < h; i++) { ETZ xyz = hpowers[i][xind] * hpowers[i][yind] * hpowers[i][zind]; lp.set_a(j, i, xyz); } for (int i = 0; i < t; i++) { ETZ xyz = tpowers[i][xind] * tpowers[i][yind] * tpowers[i][zind]; lp.set_a(j, h + i, -xyz); } } lp.set_c(delta, -1); //lp.set_l(delta, true, 0); lp.set_u(delta, true, 1); for (int i = 0; i < h; i++) { lp.set_b(i, 0); lp.set_a(delta, i, 0); } for (int i = 0; i < t; i++) { lp.set_a(delta, h + i, 1); lp.set_b(h + i, 0); } SolutionZ s = CGAL::solve_linear_program(lp, ETZ()); //if (s.is_optimal() && s.objective_value() < 0) // return true; //return false; ETZ result = s.objective_value().numerator() / s.objective_value().denominator(); return result; } void calcPowers(std::vector<Pt3> & cell, std::vector< std::vector<ETZ> >& powers) { int n = cell.size(); _e << "powers!" << _l; for (int i = 0; i < n; i++) { powers[i] = std::vector<ETZ>(93); ETZ xp(1), yp(1), zp(1); int cx = (int)cell[i].x(); int cy = (int)cell[i].y(); int cz = (int)cell[i].z(); for (int d = 0; d <= 30; d++) { powers[i][d] = xp; powers[i][31 + d] = yp; powers[i][62 + d] = zp; if (d == 30) break; xp *= cx; yp *= cy; zp *= cz; //_e << xp << " " << yp << " " << zp << _l; } } } void Radiation() { int h, t; _i >> h >> t; std::vector<Pt3> hcell(h), tcell(t); for (int i = 0; i < h; i++) { int x, y, z; _i >> x >> y >> z; hcell[i] = Pt3(x, y, z); //_e << hcell[i] << _l; } for (int j = 0; j < t; j++) { int x, y, z; _i >> x >> y >> z; tcell[j] = Pt3(x, y, z); //_e << tcell[j] << _l; } if (h == 0 || t == 0) { _o << 0 << _l; return; } std::vector< std::vector<ETZ> > hpowers(h), tpowers(t); calcPowers(hcell, hpowers); calcPowers(tcell, tpowers); _e << "calcpowers!" << _l; //std::vector<bool> canFinds(31, false); std::vector<ETZ> res(31, 0); int st = 0, ed = 1; int low, up, mid; while (true) { _e << "d=" << ed << _l; //canFinds[ed] = canFindPoly(ed, hcell, tcell, hpowers, tpowers); res[ed] = findPoly(ed, hcell, tcell, hpowers, tpowers); if (res[ed] < 0) { low = st; up = ed; mid = (low + up) / 2; break; } else { if (ed == 30) { _o << "Impossible!\n"; return; } st = ed; ed = std::min(30, ed * 2); } } // binary search while (true) { _e << "d=" << mid << _l; if (up - low <= 1) { if (res[low]<0 || findPoly(low, hcell, tcell, hpowers, tpowers)<0) { _o << low << _l; return; } else if (res[up]<0 || findPoly(up, hcell, tcell, hpowers, tpowers)<0) { _o << up << _l; return; } } res[mid] = findPoly(mid, hcell, tcell, hpowers, tpowers); if (res[mid]<0) { up = mid; mid = (low + up) / 2; } else { low = mid + 1; mid = (low + up) / 2; } } _e << _l; _o << "Impossible!" << _l; return; } // Week 13: Clues / 100pts // Delaunay + is_bipartite + connected_components void Clues() { typedef CGAL::Triangulation_vertex_base_with_info_2<int, IK> Vb; typedef CGAL::Triangulation_data_structure_2<Vb> Tds; typedef CGAL::Delaunay_triangulation_2<IK, Tds> Delaunay; typedef Delaunay::Finite_faces_iterator Face_iterator; typedef Delaunay::Finite_edges_iterator Edge_iterator; typedef Delaunay::Finite_vertices_iterator Vertex_iterator; typedef Delaunay::Vertex_handle Vertex_handle; typedef Delaunay::Point DPt; typedef Delaunay::Vertex_circulator Vertex_circulator; typedef boost::adjacency_list < boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property < boost::edge_weight_t, double > > Graph; typedef boost::property_map < Graph, boost::edge_weight_t >::type WeightMap; typedef boost::graph_traits < Graph >::edge_descriptor Edge; typedef boost::graph_traits < Graph >::vertex_descriptor Vertex; int n, m, r; _i >> n >> m >> r; lint r2 = (lint)r*r; std::vector< std::pair<Pt, int> > stations(n); std::vector< std::pair<Pt, Pt> > clues(m); for (int i = 0; i < n; i++) { int x, y; _i >> x >> y; stations[i] = std::make_pair(Pt(x, y), i); } for (int j = 0; j < m; j++) { int xa, ya, xb, yb; _i >> xa >> ya >> xb >> yb; clues[j] = std::make_pair(Pt(xa, ya), Pt(xb, yb)); } Graph G(n); std::vector<int> components(n); Delaunay D; D.insert(stations.begin(), stations.end()); Vertex_iterator vit; bool violated = false; for (vit = D.finite_vertices_begin(); vit != D.finite_vertices_end(); ++vit) { Vertex_circulator vc = D.incident_vertices(vit), done(vc); int idx = vit->info(); std::vector< std::pair<Pt, int> > candidates; candidates.push_back(std::make_pair(vit->point(), vit->info())); do { if (!D.is_infinite(vc)) { int vcidx = vc->info(); //if (vcidx < idx) continue; if (CGAL::squared_distance(vc->point(), vit->point()) > r2) continue; //boost::add_edge(idx, vcidx, G); candidates.push_back(std::make_pair(vc->point(), vcidx)); } } while (++vc != done); int ncand = candidates.size(); for (int i = 1; i < ncand; i++) { Pt pi = candidates[i].first; for (int j = i + 1; j < ncand; j++) { Pt pj = candidates[j].first; if (CGAL::squared_distance(pi, pj) <= r2) { violated = true; break; } } } if (violated) break; for (int j = 1; j < ncand; j++) { int idxj = candidates[j].second; boost::add_edge(idx, idxj, G); } } if (violated) { for (int j = 0; j < m; j++) { _o << "n"; } _o << _l; _e << "violated" << _l; return; } bool isBipartite = boost::is_bipartite(G); if (!isBipartite) { for (int j = 0; j < m; j++) { _o << "n"; } _o << _l; _e << "n" << _l; return; } boost::connected_components(G, &components[0]); for (int i = 0; i < n; i++) { _e << components[i] << " "; }_e << _l; for (int j = 0; j < m; j++) { Pt a = clues[j].first, b = clues[j].second; if (CGAL::squared_distance(a, b) <= r2) { _o << "y"; continue; } Vertex_handle vha = D.nearest_vertex(a); Vertex_handle vhb = D.nearest_vertex(b); // not reachable to any station if (CGAL::squared_distance(vha->point(), a) > r2 || CGAL::squared_distance(vhb->point(), b) > r2) { _o << "n"; continue; } // not in the same component int idxa = vha->info(), idxb = vhb->info(); if (components[idxa] == components[idxb]) { _o << "y"; //_e << vha->point() << "|" << vhb->point() << _l; //_e << components[idxa] << " " << components[idxb] << _l; } else _o << "n"; } _o << _l; return; } // Week 13: Goldfinger / 100 pts // LP + Delaunay + bin_search typedef CGAL::Delaunay_triangulation_2<IK> Delaunay; typedef Delaunay::Finite_faces_iterator Face_iterator; typedef Delaunay::Finite_edges_iterator Edge_iterator; typedef Delaunay::Vertex_handle Vertex_handle; typedef Delaunay::Point DPt; bool isSolvable(int a, std::vector<Pt> &psensor, std::vector<int> &esensor, std::vector<Pt> &pmpe, std::vector<lint> &r2mpe, int Imax, std::vector< std::vector<lint> >& d2) { int n = psensor.size(); int m = pmpe.size(); bool isRestricted = r2mpe[0] > 0; Program lp(CGAL::LARGER, true, 0, false); for (int i = 0; i < n; i++) { for (int j = 0; j < a; j++) { //lint d2 = CGAL::squared_distance(pmpe[j], psensor[i]); if (!isRestricted || d2[i][j] < r2mpe[j]) lp.set_a(j, i, (ET)1 / d2[i][j]); } lp.set_b(i, esensor[i]); } for (int j = 0; j < a; j++) { lp.set_a(j, n, -1); lp.set_c(j, 1); } lp.set_b(n, -Imax); Solution s = CGAL::solve_linear_program(lp, ET()); if (s.is_optimal()) { //_o << a << _l; return true; } else { return false; } } void Goldfinger() { int n, m, h, Imax; _i >> n >> m >> h >> Imax; std::vector<Pt> psensor(n); std::vector<Pt> pmpe(m); std::vector<Pt> phench(h); std::vector<int> esensor(n); lint BIG = (1 << 55); std::vector<lint> r2mpe(m, -1); std::vector< std::vector<lint> > d2(n); for (int i = 0; i < n; i++) { int x, y, e; _i >> x >> y >> e; psensor[i] = Pt(x, y); esensor[i] = e; } for (int j = 0; j < m; j++) { int x, y; _i >> x >> y; pmpe[j] = Pt(x, y); } for (int k = 0; k < h; k++) { int x, y; _i >> x >> y; phench[k] = Pt(x, y); } Delaunay D; D.insert(phench.begin(), phench.end()); if (h > 0) { for (int j = 0; j < m; j++) { Vertex_handle vh = D.nearest_vertex(pmpe[j]); r2mpe[j] = CGAL::squared_distance(vh->point(), pmpe[j]); } } for (int i = 0; i < n; i++) { d2[i] = std::vector<lint>(m); for (int j = 0; j < m; j++) { d2[i][j] = CGAL::squared_distance(psensor[i], pmpe[j]); } } if (isSolvable(1, psensor, esensor, pmpe, r2mpe, Imax, d2)) { _o << 1 << _l; return; } // exp. search for an interval std::vector<int> solvables(m + 1, 0); // 0 = not touched, 1 = solvable, -1 = unsolvable //solvables[m] = 1; solvables[1] = -1; int st = 1, end = 2; while (end <= m) { _e << "end=" << end << _l; if (solvables[end] == 1 || isSolvable(end, psensor, esensor, pmpe, r2mpe, Imax, d2)) { solvables[end] = 1; break; } else { solvables[end] = -1; if (end == m) break; st = end; end = std::min(end * 2, m); } } if (solvables[m] == -1) { _o << "impossible" << _l; return; } // binary search for the best int low = st, up = end, a = (low + up) / 2; while (true) { _e << "a=" << a << _l; if (up - low <= 1) { if (solvables[low] == 1 || isSolvable(low, psensor, esensor, pmpe, r2mpe, Imax, d2)) { _o << low << _l; return; } if (solvables[up] == 1 || isSolvable(up, psensor, esensor, pmpe, r2mpe, Imax, d2)) { _o << up << _l; return; } break; // impossible } bool solvable = isSolvable(a, psensor, esensor, pmpe, r2mpe, Imax, d2); if (solvable) { solvables[a] = 1; up = a; a = (low + up) / 2; } else { solvables[a] = -1; low = a; a = (low + up) / 2; } } _o << "impossible" << _l; return; } // Week 3: First Hit / 99->100 // For 5555 pts total! // OMG really?? random shuffle?? double floor_to_double_EK(const EK::FT& x) { double a = std::floor(CGAL::to_double(x)); while (a > x) a -= 1; while (a + 1 <= x) a += 1; return a; } void FirstHit(int n) { lint x, y, a, b, r, s, t, u; std::cin >> x >> y >> a >> b; IK::Point_2 p1(x, y), p2(a, b); IK::Ray_2 ray(p1, p2); EK::Point_2 ep1((double)x, (double)y), ep2((double)a, (double)b); EK::Ray_2 eray(ep1, ep2); EK::Segment_2 eseg; bool ishit = false; EK::FT minsqd = 5e100; EK::Point_2 minits(0, 0), curits(0, 0); std::vector<EK::Segment_2> esegs(n); for (int i = 0; i < n; i++) { _i >> r >> s >> t >> u; EK::Point_2 eq1((double)r, (double)s), eq2((double)t, (double)u); EK::Segment_2 esegq(eq1, eq2); esegs[i] = esegq; } std::random_shuffle(esegs.begin(), esegs.end()); for (int i = 0; i < n; i++) { EK::Segment_2 esegq = esegs[i]; EK::Point_2 eq1 = esegq.start(), eq2 = esegq.end(); if (ishit) { if (CGAL::do_intersect(eseg, esegq)) { auto result = CGAL::intersection(eseg, esegq); if (const EK::Segment_2* sp = boost::get<EK::Segment_2>(&*result)) { _e << "segment" << _l; EK::FT sqd1 = CGAL::squared_distance(ep1, eq1); EK::FT sqd2 = CGAL::squared_distance(ep1, eq2); if (sqd1 < sqd2) { minits = eq1; } else { minits = eq2; } } else if (const EK::Point_2* pp = boost::get<EK::Point_2>(&*result)) { _e << "point" << _l; minits = *pp; } eseg = EK::Segment_2(ep1, minits); } } else { if (CGAL::do_intersect(eray, esegq)) { auto result = CGAL::intersection(eray, esegq); if (const EK::Segment_2* sp = boost::get<EK::Segment_2>(&*result)) { _e << "segment0" << _l; EK::FT sqd1 = CGAL::squared_distance(ep1, eq1); EK::FT sqd2 = CGAL::squared_distance(ep1, eq2); if (sqd1 < sqd2) { minits = eq1; } else if (sqd2 < sqd1) { minits = eq2; } } else if (const EK::Point_2* pp = boost::get<EK::Point_2>(&*result)) { minits = *pp; } eseg = EK::Segment_2(ep1, minits); ishit = true; } } } if (!ishit) { std::cout << "no" << std::endl; return; } std::cout << (lint)floor_to_double_EK(minits.x()) << " " << (lint)floor_to_double_EK(minits.y()) << std::endl; return; } // Week 13, PotW: World Cup / 100 pts // LP + Triangulation typedef CGAL::Delaunay_triangulation_2<IK> Delaunay; typedef Delaunay::Finite_faces_iterator Face_iterator; typedef Delaunay::Finite_edges_iterator Edge_iterator; typedef Delaunay::Vertex_handle Vertex_handle; typedef Delaunay::Point DPt; struct Warehouse { Pt p; int s; int a; Warehouse(int x = 0, int y = 0, int s = -1, int ac = -1) :s(s), a(ac) { p = Pt(x, y); } }; struct Stadium { Pt p; int d; int u; Stadium(int x = 0, int y = 0, int d = -1, int u = -1) :d(d), u(u) { p = Pt(x, y); } }; struct Contour { Pt p; int r; Contour(int x = 0, int y = 0, int r = 0) : r(r) { p = Pt(x, y); } }; void WorldCup() { int n, m, c; _i >> n >> m >> c; std::vector<Warehouse> whs(n); std::vector<Stadium> sts(m); std::vector<Contour> cts; // not initialized -- need to choose! std::vector<Pt> whst; for (int i = 0; i < n; i++) { int x, y, s, a; _i >> x >> y >> s >> a; whs[i] = Warehouse(x, y, s, a); whst.push_back(Pt(x, y)); } for (int j = 0; j < m; j++) { int x, y, d, u; _i >> x >> y >> d >> u; sts[j] = Stadium(x, y, d, u); whst.push_back(Pt(x, y)); } int r[200][20] = {}, t[200][20] = {}; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { _i >> r[i][j]; } } Delaunay D; D.insert(whst.begin(), whst.end()); for (int k = 0; k < c; k++) { lint x, y, rad; _i >> x >> y >> rad; Pt p(x, y); Vertex_handle vh = D.nearest_vertex(p); double d2 = CGAL::squared_distance(p, vh->point()); if (d2 < rad*rad) { cts.push_back(Contour(x, y, rad)); } } int uc = cts.size(); // used c for (int k = 0; k < uc; k++) { lint r2 = cts[k].r * cts[k].r; for (int i = 0; i < n; i++) { if (CGAL::squared_distance(whs[i].p, cts[k].p) < r2) for (int j = 0; j < m; j++) t[i][j] += (CGAL::squared_distance(sts[j].p, cts[k].p) > r2); else for (int j = 0; j < m; j++) t[i][j] += (CGAL::squared_distance(sts[j].p, cts[k].p) < r2); } } // form LP, n*m variables, n+m*2 constraints Program lp(CGAL::SMALLER, true, 0, false, 0); for (int i = 0; i < n; i++) { lp.set_b(i, whs[i].s); for (int j = 0; j < m; j++) { lp.set_a(i*m + j, i, 1); } } for (int j = 0; j < m; j++) { lp.set_b(n + j, -sts[j].d); lp.set_b(n + 2 * m + j, sts[j].d); lp.set_b(n + m + j, sts[j].u * 100); for (int i = 0; i < n; i++) { lp.set_a(i*m + j, n + j, -1); lp.set_a(i*m + j, n + 2 * m + j, 1); lp.set_a(i*m + j, n + m + j, whs[i].a); } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int idx = i*m + j; lp.set_c(idx, -100 * r[i][j] + t[i][j]); } } Solution s = CGAL::solve_linear_program(lp, ET()); if (s.is_optimal()) { ET result = s.objective_value().numerator() / (100 * s.objective_value().denominator()); lint llr = floor_to_double(-result); _o << llr << _l; } else { _o << "RIOT!" << _l; } return; } // Week 10: Light the Stage // Delaunay Triangulation + binary search typedef CGAL::Delaunay_triangulation_2<IK> Delaunay; typedef Delaunay::Finite_faces_iterator Face_iterator; typedef Delaunay::Finite_edges_iterator Edge_iterator; typedef Delaunay::Vertex_handle Vertex_handle; typedef Delaunay::Point DPt; struct Participant { Pt p; lint r; Participant(int x = 0, int y = 0, lint r = 0) :p(Pt(x, y)), r(r) {} Participant(Pt p, lint r = 0) :p(p), r(r) {} }; void binarySearchLeftover(std::vector<Participant> &ps, std::vector<Pt> &lights, int h, std::vector<int> &leftover) { int m = ps.size(), n = lights.size(); Delaunay D; D.clear(); int start = 1, end = n - 1, mid = (start + end) / 2; std::vector<bool> aliveAfterMid(m, true); std::vector<int> tmpLeftOver; while (true) { if (end - start <= 1) break; D.clear(); tmpLeftOver.clear(); bool alive = false; D.insert(lights.begin(), lights.begin() + mid); for (int i = 0; i < m; i++) { Vertex_handle vh = D.nearest_vertex(ps[i].p); lint d2 = CGAL::squared_distance(vh->point(), ps[i].p); if (d2 >= (ps[i].r + h)*(ps[i].r + h)) { // existing one living participant: update the interval start = mid; mid = (start + end) / 2; alive = true; break; } } if (!alive) { end = mid - 1; mid = (start + end) / 2; } } _e << "mid: " << mid << _l; D.clear(); D.insert(lights.begin(), lights.begin() + mid); if (mid < end) { std::vector<int> endleftover; D.clear(); D.insert(lights.begin(), lights.begin() + end); for (int i = 0; i < m; i++) { Vertex_handle vh = D.nearest_vertex(ps[i].p); lint d2 = CGAL::squared_distance(vh->point(), ps[i].p); if (d2 >= (ps[i].r + h)*(ps[i].r + h)) { // existing one living participant: update the interval endleftover.push_back(i); } } if (!endleftover.empty()) { leftover.clear(); leftover.insert(leftover.begin(), endleftover.begin(), endleftover.end()); } } return; } void LightTheStage() { int m, n, h; _i >> m >> n; _e << m << " " << n << _l; std::vector<Participant> ps(m); for (int i = 0; i < m; i++) { int x, y, r; _i >> x >> y >> r; ps[i] = Participant(x, y, r); } _i >> h; std::vector<Pt> lights(n); for (int j = 0; j < n; j++) { int x, y; _i >> x >> y; lights[j] = Pt(x, y); } Delaunay D; D.insert(lights.begin(), lights.end()); std::vector<int> leftover; for (int i = 0; i < m; i++) { Vertex_handle vh = D.nearest_vertex(ps[i].p); lint d2 = CGAL::squared_distance(vh->point(), ps[i].p); if (d2 >= (ps[i].r + h)*(ps[i].r + h)) { leftover.push_back(i); } } if (!leftover.empty()) { int l = leftover.size(); for (int i = 0; i < l; i++) { _o << leftover[i] << " "; } } else { binarySearchLeftover(ps, lights, h, leftover); int l = leftover.size(); for (int i = 0; i < l; i++) { _o << leftover[i] << " "; } } _o << _l; return; } // week 8: Bistro (nearest_vertex) void Bistro(int n) { typedef CGAL::Delaunay_triangulation_2<IK> Delaunay; typedef Delaunay::Finite_faces_iterator Face_iterator; typedef Delaunay::Finite_edges_iterator Edge_iterator; typedef Delaunay::Vertex_handle Vertex_handle; typedef Delaunay::Point DPt; //int n, m; _i >> n; std::vector<Pt> existing(n); for (int i = 0; i < n; i++) { int x, y; _i >> x >> y; existing[i] = Pt(x, y); } int m; _i >> m; std::vector<Pt> possible(m); for (int j = 0; j < m; j++) { int x, y; _i >> x >> y; possible[j] = Pt(x, y); } Delaunay D; D.insert(existing.begin(), existing.end()); for (int j = 0; j < m; j++) { Vertex_handle vh = D.nearest_vertex(possible[j]); lint d2 = CGAL::squared_distance(vh->point(), possible[j]); _o << d2 << _l; } return; } // Week 11: Strikes Back // Delaunay triangulation for r // LP for e void StrikesBack() { typedef CGAL::Delaunay_triangulation_2<IK> Delaunay; typedef Delaunay::Finite_faces_iterator Face_iterator; typedef Delaunay::Finite_edges_iterator Edge_iterator; typedef Delaunay::Vertex_handle Vertex_handle; typedef Delaunay::Point DPt; struct Asteroid { Pt pos; int d; Asteroid(Pt p = Pt(), int d = 0) : pos(p), d(d) {} }; int a, s, b; _i >> a >> s >> b; int emax; _i >> emax; std::vector<Asteroid> asters(a); std::vector<Pt> shotpos(s); // model r and e outside. std::vector<Pt> bounties(b); for (int i = 0; i < a; i++) { int x, y, d; _i >> x >> y >> d; asters[i] = Asteroid(Pt(x, y), d); } for (int i = 0; i < s; i++) { int x, y; _i >> x >> y; shotpos[i] = Pt(x, y); } for (int i = 0; i < b; i++) { int x, y; _i >> x >> y; bounties[i] = DPt(x, y); } // triangulate bounties Delaunay D; D.insert(bounties.begin(), bounties.end()); _e << "delaunay" << _l; std::vector<lint> shotradsq(s); if (b > 0) { for (int i = 0; i < s; i++) { DPt dpt(shotpos[i]); Vertex_handle vh = D.nearest_vertex(shotpos[i]); shotradsq[i] = CGAL::squared_distance(shotpos[i], vh->point()); if (shotradsq[i] < 1) { shotradsq[i] = 1; } } _e << "shotradsq" << _l; } // set up LP to solve for min\Sum_i e_i Program lp(CGAL::LARGER, true, 0, true, emax); // Ax >= b for (int i = 0; i < a; i++) { lp.set_b(i, asters[i].d); for (int j = 0; j < s; j++) { lint sqdistij = CGAL::squared_distance(asters[i].pos, shotpos[j]); if (b == 0 || sqdistij <= shotradsq[j]) { // in shot range lp.set_a(j, i, ET(1) / sqdistij); // will it work? } } } for (int j = 0; j < s; j++) { lp.set_c(j, 1); } _e << "lpsetup" << _l; // solve the program, using ET as the exact type Solution solution = CGAL::solve_linear_program(lp, ET()); assert(solution.solves_linear_program(lp)); if (solution.is_infeasible()) { _o << "n" << _l; return; } else { ET eoptimal = solution.objective_value().numerator() / solution.objective_value().denominator(); if (eoptimal <= emax) { _o << "y" << _l; } else { _o << "n" << _l; } } return; } // Week 12 PotW: Golden Eye / 100pts // Euclidean (Kruskal) MST + Union Find for connectivity // Cautions(I am not good today...): // 1. check connectivity before adding any edges // 2. it could be that the distance from queries to its nearest_vertex dominates the distance // 3. beware of the order of setting a variable and using its value...... // 4. set everything to _lint_.... lint minLevelSet(Graph& G, std::vector<Edge>& mst, std::vector<int>& s, std::vector<int> &t, std::vector<lint> &maxd2, lint maxp) { int n = boost::num_vertices(G); int m = s.size(); WeightMap wmap = boost::get(boost::edge_weight, G); UnionFind uf(n); lint start = 0; std::vector<bool> isconnected(m, false); bool allconn = true; for (int j = 0; j < m; j++) { start = std::max(start, maxd2[j]); isconnected[j] = uf.inSameSet(s[j], t[j]); if (!isconnected[j]) allconn = false; } if (allconn || start > maxp) { return start; } std::vector<Edge>::iterator eit = mst.begin(); for (; eit != mst.end(); eit++) { if (wmap[*eit] > maxp) return -1; int u = boost::source(*eit, G); int v = boost::target(*eit, G); uf.unionSets(u, v); if (eit == mst.end() - 1 || wmap[*(eit + 1)] >= start) { bool allconnected = true; for (int j = 0; j < m; j++) { if (isconnected[j]) continue; if (uf.inSameSet(s[j], t[j])) isconnected[j] = true; if (!isconnected[j]) allconnected = false; // isconnected[j] could have been altered! } if (allconnected) return std::max(start, (lint)wmap[*eit]); } } return -1; // never happen } void GoldenEye2() { typedef CGAL::Triangulation_vertex_base_with_info_2<ind_t, IK> Vb; typedef CGAL::Triangulation_data_structure_2<Vb> Tds; typedef CGAL::Delaunay_triangulation_2<IK, Tds> Delaunay; typedef Delaunay::Finite_faces_iterator Face_iterator; typedef Delaunay::Finite_edges_iterator Edge_iterator; typedef Delaunay::Vertex_handle Vertex_handle; typedef Delaunay::Point DPt; lint n, m, p; _i >> n >> m >> p; std::vector< std::pair<DPt, int> > jams(n); std::vector<Pt> ss(m); std::vector<Pt> ts(m); Graph G(n); // undirected graph WeightMap weight = boost::get(boost::edge_weight, G); int x, y; for (int i = 0; i < n; i++) { _i >> x >> y; jams[i] = std::make_pair(DPt(x, y), i); } for (int j = 0; j < m; j++) { int x0, y0, x1, y1; _i >> x0 >> y0 >> x1 >> y1; ss[j] = Pt(x0, y0); ts[j] = Pt(x1, y1); } Delaunay D; D.insert(jams.begin(), jams.end()); // Euclid MST for (Edge_iterator ei = D.finite_edges_begin(); ei != D.finite_edges_end(); ++ei) { Vertex_handle v1 = ei->first->vertex((ei->second + 1) % 3); Vertex_handle v2 = ei->first->vertex((ei->second + 2) % 3); int i1 = v1->info(); int i2 = v2->info(); lint dist = CGAL::squared_distance(v1->point(), v2->point()); //_e << i1 << " " << i2 << ":" << dist << _l; bool success; Edge e; boost::tie(e, success) = boost::add_edge(i1, i2, G); if (success) weight[e] = dist; } std::vector<Edge> spanning_tree; boost::kruskal_minimum_spanning_tree(G, std::back_inserter(spanning_tree)); std::vector<lint> ds(m), dt(m), maxpow(m); std::vector<Vertex_handle> vs(m), vt(m); std::vector<int> visited(m); std::vector<bool> pset(m, true); for (int j = 0; j < m; j++) { Pt s = ss[j], t = ts[j]; vs[j] = D.nearest_vertex(s), vt[j] = D.nearest_vertex(t); ds[j] = CGAL::squared_distance(vs[j]->point(), s); dt[j] = CGAL::squared_distance(vt[j]->point(), t); maxpow[j] = 4 * std::max(ds[j], dt[j]); visited[j] = 0; if (maxpow[j] > p) pset[j] = false; } // check power level p Graph MSTP(n); std::vector<Edge>::iterator eit; lint maxwinmst = weight[spanning_tree[spanning_tree.size() - 1]]; // max weight in the MST for (eit = spanning_tree.begin(); eit != spanning_tree.end(); ++eit) { if (weight[*eit] > p) break; Vertex u = boost::source(*eit, G); Vertex v = boost::target(*eit, G); boost::add_edge(u, v, MSTP); } std::vector<int> components(n); boost::connected_components(MSTP, &components[0]); std::vector<int> p_s, p_t, all_s, all_t; std::vector<lint> p_maxd2, all_maxd2; for (int j = 0; j < m; j++) { if (!pset[j]) continue; int sidx = vs[j]->info(), tidx = vt[j]->info(); if (components[sidx] != components[tidx]) { pset[j] = false; } if (pset[j]) { p_s.push_back(sidx); p_t.push_back(tidx); p_maxd2.push_back(maxpow[j]); } } for (int j = 0; j < m; j++) { all_s.push_back(vs[j]->info()); all_t.push_back(vt[j]->info()); all_maxd2.push_back(maxpow[j]); } lint b = minLevelSet(G, spanning_tree, p_s, p_t, p_maxd2, p); lint a = minLevelSet(G, spanning_tree, all_s, all_t, all_maxd2, maxwinmst); for (int j = 0; j < m; j++) { if (pset[j]) _o << "y"; else _o << "n"; } _o << _l; _o << a << _l; _o << b << _l; } // Week 12 PotW: Golden Eye / 75pts // called uf.inSameSet() too many times void GoldenEye() { typedef CGAL::Triangulation_vertex_base_with_info_2<ind_t, IK> Vb; typedef CGAL::Triangulation_data_structure_2<Vb> Tds; typedef CGAL::Delaunay_triangulation_2<IK, Tds> Delaunay; typedef Delaunay::Finite_faces_iterator Face_iterator; typedef Delaunay::Finite_edges_iterator Edge_iterator; typedef Delaunay::Vertex_handle Vertex_handle; typedef Delaunay::Point DPt; lint n, m, p; _i >> n >> m >> p; std::vector< std::pair<DPt, int> > jams(n); std::vector<Pt> ss(m); std::vector<Pt> ts(m); Graph G(n); WeightMap weight = boost::get(boost::edge_weight, G); int x, y; for (int i = 0; i < n; i++) { _i >> x >> y; jams[i] = std::make_pair(DPt(x, y), i); } for (int j = 0; j < m; j++) { int x0, y0, x1, y1; _i >> x0 >> y0 >> x1 >> y1; ss[j] = Pt(x0, y0); ts[j] = Pt(x1, y1); } Delaunay D; D.insert(jams.begin(), jams.end()); // Euclid MST for (Edge_iterator ei = D.finite_edges_begin(); ei != D.finite_edges_end(); ++ei) { Vertex_handle v1 = ei->first->vertex((ei->second + 1) % 3); Vertex_handle v2 = ei->first->vertex((ei->second + 2) % 3); int i1 = v1->info(); int i2 = v2->info(); double dist = CGAL::squared_distance(v1->point(), v2->point()); //_e << i1 << " " << i2 << ":" << dist << _l; bool success; Edge e; boost::tie(e, success) = boost::add_edge(i1, i2, G); if (success) weight[e] = dist; } std::vector<Edge> spanning_tree; boost::kruskal_minimum_spanning_tree(G, std::back_inserter(spanning_tree)); double a = 0, b = -1; std::vector<double> ds(m), dt(m), maxpow(m); std::vector<Vertex_handle> vs(m), vt(m); std::vector<int> visited(m); for (int j = 0; j < m; j++) { Pt s = ss[j], t = ts[j]; vs[j] = D.nearest_vertex(s), vt[j] = D.nearest_vertex(t); ds[j] = CGAL::squared_distance(vs[j]->point(), s); dt[j] = CGAL::squared_distance(vt[j]->point(), t); maxpow[j] = 4 * std::max(ds[j], dt[j]); visited[j] = 0; } UnionFind uf(n); std::vector<Edge>::iterator ei; double w = 0, wlastchanged = 0; bool changed = false; for (int j = 0; j < m; j++) { if (uf.inSameSet(vs[j]->info(), vt[j]->info())) { // effectively vs[j]->info() == vt[j]->info() visited[j] = 1; changed = true; } } // Gradually add edges of the MST for (ei = spanning_tree.begin(); ei != spanning_tree.end(); ++ei) { Vertex v1 = boost::source(*ei, G), v2 = boost::target(*ei, G); uf.unionSets(v1, v2); w = weight[*ei]; // if (w > p && b < 0) b = wlastchanged; changed = false; bool allvisited = true; for (int j = 0; j < m; j++) { if (!visited[j]) allvisited = false; if (!visited[j] && uf.inSameSet(vs[j]->info(), vt[j]->info())) { visited[j] = 1; changed = true; maxpow[j] = std::max(w, maxpow[j]); } } if (changed) wlastchanged = w; if (allvisited) break; } //if (w > p && b < 0) b = wlastchanged; if (b < 0) b = 0; for (int j = 0; j < m; j++) { a = std::max(a, maxpow[j]); //if (!visited[j]) _e << vs[j]->info() << "?" << vt[j]->info() << _l; //_e << maxpow[j] << " "; if (maxpow[j] > p) visited[j] = 2; else { if (b < maxpow[j]) b = maxpow[j]; } } _e << _l; for (int j = 0; j < m; j++) { _o << (visited[j] == 1 ? "y" : "n"); } _o << _l; _o << (lint)std::ceil(a) << _l; _o << (lint)std::ceil(b) << _l; return; } // typedef CGAL:Gmpz ET; void Inball(int n, int d) { Program lp(CGAL::SMALLER, false, 0, false, 0); int c[10] = {}; for (int i = 0; i < d; i++) c[i] = i; const int r = d; int a = 0, b = 0; for (int i = 0; i < n; i++) { double norm = 0; for (int j = 0; j < d; j++) { _i >> a; lp.set_a(c[j], i, a); norm += a*a; } lp.set_a(r, i, std::round(std::sqrt(norm))); _i >> b; lp.set_b(i, b); } lp.set_l(r, true, 0); lp.set_c(r, -1); // solve the program, using ET as the exact type Solution s = CGAL::solve_linear_program(lp, ET()); assert(s.solves_linear_program(lp)); if (s.is_optimal()) { CGAL::Quadratic_program_solution<ET>::Variable_value_iterator opt = s.variable_values_begin(); CGAL::Quotient<ET> rad = *(opt + d); _o << (int)floor_to_double(rad) << _l; } else if (s.is_unbounded()) { _o << "inf" << _l; } else if (s.is_infeasible()) { _o << "none" << _l; } return; } void Lestrade() { typedef CGAL::Triangulation_vertex_base_with_info_2<ind_t, IK> Vb; typedef CGAL::Triangulation_data_structure_2<Vb> Tds; typedef CGAL::Delaunay_triangulation_2<IK, Tds> Delaunay; typedef Delaunay::Finite_faces_iterator Face_iterator; typedef Delaunay::Finite_edges_iterator Edge_iterator; typedef Delaunay::Vertex_handle Vertex_handle; typedef Delaunay::Point DPt; struct Gangster { int u; int v; int w; int ag; Gangster(int uu = 0, int vv = 0, int ww = 0, int a = -1) : u(uu), v(vv), w(ww), ag(a) {} }; int Z, U, V, W; int A, G; _i >> Z >> U >> V >> W >> A >> G; std::vector<std::pair<DPt, ind_t> > pts(G); std::vector<Gangster> gang(G); for (ind_t i = 0; i < G; i++) { int x, y, u, v, w; _i >> x >> y >> u >> v >> w; DPt pg(x, y); pts[i] = std::make_pair(pg, i); gang[i] = Gangster(u, v, w); } Delaunay T; T.insert(pts.begin(), pts.end()); //_e << gang.size() << _l; std::vector<int> ha(A); std::vector<int> spect(A); for (ind_t i = 0; i < A; i++) { int x, y, h; _i >> x >> y >> h; ha[i] = h; DPt pa(x, y); Vertex_handle vh = T.nearest_vertex(pa); ind_t gind = vh->info(); ind_t aind = gang[gind].ag; //_e << "gind" << gind << "; aind" << aind << _l; if (aind < 0 || (aind >= 0 && ha[aind] > h)) { // the gangster has not been inspected by others // or he has been inspected by another more expensive agent // --> I will do that instead! spect[i] = gind; gang[gind].ag = i; if (aind >= 0) { spect[aind] = -1; } } else { spect[i] = -1; } } //_e << ha.size() << _l; std::vector<int> hawo; std::vector<Gangster> gangspected; for (int i = 0; i < A; i++) { if (spect[i] >= 0) { hawo.push_back(ha[i]); gangspected.push_back(gang[spect[i]]); } } int nworking = hawo.size(); /// set up the LP problem Program lp(CGAL::LARGER, true, 0, true, 24.f); for (ind_t j = 0; j < nworking; j++) { int z = hawo[j]; Gangster gs = gangspected[j]; //_e << z << " " << gs.u << " " << gs.v << " " << gs.w << _l; lp.set_c(j, -gs.u); lp.set_a(j, 0, -z); lp.set_a(j, 1, gs.v); lp.set_a(j, 2, gs.w); } lp.set_b(0, -Z); lp.set_b(1, V); lp.set_b(2, W); // solve the program, using ET as the exact type Solution s = CGAL::solve_linear_program(lp, ET()); assert(s.solves_linear_program(lp)); if (s.is_optimal()) { ET optim = s.objective_value().numerator() / s.objective_value().denominator(); //_e << "optim:" << optim.to_double() << _l; if (optim > -U) _o << "H" << _l; else _o << "L" << _l; } else if (s.is_unbounded()) { _o << "L" << _l; } else if (s.is_infeasible()) { _o << "H" << _l; } }
54,046
26,461
/////////////////////////////////////////////////////////////////////////////// // File: DDTrackerXYZPosAlgo.cc // Description: Position n copies at given x-values, y-values and z-values /////////////////////////////////////////////////////////////////////////////// #include <cmath> #include <algorithm> #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "DetectorDescription/Core/interface/DDCurrentNamespace.h" #include "DetectorDescription/Core/interface/DDSplit.h" #include "Geometry/TrackerCommonData/plugins/DDTrackerXYZPosAlgo.h" #include "CLHEP/Units/GlobalPhysicalConstants.h" #include "CLHEP/Units/GlobalSystemOfUnits.h" DDTrackerXYZPosAlgo::DDTrackerXYZPosAlgo() { LogDebug("TrackerGeom") <<"DDTrackerXYZPosAlgo info: Creating an instance"; } DDTrackerXYZPosAlgo::~DDTrackerXYZPosAlgo() {} void DDTrackerXYZPosAlgo::initialize(const DDNumericArguments & nArgs, const DDVectorArguments & vArgs, const DDMapArguments & , const DDStringArguments & sArgs, const DDStringVectorArguments & vsArgs) { startCopyNo = int(nArgs["StartCopyNo"]); incrCopyNo = int(nArgs["IncrCopyNo"]); xvec = vArgs["XPositions"]; yvec = vArgs["YPositions"]; zvec = vArgs["ZPositions"]; rotMat = vsArgs["Rotations"]; idNameSpace = DDCurrentNamespace::ns(); childName = sArgs["ChildName"]; DDName parentName = parent().name(); LogDebug("TrackerGeom") << "DDTrackerXYZPosAlgo debug: Parent " << parentName << "\tChild " << childName << " NameSpace " << idNameSpace << "\tCopyNo (Start/Increment) " << startCopyNo << ", " << incrCopyNo << "\tNumber " << xvec.size() << ", " << yvec.size() << ", " << zvec.size(); for (int i = 0; i < (int)(zvec.size()); i++) { LogDebug("TrackerGeom") << "\t[" << i << "]\tX = " << xvec[i] << "\t[" << i << "]\tY = " << yvec[i] << "\t[" << i << "]\tZ = " << zvec[i] << ", Rot.Matrix = " << rotMat[i]; } } void DDTrackerXYZPosAlgo::execute(DDCompactView& cpv) { int copy = startCopyNo; DDName mother = parent().name(); DDName child(DDSplit(childName).first, DDSplit(childName).second); for (int i=0; i<(int)(zvec.size()); i++) { DDTranslation tran(xvec[i], yvec[i], zvec[i]); std::string rotstr = DDSplit(rotMat[i]).first; DDRotation rot; if (rotstr != "NULL") { std::string rotns = DDSplit(rotMat[i]).second; rot = DDRotation(DDName(rotstr, rotns)); } cpv.position(child, mother, copy, tran, rot); LogDebug("TrackerGeom") << "DDTrackerXYZPosAlgo test: " << child <<" number " << copy << " positioned in " << mother << " at " << tran << " with " << rot; copy += incrCopyNo; } }
2,772
999
#include <gtest/gtest.h> extern "C" { #include <errno.h> #include <stdint.h> #include <sys/ebpf.h> #include "../test_common.hpp" } namespace { class MapGetNextKeyTest : public CommonFixture { protected: struct ebpf_map *em; virtual void SetUp() { int error; CommonFixture::SetUp(); struct ebpf_map_attr attr; attr.type = EBPF_MAP_TYPE_ARRAY; attr.key_size = sizeof(uint32_t); attr.value_size = sizeof(uint32_t); attr.max_entries = 100; attr.flags = 0; error = ebpf_map_create(ee, &em, &attr); ASSERT_TRUE(!error); } virtual void TearDown() { ebpf_map_destroy(em); CommonFixture::TearDown(); } }; TEST_F(MapGetNextKeyTest, GetNextKeyWithNULLMap) { int error; uint32_t key = 50, next_key = 0; error = ebpf_map_get_next_key_from_user(NULL, &key, &next_key); EXPECT_EQ(EINVAL, error); } TEST_F(MapGetNextKeyTest, GetNextKeyWithNULLKey) { int error; uint32_t key = 50, next_key = 0; error = ebpf_map_get_next_key_from_user(em, NULL, &next_key); EXPECT_NE(EINVAL, error); } TEST_F(MapGetNextKeyTest, GetNextKeyWithNULLNextKey) { int error; uint32_t key = 50; error = ebpf_map_get_next_key_from_user(em, &key, NULL); EXPECT_EQ(EINVAL, error); } } // namespace
1,254
541
// ------------------------------------ // #include "ClientApplication.h" using namespace Leviathan; // ------------------------------------ // DLLEXPORT ClientApplication::ClientApplication() {} DLLEXPORT ClientApplication::ClientApplication(Engine* engine) : LeviathanApplication(engine) {} DLLEXPORT ClientApplication::~ClientApplication() {}
349
84
/*-------------------------------------------------------------------------- + IRduino.cpp 2017 Copyright (c) Longan Labs. All right reserved. Author: Stephen,stephen@longan-labs.cc ------------------- The MIT License (MIT) Copyright (c) 2017 Longan Labs 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 <Arduino.h> #include <IRDuino.h> #include <IRDuinoRecv.h> #define PINIR 6 #define __DBG 0 void IRduino::begin() { num_code= 0; Keyboard.begin(); IR.Init(PINIR); for(int i=A0; i<=A5; i++) { pinMode(i, OUTPUT); digitalWrite(i, HIGH); // all led off } led(B1, 1); led(B2, 1); } // control led void IRduino::led(int pin, int state) { if(pin>A5 || pin<A0)return; // err pin int pin_off = (pin<=A2) ? 0 : 3; for(int i=A0+pin_off; i<=(A2+pin_off); i++) // all led off in one side { digitalWrite(i, HIGH); } digitalWrite(pin, 1-state); } // all led off void IRduino::all_led_off() { for(int i=A0; i<=A5; i++) { digitalWrite(i, HIGH); } } // press a key, then release it void IRduino::keyPressRelease(unsigned char keyNum) { Keyboard.press(keyNum); delay(1); Keyboard.release(keyNum); } /* * enter a string */ void IRduino::printf(char *str) { if(NULL == str)return; while(*str) { keyPressRelease(str[0]); str++; } } /* * find if this ir code was stored, if not return -1 */ int IRduino::find_ir_code(int irCode) { for(int i=0; i<num_code; i++) { if(irCode == ir_code[i]) { return i; } } return -1; } /* * add an task */ bool IRduino::addItem(int irCode, void (*pfun)()) { ir_code[num_code] = irCode; task_fun[num_code++] = pfun; // FIXME: undocumented symantics... asumming returning true means successful add return true; } /* process */ void IRduino::process() { if(!isGetIrDta())return; int irCode = getIrDta(); Serial.println("+------------------------------------------------------+"); if(irCode<=0) { Serial.println("get error code, try again"); } else { Serial.print("get IR Code: 0x"); Serial.println(irCode, HEX); } int task_loca = find_ir_code(irCode); if(task_loca >= 0) // find { Serial.print("task_loca = "); Serial.println(task_loca); led(G1, 1); led(G2, 1); delay(100); led(G1, 0); led(G2, 0); (task_fun[task_loca])(); } else { Serial.println("can't find this ir code"); led(R1, 1); led(R2, 1); delay(100); led(R1, 0); led(R2, 0); } Serial.println("+------------------------------------------------------+\r\n\r\n"); } IRduino iRduino;
4,059
1,436
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #include "Pixel2DLayerCommands.h" #define LOCTEXT_NAMESPACE "FPixel2DLayerModule" void FPixel2DLayerCommands::RegisterCommands() { UI_COMMAND(OpenPluginWindow, "Pixel2DLayers", "Bring up Pixel2D Layers window", EUserInterfaceActionType::Button, FInputGesture()); } #undef LOCTEXT_NAMESPACE
356
134
/* Copyright (C) 2005-2011 Fabio Riccardi */ #include <cstdlib> #include <cstring> #include <ctime> #include <fstream> #include <iostream> using namespace std; int const OldTrialLicenseSize = 1 + sizeof( time_t ); int const TrialLicenseSize = OldTrialLicenseSize + sizeof( short ); long const TrialLicenseDuration = 60*60*24 /* seconds/day */ * 30 /* days */; enum cpu_t { cpu_none, cpu_intel, cpu_powerpc }; cpu_t cpu; char const* me; bool opt_print_start; bool opt_write_expired; /** * Flip a time_t for the right CPU. */ void flip( time_t *t ) { #ifdef __POWERPC__ if ( cpu == cpu_intel ) { #else if ( cpu == cpu_powerpc ) { #endif *t = (*t << 24) & 0xFF000000 | (*t << 8) & 0x00FF0000 | (*t >> 8) & 0x0000FF00 | (*t >> 24) & 0x000000FF ; } } /** * Read an existing trial license file. */ void read_trial( char const *file ) { ifstream in( file, ios::binary ); if ( !in ) { cerr << me << ": could not open " << file << endl; ::exit( 2 ); } char buf[ 64 ]; int const bytes_read = in.readsome( buf, sizeof( buf ) ); in.close(); switch ( bytes_read ) { case OldTrialLicenseSize: case TrialLicenseSize: if ( buf[0] != 'T' ) { cerr << me << ": " << file << " isn't a trial license file (first byte is 0x" << hex << (int)buf[0] << ")\n"; ::exit( 3 ); } break; default: cerr << me << ": " << file << " isn't either " << OldTrialLicenseSize << " or " << TrialLicenseSize << " bytes\n"; ::exit( 4 ); } time_t t; ::memcpy( &t, buf + 1, sizeof( time_t ) ); flip( &t ); if ( !opt_print_start ) t += TrialLicenseDuration; cout << ::ctime( &t ); } /** * Write a new trial license file. */ void write_trial( char const *file ) { ofstream out( file, ios::out | ios::binary ); if ( !out ) { cerr << me << ": could not write to " << file << endl; ::exit( 5 ); } char buf[ TrialLicenseSize ]; buf[0] = 'T'; time_t now; if ( opt_write_expired ) now = 0; else { now = ::time( 0 ); flip( &now ); } ::memcpy( buf + 1, &now, sizeof( time_t ) ); short revision = 0; ::memcpy( buf + 5, &revision, sizeof( short ) ); out.write( buf, sizeof( buf ) ); out.close(); } /** * Print usage message and exit. */ void usage() { cerr << "usage: " << me << "[options] trial_file\n" "------\n" " -e: write an expired license for testing (implies -w)\n" " -i: read/write Intel\n" " -p: read/write PowerPC\n" " -s: print start date instead of expiration\n" " -w: write new file instead of read\n"; ::exit( 1 ); } /** * Main. */ int main( int argc, char *argv[] ) { if ( me = ::strrchr( argv[0], '/' ) ) ++me; else me = argv[0]; bool opt_write_new = false; extern char *optarg; extern int optind, opterr; for ( int c; (c = ::getopt( argc, argv, "eipsw" )) != EOF; ) switch ( c ) { case 'i': cpu = cpu_intel; break; case 'p': cpu = cpu_powerpc; break; case 's': opt_print_start = true; break; case 'e': opt_write_expired = true; cpu = cpu_intel; // doesn't matter for expired // no break; case 'w': opt_write_new = true; break; case '?': usage(); } argc -= optind, argv += optind; if ( argc != 1 ) usage(); if ( cpu == cpu_none ) { cerr << me << ": either -i or -p is required\n"; ::exit( 1 ); } if ( opt_write_new ) write_trial( argv[0] ); else read_trial( argv[0] ); } /* vim:set et sw=4 ts=4: */
4,118
1,464
#include "stdafx.h" #include "ItemRenderingSystem.h" #include "GameObject.h" ItemRenderingSystem::ItemRenderingSystem( GameObject& parent, std::string spritePath, std::unique_ptr<IEffect> deadEffect, std::unique_ptr<IEffect> hitEffect) : parent{ parent } { this->spritePath = spritePath; this->deadEffect = std::move(deadEffect); this->hitEffect = std::move(hitEffect); } ItemRenderingSystem::ItemRenderingSystem( GameObject& parent, TextureRegion textureRegion, std::unique_ptr<IEffect> deadEffect, std::unique_ptr<IEffect> hitEffect) : parent{ parent } { this->sprite = std::make_unique<Sprite>(textureRegion); this->deadEffect = std::move(deadEffect); this->hitEffect = std::move(hitEffect); } Sprite& ItemRenderingSystem::GetSprite() { return *sprite; } GameObject& ItemRenderingSystem::GetParent() { return parent; } void ItemRenderingSystem::LoadContent(ContentManager& content) { RenderingSystem::LoadContent(content); if (sprite != nullptr) return; auto texture = content.Load<Texture>(spritePath); sprite = std::make_unique<Sprite>(texture); } void ItemRenderingSystem::Update(GameTime gameTime) { if (GetParent().GetState() == ObjectState::DYING) { deadEffect->Update(gameTime); if (deadEffect->IsFinished()) GetParent().Destroy(); } if (hitEffect != nullptr) hitEffect->Update(gameTime); } void ItemRenderingSystem::Draw(SpriteExtensions& spriteBatch) { switch (GetParent().GetState()) { case ObjectState::NORMAL: spriteBatch.Draw(*sprite, GetParent().GetPosition()); RenderingSystem::Draw(spriteBatch); break; case ObjectState::DYING: deadEffect->Draw(spriteBatch); break; } if (hitEffect != nullptr) hitEffect->Draw(spriteBatch); } void ItemRenderingSystem::OnStateChanged() { if (GetParent().GetState() == ObjectState::DYING) { if (deadEffect != nullptr) deadEffect->Show(GetParent().GetOriginPosition()); else GetParent().Destroy(); } } void ItemRenderingSystem::OnTakingDamage() { if (hitEffect != nullptr) hitEffect->Show(GetParent().GetOriginPosition()); }
2,062
752
// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gtest/gtest.h> #include "lite/api/paddle_use_kernels.h" #include "lite/api/paddle_use_ops.h" #include "lite/core/test/arena/framework.h" namespace paddle { namespace lite { inline std::vector<int64_t> vector_int2int64_t(std::vector<int> input) { std::vector<int64_t> output{}; for (auto i : input) { output.push_back(static_cast<int64_t>(i)); } return output; } template <typename T> void stride_slice(const T* input, T* out, std::vector<int64_t> in_dims, std::vector<int64_t> out_dims, std::vector<int64_t> starts_indices, std::vector<int64_t> ends_indices, std::vector<int64_t> strides_indices) { size_t in_dims_size = in_dims.size(); std::vector<int> dst_step; std::vector<int> src_step; for (size_t i = 0; i < in_dims_size; ++i) { dst_step.push_back(1); src_step.push_back(1); } int out_num = out_dims[in_dims_size - 1]; for (int i = in_dims_size - 2; i >= 0; i--) { dst_step[i] = out_dims[i + 1] * dst_step[i + 1]; src_step[i] = in_dims[i + 1] * src_step[i + 1]; out_num *= out_dims[i]; } for (int dst_id = 0; dst_id < out_num; dst_id++) { int src_id = 0; int index_id = dst_id; for (size_t j = 0; j < out_dims.size(); j++) { int cur_id = index_id / dst_step[j]; index_id = index_id % dst_step[j]; src_id += (cur_id * strides_indices[j] + starts_indices[j]) * src_step[j]; } out[dst_id] = input[src_id]; } } template <typename T> void reverse(const T* input, T* out, std::vector<int64_t> in_dims, std::vector<bool> reverse_axis) { const T* in_ptr = input; T* out_ptr = out; size_t in_dims_size = in_dims.size(); std::vector<int> src_step; for (size_t i = 0; i < in_dims_size; ++i) { src_step.push_back(1); } for (int i = in_dims_size - 2; i >= 0; i--) { src_step[i] *= in_dims[i + 1] * src_step[i + 1]; } for (size_t i = 0; i < reverse_axis.size(); i++) { if (reverse_axis[i]) { // reverse for (int j = 0; j < in_dims[i]; j++) { int size = 1; if (i + 1 < in_dims_size) { size = src_step[i + 1]; } const T* in_ptr1 = in_ptr + j * size; T* out_ptr1 = out_ptr + (in_dims[i] - 1 - j) * size; memcpy(out_ptr1, in_ptr1, sizeof(T) * size); } } in_ptr += src_step[i]; out_ptr += src_step[i]; } } inline std::vector<int64_t> StridedSliceOutDims( const std::vector<int> starts, const std::vector<int> ends, const std::vector<int> strides, const std::vector<int> axes, const std::vector<int> infer_flags, const std::vector<int64_t> in_dims, const std::vector<int> decrease_axis, const size_t size, bool infer_shape) { std::vector<int64_t> out_dims_vector; for (size_t i = 0; i < in_dims.size(); i++) { out_dims_vector.push_back(in_dims[i]); } int stride_index; int start_index; int end_index; for (size_t i = 0; i < size; i++) { int axes_index = axes[i]; start_index = starts[i]; end_index = ends[i]; stride_index = strides[i]; bool decrease_axis_affect = false; if (start_index == -1 && end_index == 0 && infer_flags[i] == -1) { auto ret = std::find(decrease_axis.begin(), decrease_axis.end(), axes[i]); if (ret != decrease_axis.end()) { decrease_axis_affect = true; } } if (decrease_axis_affect) { out_dims_vector[axes_index] = 1; continue; } if (infer_shape && infer_flags[i] == -1) { out_dims_vector[axes_index] = -1; continue; } CHECK_NE(stride_index, 0) << "stride index in StridedSlice operator is 0."; CHECK_LT(axes_index, in_dims.size()) << "axes_index: " << axes_index << " should be less than in_dims.size(): " << in_dims.size() << "."; int64_t axis_size = in_dims[axes_index]; if (axis_size < 0) { continue; } if (start_index < 0) { start_index = start_index + axis_size; } if (end_index < 0) { if (!(end_index == -1 && stride_index < 0)) { // skip None stop condition end_index = end_index + axis_size; } } if (stride_index < 0) { start_index = start_index + 1; end_index = end_index + 1; } bool zero_dim_condition = ((stride_index < 0 && (start_index <= end_index)) || (stride_index > 0 && (start_index >= end_index))); CHECK_EQ(zero_dim_condition, false) << "The start index and end index are " "invalid for their corresponding " "stride."; auto tmp = std::max(start_index, end_index); int32_t left = std::max(static_cast<int32_t>(0), std::min(start_index, end_index)); int64_t right = std::min(axis_size, static_cast<int64_t>(tmp)); int64_t step = std::abs(static_cast<int64_t>(stride_index)); auto out_dims_index = (std::abs(right - left) + step - 1) / step; out_dims_vector[axes_index] = out_dims_index; } return out_dims_vector; } inline void StridedSliceFunctor(int* starts, int* ends, int* strides, int* axes, int* reverse_axis, std::vector<int64_t> dims, const std::vector<int> infer_flags, const std::vector<int> decrease_axis, const size_t size) { for (size_t axis = 0; axis < size; axis++) { int64_t axis_size = dims[axes[axis]]; int axis_index = axis; if (axis_size < 0) { starts[axis_index] = 0; ends[axis_index] = 1; strides[axis_index] = 1; } bool decrease_axis_affect = false; if (starts[axis_index] == -1 && ends[axis_index] == 0 && infer_flags[axis_index] == -1) { auto ret = std::find( decrease_axis.begin(), decrease_axis.end(), axes[axis_index]); if (ret != decrease_axis.end()) { decrease_axis_affect = true; } } // stride must not be zero if (starts[axis_index] < 0) { starts[axis_index] = starts[axis_index] + axis_size; } if (ends[axis_index] < 0) { if (!(ends[axis_index] == -1 && strides[axis_index] < 0)) { // skip None stop condition ends[axis_index] = ends[axis_index] + axis_size; } } if (decrease_axis_affect) { if (strides[axis_index] < 0) { ends[axis_index] = starts[axis_index] - 1; } else { ends[axis_index] = starts[axis_index] + 1; } } if (strides[axis_index] < 0) { reverse_axis[axis_index] = 1; strides[axis_index] = -strides[axis_index]; if (starts[axis_index] > ends[axis_index]) { // swap the reverse starts[axis_index] = starts[axis_index] + 1; ends[axis_index] = ends[axis_index] + 1; } std::swap(starts[axis_index], ends[axis_index]); } else { reverse_axis[axis_index] = 0; strides[axis_index] = strides[axis_index]; } } } class StridedSliceComputeTester : public arena::TestCase { protected: // common attributes for this op. std::string input_ = "Input"; std::string output_ = "Out"; std::vector<int> axes_; std::vector<int> starts_; std::vector<int> ends_; std::vector<int> strides_; std::vector<int64_t> starts_i64; std::vector<int64_t> ends_i64; std::vector<int> decrease_axis_; DDim dims_; std::vector<int> infer_flags_; std::string starts_tensor_ = "StartsTensor"; std::string ends_tensor_ = "EndsTensor"; bool use_tensor_; bool use_tensor_list_; public: StridedSliceComputeTester(const Place& place, const std::string& alias, const std::vector<int>& axes, const std::vector<int>& starts, const std::vector<int>& ends, const std::vector<int>& strides, const std::vector<int>& decrease_axis, const DDim& dims, bool use_tensor = false, bool use_tensor_list = false, const std::vector<int>& infer_flags = {}) : TestCase(place, alias), axes_(axes), starts_(starts), ends_(ends), strides_(strides), decrease_axis_(decrease_axis), dims_(dims), infer_flags_(infer_flags), use_tensor_(use_tensor), use_tensor_list_(use_tensor_list) { this->starts_i64 = vector_int2int64_t(starts); this->ends_i64 = vector_int2int64_t(ends); } void RunBaseline(Scope* scope) override { auto* out = scope->NewTensor(output_); auto* input = scope->FindTensor(input_); CHECK(out); CHECK(input); const auto* input_data = input->data<float>(); auto in_dims = input->dims(); std::vector<int64_t> out_dims_vector(in_dims.size(), -1); out_dims_vector = StridedSliceOutDims(starts_, ends_, strides_, axes_, infer_flags_, in_dims.data(), decrease_axis_, axes_.size(), true); auto out_dims = DDim(out_dims_vector); out->Resize(out_dims); auto* out_data = out->mutable_data<float>(); std::vector<int> reverse_vector(starts_.size(), 0); StridedSliceFunctor(starts_.data(), ends_.data(), strides_.data(), axes_.data(), reverse_vector.data(), in_dims.data(), infer_flags_, decrease_axis_, starts_.size()); std::vector<int64_t> starts_indices; std::vector<int64_t> ends_indices; std::vector<int64_t> strides_indices; std::vector<bool> reverse_axis; for (size_t axis = 0; axis < in_dims.size(); axis++) { starts_indices.push_back(0); ends_indices.push_back(out_dims[axis]); strides_indices.push_back(1); reverse_axis.push_back(false); } for (size_t axis = 0; axis < axes_.size(); axis++) { int axis_index = axes_[axis]; starts_indices[axis_index] = starts_[axis]; ends_indices[axis_index] = ends_[axis]; strides_indices[axis_index] = strides_[axis]; reverse_axis[axis_index] = (reverse_vector[axis] == 1) ? true : false; } auto out_dims_origin = out_dims; if (decrease_axis_.size() > 0) { std::vector<int64_t> new_out_shape; for (size_t i = 0; i < decrease_axis_.size(); ++i) { out_dims_origin[decrease_axis_[i]] = 0; } for (size_t i = 0; i < out_dims_origin.size(); ++i) { if (out_dims_origin[i] != 0) { new_out_shape.push_back(out_dims_origin[i]); } } if (new_out_shape.size() == 0) { new_out_shape.push_back(1); } out_dims_origin = DDim(new_out_shape); } bool need_reverse = false; for (size_t axis = 0; axis < axes_.size(); axis++) { if (reverse_vector[axis] == 1) { need_reverse = true; break; } } out->Resize(out_dims); if (need_reverse) { Tensor* tmp = new Tensor(); tmp->Resize(out_dims); auto* tmp_t = tmp->mutable_data<float>(); stride_slice(input_data, tmp_t, in_dims.data(), out_dims.data(), starts_indices, ends_indices, strides_indices); reverse(tmp_t, out_data, out_dims.data(), reverse_axis); } else { stride_slice(input_data, out_data, in_dims.data(), out_dims.data(), starts_indices, ends_indices, strides_indices); } if (decrease_axis_.size() > 0) { out->Resize(out_dims_origin); } } void PrepareOpDesc(cpp::OpDesc* op_desc) { op_desc->SetType("strided_slice"); op_desc->SetInput("Input", {input_}); if (use_tensor_) { op_desc->SetInput("StartsTensor", {starts_tensor_}); op_desc->SetInput("EndsTensor", {ends_tensor_}); } else if (use_tensor_list_) { std::vector<std::string> starts_tensor_list_; std::vector<std::string> ends_tensor_list_; for (size_t i = 0; i < starts_.size(); ++i) { starts_tensor_list_.push_back("starts_tensor_list_" + paddle::lite::to_string(i)); ends_tensor_list_.push_back("ends_tensor_list_" + paddle::lite::to_string(i)); } op_desc->SetInput("StartsTensorList", {starts_tensor_list_}); op_desc->SetInput("EndsTensorList", {ends_tensor_list_}); } if (infer_flags_.size() > 0) { op_desc->SetAttr("infer_flags", infer_flags_); } op_desc->SetOutput("Out", {output_}); op_desc->SetAttr("axes", axes_); op_desc->SetAttr("starts", starts_); op_desc->SetAttr("ends", ends_); op_desc->SetAttr("strides", strides_); op_desc->SetAttr("decrease_axis", decrease_axis_); } void PrepareData() override { std::vector<float> data(dims_.production()); for (int i = 0; i < dims_.production(); i++) { data[i] = i; } SetCommonTensor(input_, dims_, data.data()); if (use_tensor_) { SetCommonTensor(starts_tensor_, DDim({static_cast<int64_t>(starts_.size())}), starts_i64.data()); SetCommonTensor(ends_tensor_, DDim({static_cast<int64_t>(ends_.size())}), ends_i64.data()); } else if (use_tensor_list_) { for (size_t i = 0; i < starts_.size(); ++i) { SetCommonTensor("starts_tensor_list_" + paddle::lite::to_string(i), DDim({1}), &starts_i64[i]); } for (size_t i = 0; i < ends_.size(); ++i) { SetCommonTensor("ends_tensor_list_" + paddle::lite::to_string(i), DDim({1}), &ends_i64[i]); } } } }; void test_slice(Place place, float abs_error) { std::vector<int> axes({1, 2}); std::vector<int> starts({2, 2}); std::vector<int> strides({1, 1}); std::vector<int> ends({6, 7}); std::vector<int> infer_flags({1, 1}); std::vector<int> decrease_axis({}); DDim dims({10, 10, 10}); std::unique_ptr<arena::TestCase> tester( new StridedSliceComputeTester(place, "def", axes, starts, ends, strides, decrease_axis, dims, false, false, infer_flags)); arena::Arena arena(std::move(tester), place, 2e-4); arena.TestPrecision(); } void test_slice_axes(Place place, float abs_error) { std::vector<int> axes({1, 2}); std::vector<int> starts({1, 1}); std::vector<int> strides({1, 1}); std::vector<int> ends({2, 3}); std::vector<int> infer_flags({1, 1}); std::vector<int> decrease_axis({}); DDim dims({2, 3, 4, 5}); std::unique_ptr<arena::TestCase> tester( new StridedSliceComputeTester(place, "def", axes, starts, ends, strides, decrease_axis, dims, false, false, infer_flags)); arena::Arena arena(std::move(tester), place, 2e-4); arena.TestPrecision(); } void test_slice_decrease_axis(Place place, float abs_error) { std::vector<int> axes({1}); std::vector<int> starts({0}); std::vector<int> ends({1}); std::vector<int> strides({1}); std::vector<int> decrease_axis({1}); std::vector<int> infer_flags({1}); DDim dims({2, 3, 4, 5}); std::unique_ptr<arena::TestCase> tester( new StridedSliceComputeTester(place, "def", axes, starts, ends, strides, decrease_axis, dims, false, false, infer_flags)); arena::Arena arena(std::move(tester), place, 2e-4); arena.TestPrecision(); } void test_slice_tensor(Place place, float abs_error) { std::vector<int> axes({0, 1, 2}); std::vector<int> starts({2, 2, 2}); std::vector<int> ends({5, 6, 7}); std::vector<int> strides({1, 1, 2}); std::vector<int> infer_flags({1, 1, 1}); std::vector<int> decrease_axis({}); DDim dims({10, 10, 10}); std::unique_ptr<arena::TestCase> tester( new StridedSliceComputeTester(place, "def", axes, starts, ends, strides, decrease_axis, dims, false, false, infer_flags)); arena::Arena arena(std::move(tester), place, 2e-4); arena.TestPrecision(); } void test_slice_tensor_list(Place place, float abs_error) { std::vector<int> axes({0, 1, 2}); std::vector<int> starts({2, 2, 2}); std::vector<int> ends({5, 6, 7}); std::vector<int> strides({1, 1, 2}); std::vector<int> decrease_axis({}); std::vector<int> infer_flags({1, 1, 1}); DDim dims({10, 10, 10}); std::unique_ptr<arena::TestCase> tester( new StridedSliceComputeTester(place, "def", axes, starts, ends, strides, decrease_axis, dims, false, true, infer_flags)); arena::Arena arena(std::move(tester), place, 2e-4); arena.TestPrecision(); } TEST(StrideSlice, precision) { Place place; float abs_error = 1e-5; #if defined(LITE_WITH_NNADAPTER) place = TARGET(kNNAdapter); #if defined(NNADAPTER_WITH_HUAWEI_ASCEND_NPU) abs_error = 1e-2; test_slice(place, abs_error); test_slice_axes(place, abs_error); test_slice_decrease_axis(place, abs_error); return; #elif defined(NNADAPTER_WITH_HUAWEI_KIRIN_NPU) abs_error = 1e-2; test_slice(place, abs_error); test_slice_axes(place, abs_error); test_slice_decrease_axis(place, abs_error); return; #elif defined(NNADAPTER_WITH_NVIDIA_TENSORRT) abs_error = 1e-2; test_slice(place, abs_error); test_slice_axes(place, abs_error); test_slice_decrease_axis(place, abs_error); return; #else return; #endif #elif defined(LITE_WITH_X86) || defined(LITE_WITH_ARM) place = TARGET(kHost); #endif test_slice(place, abs_error); test_slice_axes(place, abs_error); test_slice_decrease_axis(place, abs_error); test_slice_tensor(place, abs_error); test_slice_tensor_list(place, abs_error); } } // namespace lite } // namespace paddle
20,800
7,117
// ply instantiate build-common PLY_BUILD void inst_ply_build_common(TargetInstantiatorArgs* args) { args->addSourceFiles("common/ply-build-common"); args->addIncludeDir(Visibility::Public, "common"); args->addTarget(Visibility::Public, "reflect"); } // ply instantiate build-target PLY_BUILD void inst_ply_build_target(TargetInstantiatorArgs* args) { args->addSourceFiles("target/ply-build-target"); args->addIncludeDir(Visibility::Public, "target"); args->addIncludeDir(Visibility::Private, NativePath::join(args->projInst->env->buildFolderPath, "codegen/ply-build-target")); args->addTarget(Visibility::Public, "build-common"); // Write codegen/ply-build-target/ply-build-target/NativeToolchain.inl // Note: If we ever cross-compile this module, the NativeToolchain will have to be different const CMakeGeneratorOptions* cmakeOptions = args->projInst->env->cmakeOptions; PLY_ASSERT(cmakeOptions); String nativeToolchainFile = String::format( R"(CMakeGeneratorOptions NativeToolchain = {{ "{}", "{}", "{}", "{}", }}; )", cmakeOptions->generator, cmakeOptions->platform, cmakeOptions->toolset, cmakeOptions->buildType); FileSystem::native()->makeDirsAndSaveTextIfDifferent( NativePath::join(args->projInst->env->buildFolderPath, "codegen/ply-build-target/ply-build-target/NativeToolchain.inl"), nativeToolchainFile, TextFormat::platformPreference()); } // ply instantiate build-provider PLY_BUILD void inst_ply_build_provider(TargetInstantiatorArgs* args) { args->addSourceFiles("provider/ply-build-provider"); args->addIncludeDir(Visibility::Public, "provider"); args->addTarget(Visibility::Public, "build-common"); args->addTarget(Visibility::Private, "pylon-reflect"); } // ply instantiate build-repo PLY_BUILD void inst_ply_build_repo(TargetInstantiatorArgs* args) { args->addSourceFiles("repo/ply-build-repo"); args->addIncludeDir(Visibility::Public, "repo"); args->addTarget(Visibility::Public, "build-target"); args->addTarget(Visibility::Public, "build-provider"); args->addTarget(Visibility::Private, "pylon-reflect"); args->addTarget(Visibility::Private, "cpp"); } // ply instantiate build-folder PLY_BUILD void inst_ply_build_folder(TargetInstantiatorArgs* args) { args->addSourceFiles("folder/ply-build-folder"); args->addIncludeDir(Visibility::Public, "folder"); args->addTarget(Visibility::Public, "build-repo"); args->addTarget(Visibility::Private, "pylon-reflect"); }
2,641
772
#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <cstring> #include <string> #include <iomanip> #include <climits> #include <vector> #include <set> #include <queue> #include <map> using namespace std; map <string, string> mp; int main() { ios::sync_with_stdio(false); int serverNum, commandNum; cin >> serverNum >> commandNum; for (int i = 0; i < serverNum; i++) { string name, ip; cin >> name >> ip; mp[ip] = name; } for (int i = 0; i < commandNum; i++) { string command, ip; cin >> command >> ip; ip = ip.substr(0, ip.length() - 1); cout << command << " " << ip << "; #" << mp[ip] << endl; } return 0; }
740
266
/* Copyright (c) 2017, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * * All rights reserved. * * The Astrobee platform is licensed under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ #include <astrobee_gazebo/astrobee_gazebo.h> // Transformation helper code #include <Eigen/Eigen> #include <Eigen/Geometry> // TF2 eigen bindings #include <tf2_eigen/tf2_eigen.h> namespace gazebo { // Model plugin FreeFlyerModelPlugin::FreeFlyerModelPlugin(std::string const& name, bool heartbeats) : ff_util::FreeFlyerNodelet(name, heartbeats), name_(name) {} FreeFlyerModelPlugin::~FreeFlyerModelPlugin() { thread_.join(); } void FreeFlyerModelPlugin::Load(physics::ModelPtr model, sdf::ElementPtr sdf) { gzmsg << "[FF] Loading plugin for model with name " << name_ << "\n"; // Get usefule properties sdf_ = sdf; link_ = model->GetLink(); world_ = model->GetWorld(); model_ = model; // Make sure the ROS node for Gazebo has already been initialized if (!ros::isInitialized()) ROS_FATAL_STREAM("A ROS node for Gazebo has not been initialized"); // Get a nodehandle based on the model name and use a different default queue // We have to do this to avoid gazebo main thread blocking the ROS queue. nh_ = ros::NodeHandle(model_->GetName()); nh_.setCallbackQueue(&queue_); // Start a custom queue thread for messages thread_ = boost::thread( boost::bind(&FreeFlyerModelPlugin::QueueThread, this)); // Call initialize on the freeflyer nodelet to start heartbeat and faults Setup(nh_); // Pass the new callback queue LoadCallback(&nh_, model_, sdf_); } // Get the model link physics::LinkPtr FreeFlyerModelPlugin::GetLink() { return link_; } // Get the model world physics::WorldPtr FreeFlyerModelPlugin::GetWorld() { return world_; } // Get the model physics::ModelPtr FreeFlyerModelPlugin::GetModel() { return model_; } // Get the extrinsics frame std::string FreeFlyerModelPlugin::GetFrame(std::string target) { std::string frame = (target.empty() ? "body" : target); if (GetModel()->GetName() == "/") return frame; return GetModel()->GetName() + "/" + frame; } // Put laser data to the interface void FreeFlyerModelPlugin::QueueThread() { while (nh_.ok()) queue_.callAvailable(ros::WallDuration(0.1)); } // Sensor plugin FreeFlyerSensorPlugin::FreeFlyerSensorPlugin(std::string const& name, bool heartbeats) : ff_util::FreeFlyerNodelet(name, heartbeats), name_(name) {} FreeFlyerSensorPlugin::~FreeFlyerSensorPlugin() { thread_.join(); } void FreeFlyerSensorPlugin::Load(sensors::SensorPtr sensor, sdf::ElementPtr sdf) { gzmsg << "[FF] Loading plugin for sensor with name " << name_ << "\n"; // Get the world in which this sensor exists, and the link it is attached to sensor_ = sensor; sdf_ = sdf; world_ = gazebo::physics::get_world(sensor->WorldName()); model_ = boost::static_pointer_cast < physics::Link > ( world_->GetEntity(sensor->ParentName()))->GetModel(); // If we specify a frame name different to our sensor tag name if (sdf->HasElement("frame")) frame_ = sdf->Get<std::string>("frame"); else frame_ = sensor_->Name(); // If we specify a different sensor type if (sdf->HasElement("rotation_type")) rotation_type_ = sdf->Get<std::string>("rotation_type"); else rotation_type_ = sensor_->Type(); // Make sure the ROS node for Gazebo has already been initialized if (!ros::isInitialized()) ROS_FATAL_STREAM("A ROS node for Gazebo has not been initialized"); // Get a nodehandle based on the model name and use a different default queue // We have to do this to avoid gazebo main thread blocking the ROS queue. nh_ = ros::NodeHandle(model_->GetName()); nh_.setCallbackQueue(&queue_); // Start a custom queue thread for messages thread_ = boost::thread( boost::bind(&FreeFlyerSensorPlugin::QueueThread, this)); // Call initialize on the freeflyer nodelet to start heartbeat and faults Setup(nh_); // Pass the new callback queue LoadCallback(&nh_, sensor_, sdf_); // Defer the extrinsics setup to allow plugins to load timer_ = nh_.createTimer(ros::Duration(1.0), &FreeFlyerSensorPlugin::SetupExtrinsics, this, true, true); } // Get the sensor world physics::WorldPtr FreeFlyerSensorPlugin::GetWorld() { return world_; } // Get the sensor model physics::ModelPtr FreeFlyerSensorPlugin::GetModel() { return model_; } // Get the extrinsics frame std::string FreeFlyerSensorPlugin::GetFrame(std::string target) { std::string frame = (target.empty() ? frame_ : target); if (GetModel()->GetName() == "/") return frame; return GetModel()->GetName() + "/" + frame; } // Get the type of the sensor std::string FreeFlyerSensorPlugin::GetRotationType() { return rotation_type_; } // Put laser data to the interface void FreeFlyerSensorPlugin::QueueThread() { while (nh_.ok()) queue_.callAvailable(ros::WallDuration(0.1)); } // Manage the extrinsics based on the sensor type void FreeFlyerSensorPlugin::SetupExtrinsics(const ros::TimerEvent&) { // Create a buffer and listener for TF2 transforms tf2_ros::Buffer buffer; tf2_ros::TransformListener listener(buffer); // Get extrinsics from framestore try { // Lookup the transform for this sensor geometry_msgs::TransformStamped tf = buffer.lookupTransform( GetFrame("body"), GetFrame(), ros::Time(0), ros::Duration(60.0)); // Handle the transform for all sensor types ignition::math::Pose3d pose( tf.transform.translation.x, tf.transform.translation.y, tf.transform.translation.z, tf.transform.rotation.w, tf.transform.rotation.x, tf.transform.rotation.y, tf.transform.rotation.z); sensor_->SetPose(pose); gzmsg << "Extrinsics set for sensor " << name_ << "\n"; // Get the pose as an Eigen type Eigen::Quaterniond pose_temp = Eigen::Quaterniond(tf.transform.rotation.w, tf.transform.rotation.x, tf.transform.rotation.y, tf.transform.rotation.z); // define the two rotations needed to transform from the flight software camera pose to the // gazebo camera pose Eigen::Quaterniond rot_90_x = Eigen::Quaterniond(0.70710678, 0.70710678, 0, 0); Eigen::Quaterniond rot_90_z = Eigen::Quaterniond(0.70710678, 0, 0, 0.70710678); pose_temp = pose_temp * rot_90_x; pose_temp = pose_temp * rot_90_z; pose = ignition::math::Pose3d( tf.transform.translation.x, tf.transform.translation.y, tf.transform.translation.z, pose_temp.w(), pose_temp.x(), pose_temp.y(), pose_temp.z()); // transform the pose into the world frame and set the camera world pose math::Pose tf_bs = pose; math::Pose tf_wb = model_->GetWorldPose(); math::Pose tf_ws = tf_bs + tf_wb; ignition::math::Pose3d world_pose = ignition::math::Pose3d(tf_ws.pos.x, tf_ws.pos.y, tf_ws.pos.z, tf_ws.rot.w, tf_ws.rot.x, tf_ws.rot.y, tf_ws.rot.z); //////////////////////////// // SPECIAL CASE 1: CAMERA // //////////////////////////// if (sensor_->Type() == "camera") { // Dynamically cast to the correct sensor sensors::CameraSensorPtr sensor = std::dynamic_pointer_cast < sensors::CameraSensor > (sensor_); if (!sensor) gzerr << "Extrinsics requires a camera sensor as a parent.\n"; // set the sensor pose to the pose from tf2 static sensor_->SetPose(pose); sensor->Camera()->SetWorldPose(world_pose); gzmsg << "Extrinsics update for camera " << name_ << "\n"; } ////////////////////////////////////// // SPECIAL CASE 2: WIDEANGLE CAMERA // ////////////////////////////////////// if (sensor_->Type() == "wideanglecamera") { // Dynamically cast to the correct sensor sensors::WideAngleCameraSensorPtr sensor = std::dynamic_pointer_cast < sensors::WideAngleCameraSensor > (sensor_); if (!sensor) gzerr << "Extrinsics requires a wideanglecamera sensor as a parent.\n"; // set the sensor pose to the pose from tf2 static sensor_->SetPose(pose); sensor->Camera()->SetWorldPose(world_pose); gzmsg << "Extrinsics update for wideanglecamera " << name_ << "\n"; } ////////////////////////////////// // SPECIAL CASE 3: DEPTH CAMERA // ////////////////////////////////// if (sensor_->Type() == "depth") { // Dynamically cast to the correct sensor sensors::DepthCameraSensorPtr sensor = std::dynamic_pointer_cast < sensors::DepthCameraSensor > (sensor_); if (!sensor) gzerr << "Extrinsics requires a depth camera sensor as a parent.\n"; sensor->DepthCamera()->SetWorldPose(world_pose); gzmsg << "Extrinsics update for depth camera " << name_ << "\n"; } } catch (tf2::TransformException &ex) { gzmsg << "[FF] No extrinsics for sensor " << name_ << "\n"; } } } // namespace gazebo
9,478
3,125
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'multi_edit.pas' rev: 6.00 #ifndef multi_editHPP #define multi_editHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <CommCtrl.hpp> // Pascal unit #include <ComCtrls.hpp> // Pascal unit #include <ExtCtrls.hpp> // Pascal unit #include <StdCtrls.hpp> // Pascal unit #include <Graphics.hpp> // Pascal unit #include <Menus.hpp> // Pascal unit #include <Forms.hpp> // Pascal unit #include <Controls.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <Windows.hpp> // Pascal unit #include <Messages.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Multi_edit { //-- type declarations ------------------------------------------------------- #pragma option push -b- enum TSpinButtonState { sbNotDown, sbTopDown, sbBottomDown }; #pragma option pop #pragma option push -b- enum TValueType { vtInt, vtFloat, vtHex }; #pragma option pop #pragma option push -b- enum TSpinButtonKind { bkStandard, bkDiagonal, bkLightWave }; #pragma option pop #pragma option push -b- enum TLWButtonState { sbLWNotDown, sbLWDown }; #pragma option pop class DELPHICLASS TMultiObjSpinButton; class PASCALIMPLEMENTATION TMultiObjSpinButton : public Controls::TGraphicControl { typedef Controls::TGraphicControl inherited; private: TSpinButtonState FDown; Graphics::TBitmap* FUpBitmap; Graphics::TBitmap* FDownBitmap; bool FDragging; bool FInvalidate; Graphics::TBitmap* FTopDownBtn; Graphics::TBitmap* FBottomDownBtn; Extctrls::TTimer* FRepeatTimer; Graphics::TBitmap* FNotDownBtn; TSpinButtonState FLastDown; Controls::TWinControl* FFocusControl; Classes::TNotifyEvent FOnTopClick; Classes::TNotifyEvent FOnBottomClick; void __fastcall TopClick(void); void __fastcall BottomClick(void); void __fastcall GlyphChanged(System::TObject* Sender); Graphics::TBitmap* __fastcall GetUpGlyph(void); Graphics::TBitmap* __fastcall GetDownGlyph(void); void __fastcall SetUpGlyph(Graphics::TBitmap* Value); void __fastcall SetDownGlyph(Graphics::TBitmap* Value); void __fastcall SetDown(TSpinButtonState Value); void __fastcall SetFocusControl(Controls::TWinControl* Value); void __fastcall DrawAllBitmap(void); void __fastcall DrawBitmap(Graphics::TBitmap* ABitmap, TSpinButtonState ADownState); void __fastcall TimerExpired(System::TObject* Sender); HIDESBASE MESSAGE void __fastcall CMEnabledChanged(Messages::TMessage &Message); protected: virtual void __fastcall Paint(void); DYNAMIC void __fastcall MouseDown(Controls::TMouseButton Button, Classes::TShiftState Shift, int X, int Y); DYNAMIC void __fastcall MouseMove(Classes::TShiftState Shift, int X, int Y); DYNAMIC void __fastcall MouseUp(Controls::TMouseButton Button, Classes::TShiftState Shift, int X, int Y); virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation); public: __fastcall virtual TMultiObjSpinButton(Classes::TComponent* AOwner); __fastcall virtual ~TMultiObjSpinButton(void); __property TSpinButtonState Down = {read=FDown, write=SetDown, default=0}; __published: __property DragCursor = {default=-12}; __property DragMode = {default=0}; __property Enabled = {default=1}; __property Visible = {default=1}; __property Graphics::TBitmap* DownGlyph = {read=GetDownGlyph, write=SetDownGlyph}; __property Graphics::TBitmap* UpGlyph = {read=GetUpGlyph, write=SetUpGlyph}; __property Controls::TWinControl* FocusControl = {read=FFocusControl, write=SetFocusControl}; __property ShowHint ; __property ParentShowHint = {default=1}; __property Classes::TNotifyEvent OnBottomClick = {read=FOnBottomClick, write=FOnBottomClick}; __property Classes::TNotifyEvent OnTopClick = {read=FOnTopClick, write=FOnTopClick}; __property OnDragDrop ; __property OnDragOver ; __property OnEndDrag ; __property OnStartDrag ; }; typedef void __fastcall (__closure *TLWNotifyEvent)(System::TObject* Sender, int Val); class DELPHICLASS TMultiObjLWButton; class PASCALIMPLEMENTATION TMultiObjLWButton : public Controls::TGraphicControl { typedef Controls::TGraphicControl inherited; private: TLWButtonState FDown; Graphics::TBitmap* FLWBitmap; bool FDragging; bool FInvalidate; Graphics::TBitmap* FLWDownBtn; Graphics::TBitmap* FLWNotDownBtn; Controls::TWinControl* FFocusControl; TLWNotifyEvent FOnLWChange; double FSens; double FAccum; void __fastcall LWChange(System::TObject* Sender, int Val); void __fastcall GlyphChanged(System::TObject* Sender); Graphics::TBitmap* __fastcall GetGlyph(void); void __fastcall SetGlyph(Graphics::TBitmap* Value); void __fastcall SetDown(TLWButtonState Value); void __fastcall SetFocusControl(Controls::TWinControl* Value); void __fastcall DrawAllBitmap(void); void __fastcall DrawBitmap(Graphics::TBitmap* ABitmap, TLWButtonState ADownState); HIDESBASE MESSAGE void __fastcall CMEnabledChanged(Messages::TMessage &Message); protected: virtual void __fastcall Paint(void); DYNAMIC void __fastcall MouseDown(Controls::TMouseButton Button, Classes::TShiftState Shift, int X, int Y); DYNAMIC void __fastcall MouseMove(Classes::TShiftState Shift, int X, int Y); DYNAMIC void __fastcall MouseUp(Controls::TMouseButton Button, Classes::TShiftState Shift, int X, int Y); virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation); void __fastcall SetSens(double Value); public: __fastcall virtual TMultiObjLWButton(Classes::TComponent* AOwner); __fastcall virtual ~TMultiObjLWButton(void); __property TLWButtonState Down = {read=FDown, write=SetDown, default=0}; virtual void __fastcall Invalidate(void); __published: __property double LWSensitivity = {read=FSens, write=SetSens}; __property DragCursor = {default=-12}; __property DragMode = {default=0}; __property Enabled = {default=1}; __property Visible = {default=1}; __property Graphics::TBitmap* LWGlyph = {read=GetGlyph, write=SetGlyph}; __property Controls::TWinControl* FocusControl = {read=FFocusControl, write=SetFocusControl}; __property TLWNotifyEvent OnLWChange = {read=FOnLWChange, write=FOnLWChange}; __property ShowHint ; __property ParentShowHint = {default=1}; __property OnDragDrop ; __property OnDragOver ; __property OnEndDrag ; __property OnStartDrag ; }; class DELPHICLASS TMultiObjSpinEdit; class PASCALIMPLEMENTATION TMultiObjSpinEdit : public Stdctrls::TCustomEdit { typedef Stdctrls::TCustomEdit inherited; private: bool bIsMulti; bool bChanged; Extended BeforeValue; Graphics::TColor StartColor; Graphics::TColor FBtnColor; Classes::TAlignment FAlignment; Extended FMinValue; Extended FMaxValue; Extended FIncrement; int FButtonWidth; Byte FDecimal; bool FChanging; bool FEditorEnabled; TValueType FValueType; TMultiObjSpinButton* FButton; Controls::TWinControl* FBtnWindow; bool FArrowKeys; Classes::TNotifyEvent FOnTopClick; Classes::TNotifyEvent FOnBottomClick; TSpinButtonKind FButtonKind; Comctrls::TCustomUpDown* FUpDown; TMultiObjLWButton* FLWButton; TLWNotifyEvent FOnLWChange; double FSens; TSpinButtonKind __fastcall GetButtonKind(void); void __fastcall SetButtonKind(TSpinButtonKind Value); void __fastcall UpDownClick(System::TObject* Sender, Comctrls::TUDBtnType Button); void __fastcall LWChange(System::TObject* Sender, int Val); Extended __fastcall GetValue(void); Extended __fastcall CheckValue(Extended NewValue); int __fastcall GetAsInteger(void); bool __fastcall IsIncrementStored(void); bool __fastcall IsMaxStored(void); bool __fastcall IsMinStored(void); bool __fastcall IsValueStored(void); void __fastcall SetArrowKeys(bool Value); void __fastcall SetAsInteger(int NewValue); void __fastcall SetValue(Extended NewValue); void __fastcall SetValueType(TValueType NewType); void __fastcall SetButtonWidth(int NewValue); void __fastcall SetDecimal(Byte NewValue); int __fastcall GetButtonWidth(void); void __fastcall RecreateButton(void); void __fastcall ResizeButton(void); void __fastcall SetEditRect(void); void __fastcall SetAlignment(Classes::TAlignment Value); HIDESBASE MESSAGE void __fastcall WMSize(Messages::TWMSize &Message); HIDESBASE MESSAGE void __fastcall CMEnter(Messages::TMessage &Message); HIDESBASE MESSAGE void __fastcall CMExit(Messages::TWMNoParams &Message); MESSAGE void __fastcall WMPaste(Messages::TWMNoParams &Message); MESSAGE void __fastcall WMCut(Messages::TWMNoParams &Message); HIDESBASE MESSAGE void __fastcall CMCtl3DChanged(Messages::TMessage &Message); HIDESBASE MESSAGE void __fastcall CMEnabledChanged(Messages::TMessage &Message); HIDESBASE MESSAGE void __fastcall CMFontChanged(Messages::TMessage &Message); void __fastcall SetBtnColor(Graphics::TColor Value); protected: DYNAMIC void __fastcall Change(void); virtual bool __fastcall IsValidChar(char Key); virtual void __fastcall UpClick(System::TObject* Sender); virtual void __fastcall DownClick(System::TObject* Sender); DYNAMIC void __fastcall KeyDown(Word &Key, Classes::TShiftState Shift); DYNAMIC void __fastcall KeyPress(char &Key); virtual void __fastcall CreateParams(Controls::TCreateParams &Params); virtual void __fastcall CreateWnd(void); void __fastcall SetSens(double Val); double __fastcall GetSens(void); public: __fastcall virtual TMultiObjSpinEdit(Classes::TComponent* AOwner); __fastcall virtual ~TMultiObjSpinEdit(void); __property int AsInteger = {read=GetAsInteger, write=SetAsInteger, default=0}; __property Text ; void __fastcall ObjFirstInit(float v); void __fastcall ObjNextInit(float v); void __fastcall ObjApplyFloat(float &_to); void __fastcall ObjApplyInt(int &_to); __published: __property double LWSensitivity = {read=GetSens, write=SetSens}; __property Classes::TAlignment Alignment = {read=FAlignment, write=SetAlignment, default=0}; __property bool ArrowKeys = {read=FArrowKeys, write=SetArrowKeys, default=1}; __property Graphics::TColor BtnColor = {read=FBtnColor, write=SetBtnColor, default=-2147483633}; __property TSpinButtonKind ButtonKind = {read=FButtonKind, write=SetButtonKind, default=0}; __property Byte Decimal = {read=FDecimal, write=SetDecimal, default=2}; __property int ButtonWidth = {read=FButtonWidth, write=SetButtonWidth, default=14}; __property bool EditorEnabled = {read=FEditorEnabled, write=FEditorEnabled, default=1}; __property Extended Increment = {read=FIncrement, write=FIncrement, stored=IsIncrementStored}; __property Extended MaxValue = {read=FMaxValue, write=FMaxValue, stored=IsMaxStored}; __property Extended MinValue = {read=FMinValue, write=FMinValue, stored=IsMinStored}; __property TValueType ValueType = {read=FValueType, write=SetValueType, default=0}; __property Extended Value = {read=GetValue, write=SetValue, stored=IsValueStored}; __property AutoSelect = {default=1}; __property AutoSize = {default=1}; __property BorderStyle = {default=1}; __property Color = {default=-2147483643}; __property Ctl3D ; __property DragCursor = {default=-12}; __property DragMode = {default=0}; __property Enabled = {default=1}; __property Font ; __property Anchors = {default=3}; __property BiDiMode ; __property Constraints ; __property DragKind = {default=0}; __property ParentBiDiMode = {default=1}; __property ImeMode = {default=3}; __property ImeName ; __property MaxLength = {default=0}; __property ParentColor = {default=0}; __property ParentCtl3D = {default=1}; __property ParentFont = {default=1}; __property ParentShowHint = {default=1}; __property PopupMenu ; __property ReadOnly = {default=0}; __property ShowHint ; __property TabOrder = {default=-1}; __property TabStop = {default=1}; __property Visible = {default=1}; __property TLWNotifyEvent OnLWChange = {read=FOnLWChange, write=FOnLWChange}; __property Classes::TNotifyEvent OnBottomClick = {read=FOnBottomClick, write=FOnBottomClick}; __property Classes::TNotifyEvent OnTopClick = {read=FOnTopClick, write=FOnTopClick}; __property OnChange ; __property OnClick ; __property OnDblClick ; __property OnDragDrop ; __property OnDragOver ; __property OnEndDrag ; __property OnEnter ; __property OnExit ; __property OnKeyDown ; __property OnKeyPress ; __property OnKeyUp ; __property OnMouseDown ; __property OnMouseMove ; __property OnMouseUp ; __property OnStartDrag ; __property OnContextPopup ; __property OnMouseWheelDown ; __property OnMouseWheelUp ; __property OnEndDock ; __property OnStartDock ; public: #pragma option push -w-inl /* TWinControl.CreateParented */ inline __fastcall TMultiObjSpinEdit(HWND ParentWindow) : Stdctrls::TCustomEdit(ParentWindow) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- } /* namespace Multi_edit */ using namespace Multi_edit; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // multi_edit
13,233
4,418
//#include "../assert/assert.hpp" #include "../assert/assert.hpp" #include "window.hpp" #include "window_taborder.hpp" namespace shoujin::gui { void WindowTabOrder::AddWindow(Window* window, int& out_taborder) { SHOUJIN_ASSERT(window); if(window->tabstop()) { _taborder_map.emplace(++_taborder_max, window); out_taborder = _taborder_max; } else out_taborder = 0; } void WindowTabOrder::CycleTab(bool cycle_up) { HWND focus_hwnd = GetFocus(); if(!focus_hwnd) { SetFocusToFirstWindow(); return; } auto window = Window::FindWindowByHandle(focus_hwnd); if(!window) { SetFocusToFirstWindow(); return; } window = FindNextWindowInTabOrder(window, cycle_up); if(window) window->SetFocus(); } Window* WindowTabOrder::FindNextWindowInTabOrder(Window* window, bool cycle_up) const { if(_taborder_map.size() == 1) return window; auto current = _taborder_map.find(window->taborder()); if(current == _taborder_map.end()) return nullptr; if(cycle_up) { if(current == _taborder_map.begin()) return _taborder_map.rbegin()->second; return std::prev(current)->second; } auto next = std::next(current); if(next == _taborder_map.end()) return _taborder_map.begin()->second; return next->second; } void WindowTabOrder::SetFocusToFirstWindow() { const auto it = _taborder_map.cbegin(); if(it != _taborder_map.cend()) it->second->SetFocus(); } }
1,389
541
/* Title - Recusive Sum Description- A Program to recursively calculate sum of N natural numbers. */ #include<bits/stdc++.h> using namespace std; // A recursive function to calculate the sum of N natural numbers int recursiveSum(int num) { if(num == 0) return 0; return (recursiveSum(num - 1) + num); } int main() { int num; cout<<"\n Enter a number N to find sum of first N natural numbers: "; cin>>num; cout<<"\n Sum of first "<<num<<" natural numbers is = "<<recursiveSum(num); return 0; } /* Time complexity - O(n) Sample Input - 5 Sample Output - 15 */
608
207
/* SPDX-License-Identifier: MIT */ /** @file ntv2capture8k.cpp @brief Implementation of NTV2Capture class. @copyright (C) 2012-2021 AJA Video Systems, Inc. All rights reserved. **/ #include "ntv2capture8k.h" #include "ntv2utils.h" #include "ntv2devicefeatures.h" #include "ajabase/system/process.h" #include "ajabase/system/systemtime.h" #include "ajabase/system/memory.h" using namespace std; /** @brief The alignment of the video and audio buffers has a big impact on the efficiency of DMA transfers. When aligned to the page size of the architecture, only one DMA descriptor is needed per page. Misalignment will double the number of descriptors that need to be fetched and processed, thus reducing bandwidth. **/ static const uint32_t BUFFER_ALIGNMENT (4096); // The correct size for many systems NTV2Capture8K::NTV2Capture8K (const string inDeviceSpecifier, const bool withAudio, const NTV2Channel channel, const NTV2FrameBufferFormat pixelFormat, const bool inLevelConversion, const bool inDoMultiFormat, const bool inWithAnc, const bool inDoTsiRouting) : mConsumerThread (AJAThread()), mProducerThread (AJAThread()), mDeviceID (DEVICE_ID_NOTFOUND), mDeviceSpecifier (inDeviceSpecifier), mWithAudio (withAudio), mInputChannel (channel), mInputSource (::NTV2ChannelToInputSource (mInputChannel)), mVideoFormat (NTV2_FORMAT_UNKNOWN), mPixelFormat (pixelFormat), mSavedTaskMode (NTV2_DISABLE_TASKS), mAudioSystem (NTV2_AUDIOSYSTEM_1), mDoLevelConversion (inLevelConversion), mDoMultiFormat (inDoMultiFormat), mGlobalQuit (false), mWithAnc (inWithAnc), mVideoBufferSize (0), mAudioBufferSize (0), mDoTsiRouting (inDoTsiRouting) { ::memset (mAVHostBuffer, 0x0, sizeof (mAVHostBuffer)); } // constructor NTV2Capture8K::~NTV2Capture8K () { // Stop my capture and consumer threads, then destroy them... Quit (); // Unsubscribe from input vertical event... mDevice.UnsubscribeInputVerticalEvent (mInputChannel); // Unsubscribe from output vertical mDevice.UnsubscribeOutputVerticalEvent(NTV2_CHANNEL1); // Free all my buffers... for (unsigned bufferNdx = 0; bufferNdx < CIRCULAR_BUFFER_SIZE; bufferNdx++) { if (mAVHostBuffer[bufferNdx].fVideoBuffer) { delete mAVHostBuffer[bufferNdx].fVideoBuffer; mAVHostBuffer[bufferNdx].fVideoBuffer = AJA_NULL; } if (mAVHostBuffer[bufferNdx].fAudioBuffer) { delete mAVHostBuffer[bufferNdx].fAudioBuffer; mAVHostBuffer[bufferNdx].fAudioBuffer = AJA_NULL; } if (mAVHostBuffer[bufferNdx].fAncBuffer) { delete mAVHostBuffer[bufferNdx].fAncBuffer; mAVHostBuffer[bufferNdx].fAncBuffer = AJA_NULL; } } // for each buffer in the ring if (!mDoMultiFormat) { mDevice.ReleaseStreamForApplication(kDemoAppSignature, static_cast<int32_t>(AJAProcess::GetPid())); mDevice.SetEveryFrameServices(mSavedTaskMode); // Restore prior task mode } } // destructor void NTV2Capture8K::Quit (void) { // Set the global 'quit' flag, and wait for the threads to go inactive... mGlobalQuit = true; while (mConsumerThread.Active()) AJATime::Sleep(10); while (mProducerThread.Active()) AJATime::Sleep(10); mDevice.DMABufferUnlockAll(); } // Quit AJAStatus NTV2Capture8K::Init (void) { AJAStatus status (AJA_STATUS_SUCCESS); // Open the device... if (!CNTV2DeviceScanner::GetFirstDeviceFromArgument (mDeviceSpecifier, mDevice)) {cerr << "## ERROR: Device '" << mDeviceSpecifier << "' not found" << endl; return AJA_STATUS_OPEN;} if (!mDevice.IsDeviceReady ()) {cerr << "## ERROR: Device '" << mDeviceSpecifier << "' not ready" << endl; return AJA_STATUS_INITIALIZE;} if (!mDoMultiFormat) { if (!mDevice.AcquireStreamForApplication (kDemoAppSignature, static_cast<int32_t>(AJAProcess::GetPid()))) return AJA_STATUS_BUSY; // Another app is using the device mDevice.GetEveryFrameServices (mSavedTaskMode); // Save the current state before we change it } mDevice.SetEveryFrameServices (NTV2_OEM_TASKS); // Since this is an OEM demo, use the OEM service level mDeviceID = mDevice.GetDeviceID (); // Keep the device ID handy, as it's used frequently // Sometimes other applications disable some or all of the frame buffers, so turn them all on here... mDevice.EnableChannel(NTV2_CHANNEL4); mDevice.EnableChannel(NTV2_CHANNEL3); mDevice.EnableChannel(NTV2_CHANNEL2); mDevice.EnableChannel(NTV2_CHANNEL1); if (::NTV2DeviceCanDoMultiFormat (mDeviceID)) { mDevice.SetMultiFormatMode (mDoMultiFormat); } else { mDoMultiFormat = false; } // Set up the video and audio... status = SetupVideo (); if (AJA_FAILURE (status)) return status; status = SetupAudio (); if (AJA_FAILURE (status)) return status; // Set up the circular buffers, the device signal routing, and both playout and capture AutoCirculate... SetupHostBuffers (); RouteInputSignal (); SetupInputAutoCirculate (); return AJA_STATUS_SUCCESS; } // Init AJAStatus NTV2Capture8K::SetupVideo (void) { // Enable and subscribe to the interrupts for the channel to be used... mDevice.EnableInputInterrupt(mInputChannel); mDevice.SubscribeInputVerticalEvent(mInputChannel); // The input vertical is not always available so we like to use the output for timing - sometimes mDevice.SubscribeOutputVerticalEvent(mInputChannel); // disable SDI transmitter mDevice.SetSDITransmitEnable(mInputChannel, false); // Wait for four verticals to let the reciever lock... mDevice.WaitForOutputVerticalInterrupt(mInputChannel, 10); // Set the video format to match the incomming video format. // Does the device support the desired input source? // Determine the input video signal format... mVideoFormat = mDevice.GetInputVideoFormat (mInputSource); if (mVideoFormat == NTV2_FORMAT_UNKNOWN) { cerr << "## ERROR: No input signal or unknown format" << endl; return AJA_STATUS_NOINPUT; // Sorry, can't handle this format } // Convert the signal wire format to a 8k format CNTV2DemoCommon::Get8KInputFormat(mVideoFormat); mDevice.SetVideoFormat(mVideoFormat, false, false, mInputChannel); mDevice.SetQuadQuadFrameEnable(true, mInputChannel); mDevice.SetQuadQuadSquaresEnable(!mDoTsiRouting, mInputChannel); // Set the device video format to whatever we detected at the input... // The user has an option here. If doing multi-format, we are, lock to the board. // If the user wants to E-E the signal then lock to input. mDevice.SetReference(NTV2_REFERENCE_FREERUN); // Set the frame buffer pixel format for all the channels on the device // (assuming it supports that pixel format -- otherwise default to 8-bit YCbCr)... if (!::NTV2DeviceCanDoFrameBufferFormat (mDeviceID, mPixelFormat)) mPixelFormat = NTV2_FBF_8BIT_YCBCR; // ...and set all buffers pixel format... if (mDoTsiRouting) { if (mInputChannel < NTV2_CHANNEL3) { mDevice.SetFrameBufferFormat(NTV2_CHANNEL1, mPixelFormat); mDevice.SetFrameBufferFormat(NTV2_CHANNEL2, mPixelFormat); mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL1); mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL2); mDevice.EnableChannel(NTV2_CHANNEL1); mDevice.EnableChannel(NTV2_CHANNEL2); if (!mDoMultiFormat) { mDevice.DisableChannel(NTV2_CHANNEL3); mDevice.DisableChannel(NTV2_CHANNEL4); } } else { mDevice.SetFrameBufferFormat(NTV2_CHANNEL3, mPixelFormat); mDevice.SetFrameBufferFormat(NTV2_CHANNEL4, mPixelFormat); mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL3); mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL4); mDevice.EnableChannel(NTV2_CHANNEL3); mDevice.EnableChannel(NTV2_CHANNEL4); if (!mDoMultiFormat) { mDevice.DisableChannel(NTV2_CHANNEL1); mDevice.DisableChannel(NTV2_CHANNEL2); } } } else { mDevice.SetFrameBufferFormat(NTV2_CHANNEL1, mPixelFormat); mDevice.SetFrameBufferFormat(NTV2_CHANNEL2, mPixelFormat); mDevice.SetFrameBufferFormat(NTV2_CHANNEL3, mPixelFormat); mDevice.SetFrameBufferFormat(NTV2_CHANNEL4, mPixelFormat); mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL1); mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL2); mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL3); mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL4); mDevice.EnableChannel(NTV2_CHANNEL1); mDevice.EnableChannel(NTV2_CHANNEL2); mDevice.EnableChannel(NTV2_CHANNEL3); mDevice.EnableChannel(NTV2_CHANNEL4); } return AJA_STATUS_SUCCESS; } // SetupVideo AJAStatus NTV2Capture8K::SetupAudio (void) { // In multiformat mode, base the audio system on the channel... if (mDoMultiFormat && ::NTV2DeviceGetNumAudioSystems (mDeviceID) > 1 && UWord (mInputChannel) < ::NTV2DeviceGetNumAudioSystems (mDeviceID)) mAudioSystem = ::NTV2ChannelToAudioSystem (mInputChannel); // Have the audio system capture audio from the designated device input (i.e., ch1 uses SDIIn1, ch2 uses SDIIn2, etc.)... mDevice.SetAudioSystemInputSource (mAudioSystem, NTV2_AUDIO_EMBEDDED, ::NTV2InputSourceToEmbeddedAudioInput (mInputSource)); mDevice.SetNumberAudioChannels (::NTV2DeviceGetMaxAudioChannels (mDeviceID), mAudioSystem); mDevice.SetAudioRate (NTV2_AUDIO_48K, mAudioSystem); // The on-device audio buffer should be 4MB to work best across all devices & platforms... mDevice.SetAudioBufferSize (NTV2_AUDIO_BUFFER_BIG, mAudioSystem); mDevice.SetAudioLoopBack(NTV2_AUDIO_LOOPBACK_OFF, mAudioSystem); return AJA_STATUS_SUCCESS; } // SetupAudio void NTV2Capture8K::SetupHostBuffers (void) { // Let my circular buffer know when it's time to quit... mAVCircularBuffer.SetAbortFlag (&mGlobalQuit); mVideoBufferSize = ::GetVideoWriteSize (mVideoFormat, mPixelFormat); printf("video size = %d\n", mVideoBufferSize); mAudioBufferSize = NTV2_AUDIOSIZE_MAX; mAncBufferSize = NTV2_ANCSIZE_MAX; // Allocate and add each in-host AVDataBuffer to my circular buffer member variable... for (unsigned bufferNdx = 0; bufferNdx < CIRCULAR_BUFFER_SIZE; bufferNdx++ ) { mAVHostBuffer [bufferNdx].fVideoBuffer = reinterpret_cast <uint32_t *> (AJAMemory::AllocateAligned (mVideoBufferSize, BUFFER_ALIGNMENT)); mAVHostBuffer [bufferNdx].fVideoBufferSize = mVideoBufferSize; mAVHostBuffer [bufferNdx].fAudioBuffer = mWithAudio ? reinterpret_cast <uint32_t *> (AJAMemory::AllocateAligned (mAudioBufferSize, BUFFER_ALIGNMENT)) : 0; mAVHostBuffer [bufferNdx].fAudioBufferSize = mWithAudio ? mAudioBufferSize : 0; mAVHostBuffer [bufferNdx].fAncBuffer = mWithAnc ? reinterpret_cast <uint32_t *> (AJAMemory::AllocateAligned (mAncBufferSize, BUFFER_ALIGNMENT)) : 0; mAVHostBuffer [bufferNdx].fAncBufferSize = mAncBufferSize; mAVCircularBuffer.Add (& mAVHostBuffer [bufferNdx]); // Page lock the memory if (mAVHostBuffer [bufferNdx].fVideoBuffer != AJA_NULL) mDevice.DMABufferLock((ULWord*)mAVHostBuffer [bufferNdx].fVideoBuffer, mVideoBufferSize, true); if (mAVHostBuffer [bufferNdx].fAudioBuffer) mDevice.DMABufferLock((ULWord*)mAVHostBuffer [bufferNdx].fAudioBuffer, mAudioBufferSize, true); if (mAVHostBuffer [bufferNdx].fAncBuffer) mDevice.DMABufferLock((ULWord*)mAVHostBuffer [bufferNdx].fAncBuffer, mAncBufferSize, true); } // for each AVDataBuffer } // SetupHostBuffers void NTV2Capture8K::RouteInputSignal(void) { if (mDoTsiRouting) { if (::IsRGBFormat (mPixelFormat)) { if (mInputChannel < NTV2_CHANNEL3) { mDevice.Connect(NTV2_XptDualLinkIn1Input, NTV2_XptSDIIn1); mDevice.Connect(NTV2_XptDualLinkIn1DSInput, NTV2_XptSDIIn1DS2); mDevice.Connect(NTV2_XptDualLinkIn2Input, NTV2_XptSDIIn2); mDevice.Connect(NTV2_XptDualLinkIn2DSInput, NTV2_XptSDIIn2DS2); mDevice.Connect(NTV2_XptDualLinkIn3Input, NTV2_XptSDIIn3); mDevice.Connect(NTV2_XptDualLinkIn3DSInput, NTV2_XptSDIIn3DS2); mDevice.Connect(NTV2_XptDualLinkIn4Input, NTV2_XptSDIIn4); mDevice.Connect(NTV2_XptDualLinkIn4DSInput, NTV2_XptSDIIn4DS2); mDevice.Connect(NTV2_XptFrameBuffer1Input, NTV2_XptDuallinkIn1); mDevice.Connect(NTV2_XptFrameBuffer1DS2Input, NTV2_XptDuallinkIn2); mDevice.Connect(NTV2_XptFrameBuffer2Input, NTV2_XptDuallinkIn3); mDevice.Connect(NTV2_XptFrameBuffer2DS2Input, NTV2_XptDuallinkIn4); mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false); } else { mDevice.Connect(NTV2_XptDualLinkIn1Input, NTV2_XptSDIIn1); mDevice.Connect(NTV2_XptDualLinkIn1DSInput, NTV2_XptSDIIn1DS2); mDevice.Connect(NTV2_XptDualLinkIn2Input, NTV2_XptSDIIn2); mDevice.Connect(NTV2_XptDualLinkIn2DSInput, NTV2_XptSDIIn2DS2); mDevice.Connect(NTV2_XptDualLinkIn3Input, NTV2_XptSDIIn3); mDevice.Connect(NTV2_XptDualLinkIn3DSInput, NTV2_XptSDIIn3DS2); mDevice.Connect(NTV2_XptDualLinkIn4Input, NTV2_XptSDIIn4); mDevice.Connect(NTV2_XptDualLinkIn4DSInput, NTV2_XptSDIIn4DS2); mDevice.Connect(NTV2_XptFrameBuffer3Input, NTV2_XptDuallinkIn1); mDevice.Connect(NTV2_XptFrameBuffer3DS2Input, NTV2_XptDuallinkIn2); mDevice.Connect(NTV2_XptFrameBuffer4Input, NTV2_XptDuallinkIn3); mDevice.Connect(NTV2_XptFrameBuffer4DS2Input, NTV2_XptDuallinkIn4); mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false); } } else { if (mInputChannel < NTV2_CHANNEL3) { if (NTV2_IS_QUAD_QUAD_HFR_VIDEO_FORMAT(mVideoFormat)) { mDevice.Connect(NTV2_XptFrameBuffer1Input, NTV2_XptSDIIn1); mDevice.Connect(NTV2_XptFrameBuffer1DS2Input, NTV2_XptSDIIn2); mDevice.Connect(NTV2_XptFrameBuffer2Input, NTV2_XptSDIIn3); mDevice.Connect(NTV2_XptFrameBuffer2DS2Input, NTV2_XptSDIIn4); mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false); } else { mDevice.Connect(NTV2_XptFrameBuffer1Input, NTV2_XptSDIIn1); mDevice.Connect(NTV2_XptFrameBuffer1DS2Input, NTV2_XptSDIIn1DS2); mDevice.Connect(NTV2_XptFrameBuffer2Input, NTV2_XptSDIIn2); mDevice.Connect(NTV2_XptFrameBuffer2DS2Input, NTV2_XptSDIIn2DS2); mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false); } } else { if (NTV2_IS_QUAD_QUAD_HFR_VIDEO_FORMAT(mVideoFormat)) { mDevice.Connect(NTV2_XptFrameBuffer3Input, NTV2_XptSDIIn1); mDevice.Connect(NTV2_XptFrameBuffer3DS2Input, NTV2_XptSDIIn2); mDevice.Connect(NTV2_XptFrameBuffer4Input, NTV2_XptSDIIn3); mDevice.Connect(NTV2_XptFrameBuffer4DS2Input, NTV2_XptSDIIn4); mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false); } else { mDevice.Connect(NTV2_XptFrameBuffer3Input, NTV2_XptSDIIn3); mDevice.Connect(NTV2_XptFrameBuffer3DS2Input, NTV2_XptSDIIn3DS2); mDevice.Connect(NTV2_XptFrameBuffer4Input, NTV2_XptSDIIn4); mDevice.Connect(NTV2_XptFrameBuffer4DS2Input, NTV2_XptSDIIn4DS2); mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false); } } } } else { if (::IsRGBFormat (mPixelFormat)) { mDevice.Connect(NTV2_XptDualLinkIn1Input, NTV2_XptSDIIn1); mDevice.Connect(NTV2_XptDualLinkIn1DSInput, NTV2_XptSDIIn1DS2); mDevice.Connect(NTV2_XptDualLinkIn2Input, NTV2_XptSDIIn2); mDevice.Connect(NTV2_XptDualLinkIn2DSInput, NTV2_XptSDIIn2DS2); mDevice.Connect(NTV2_XptDualLinkIn3Input, NTV2_XptSDIIn3); mDevice.Connect(NTV2_XptDualLinkIn3DSInput, NTV2_XptSDIIn3DS2); mDevice.Connect(NTV2_XptDualLinkIn4Input, NTV2_XptSDIIn4); mDevice.Connect(NTV2_XptDualLinkIn4DSInput, NTV2_XptSDIIn4DS2); mDevice.Connect(NTV2_XptFrameBuffer1Input, NTV2_XptDuallinkIn1); mDevice.Connect(NTV2_XptFrameBuffer2Input, NTV2_XptDuallinkIn2); mDevice.Connect(NTV2_XptFrameBuffer3Input, NTV2_XptDuallinkIn3); mDevice.Connect(NTV2_XptFrameBuffer4Input, NTV2_XptDuallinkIn4); mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false); } else { mDevice.Connect(NTV2_XptFrameBuffer1Input, NTV2_XptSDIIn1); mDevice.Connect(NTV2_XptFrameBuffer2Input, NTV2_XptSDIIn2); mDevice.Connect(NTV2_XptFrameBuffer3Input, NTV2_XptSDIIn3); mDevice.Connect(NTV2_XptFrameBuffer4Input, NTV2_XptSDIIn4); mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false); } } } // RouteInputSignal void NTV2Capture8K::SetupInputAutoCirculate (void) { // Tell capture AutoCirculate to use 7 frame buffers on the device... ULWord startFrame = 0, endFrame = 7; mDevice.AutoCirculateStop(NTV2_CHANNEL1); mDevice.AutoCirculateStop(NTV2_CHANNEL2); mDevice.AutoCirculateStop(NTV2_CHANNEL3); mDevice.AutoCirculateStop(NTV2_CHANNEL4); mDevice.AutoCirculateInitForInput (mInputChannel, 0, // 0 frames == explicitly set start & end frames mWithAudio ? mAudioSystem : NTV2_AUDIOSYSTEM_INVALID, // Which audio system (if any)? AUTOCIRCULATE_WITH_RP188 | AUTOCIRCULATE_WITH_ANC, // Include timecode & custom Anc 1, startFrame, endFrame); } // SetupInputAutoCirculate AJAStatus NTV2Capture8K::Run () { // Start the playout and capture threads... StartConsumerThread (); StartProducerThread (); return AJA_STATUS_SUCCESS; } // Run ////////////////////////////////////////////// // This is where we will start the consumer thread void NTV2Capture8K::StartConsumerThread (void) { // Create and start the consumer thread... mConsumerThread.Attach(ConsumerThreadStatic, this); mConsumerThread.SetPriority(AJA_ThreadPriority_High); mConsumerThread.Start(); } // StartConsumerThread // The consumer thread function void NTV2Capture8K::ConsumerThreadStatic (AJAThread * pThread, void * pContext) // static { (void) pThread; // Grab the NTV2Capture instance pointer from the pContext parameter, // then call its ConsumeFrames method... NTV2Capture8K * pApp (reinterpret_cast <NTV2Capture8K *> (pContext)); pApp->ConsumeFrames (); } // ConsumerThreadStatic void NTV2Capture8K::ConsumeFrames (void) { CAPNOTE("Thread started"); while (!mGlobalQuit) { // Wait for the next frame to become ready to "consume"... AVDataBuffer * pFrameData (mAVCircularBuffer.StartConsumeNextBuffer ()); if (pFrameData) { // Do something useful with the frame data... // . . . . . . . . . . . . // . . . . . . . . . . . . // . . . . . . . . . . . . // Now release and recycle the buffer... mAVCircularBuffer.EndConsumeNextBuffer (); } } // loop til quit signaled CAPNOTE("Thread completed, will exit"); } // ConsumeFrames ////////////////////////////////////////////// ////////////////////////////////////////////// // This is where we start the capture thread void NTV2Capture8K::StartProducerThread (void) { // Create and start the capture thread... mProducerThread.Attach(ProducerThreadStatic, this); mProducerThread.SetPriority(AJA_ThreadPriority_High); mProducerThread.Start(); } // StartProducerThread // The capture thread function void NTV2Capture8K::ProducerThreadStatic (AJAThread * pThread, void * pContext) // static { (void) pThread; // Grab the NTV2Capture instance pointer from the pContext parameter, // then call its CaptureFrames method... NTV2Capture8K * pApp (reinterpret_cast <NTV2Capture8K *> (pContext)); pApp->CaptureFrames (); } // ProducerThreadStatic void NTV2Capture8K::CaptureFrames (void) { NTV2AudioChannelPairs nonPcmPairs, oldNonPcmPairs; CAPNOTE("Thread started"); // Start AutoCirculate running... mDevice.AutoCirculateStart (mInputChannel); while (!mGlobalQuit) { AUTOCIRCULATE_STATUS acStatus; mDevice.AutoCirculateGetStatus (mInputChannel, acStatus); if (acStatus.IsRunning () && acStatus.HasAvailableInputFrame ()) { // At this point, there's at least one fully-formed frame available in the device's // frame buffer to transfer to the host. Reserve an AVDataBuffer to "produce", and // use it in the next transfer from the device... AVDataBuffer * captureData (mAVCircularBuffer.StartProduceNextBuffer ()); mInputTransfer.SetBuffers (captureData->fVideoBuffer, captureData->fVideoBufferSize, captureData->fAudioBuffer, captureData->fAudioBufferSize, captureData->fAncBuffer, captureData->fAncBufferSize); // Do the transfer from the device into our host AVDataBuffer... mDevice.AutoCirculateTransfer (mInputChannel, mInputTransfer); // mInputTransfer.acTransferStatus.acAudioTransferSize; // this is the amount of audio captured NTV2SDIInStatistics sdiStats; mDevice.ReadSDIStatistics (sdiStats); // "Capture" timecode into the host AVDataBuffer while we have full access to it... NTV2_RP188 timecode; mInputTransfer.GetInputTimeCode (timecode); captureData->fRP188Data = timecode; // Signal that we're done "producing" the frame, making it available for future "consumption"... mAVCircularBuffer.EndProduceNextBuffer (); } // if A/C running and frame(s) are available for transfer else { // Either AutoCirculate is not running, or there were no frames available on the device to transfer. // Rather than waste CPU cycles spinning, waiting until a frame becomes available, it's far more // efficient to wait for the next input vertical interrupt event to get signaled... mDevice.WaitForInputVerticalInterrupt (mInputChannel); } } // loop til quit signaled // Stop AutoCirculate... mDevice.AutoCirculateStop (mInputChannel); CAPNOTE("Thread completed, will exit"); } // CaptureFrames ////////////////////////////////////////////// void NTV2Capture8K::GetACStatus (ULWord & outGoodFrames, ULWord & outDroppedFrames, ULWord & outBufferLevel) { AUTOCIRCULATE_STATUS status; mDevice.AutoCirculateGetStatus (mInputChannel, status); outGoodFrames = status.acFramesProcessed; outDroppedFrames = status.acFramesDropped; outBufferLevel = status.acBufferLevel; }
24,627
9,208
/* File: ControlPanel.cpp Author: Mathilde Created on 18 octobre 2016, 11:37 */ #include <map> #include "vector" #include <math.h> #include <iostream> #include "Arduino.h" #include "ControlPanel.h" #include "Button.h" // constructors ControlPanel::ControlPanel() { } ControlPanel::ControlPanel(int newBtnNumberMax) { this->btnList.reserve(newBtnNumberMax); } //getter /* std::vector::size_type ControlPanel::getBtnNumber(){ return this->btnList.size; }*/ int ControlPanel::getBtnNumberMax() { return this->btnList.capacity(); } std::vector<Button> ControlPanel::getBtnList() { return this->btnList; } //setters void ControlPanel::setBtnNumberMax(int newBtnNumberMax) { this->btnList.reserve(newBtnNumberMax); } //************************************************************************ // Add button in the control panel button list // Arguments : the button you want to add in the list // Return : nothing //************************************************************************ void ControlPanel::addButton(Button newBtn) { this->btnList.push_back(newBtn); } //************************************************************************ // Memory reservation for buttons // Arguments : the number of buttons you want to rreserve memory for // Return : nothing //************************************************************************ void ControlPanel::reserve(int newBtnNumberMax) { this->btnList.reserve(newBtnNumberMax); } //************************************************************************ // Control panel read: read all buttons stocked in the button vector // Arguments : none // Return : none //************************************************************************ void ControlPanel::controlRead() { for (auto &btn : this->btnList) { btn.readValue(); } } //int ControlPanel::toBinary(){ // int count=0; // int binary=0; // // controlRead(); // for (auto &btn: this->btnList){ // if(btn.getValue() == LOW){ // binary = binary + pow(10,count); // } // count++; // } // return binary; //} //************************************************************************ // Control panel analyse: analyse the values stored in memory from read // Arguments : none // Return : 1 right; 2 left; 3 down; 4 up; 5 validate //************************************************************************ int ControlPanel::analyze() { controlRead(); // Serial.println("Analyse button"); if (this->btnList[0].value == LOW) { return 1; } else if (this->btnList[1].value == LOW) { return 2; } else if (this->btnList[2].value == LOW) { return 3; } else if (this->btnList[3].value == LOW) { return 4; } else if (this->btnList[4].value == LOW) { return 5; } else { return 0; } }
2,832
842
#include <unistd.h> #include <cctype> #include <sstream> #include <string> #include <vector> #include "process.h" #include "linux_parser.h" using std::string; using std::to_string; using std::vector; Process::Process(int pid) :pid_(pid) { cpu_utilization_ = CpuUtilization(); } // TODO: Return this process's ID int Process::Pid() { return pid_; } float Process::CpuUtilization() { std::vector<long> info = LinuxParser::CpuUtilization(pid_); long total_time = info[0] + info[1]; total_time += info[2] + info[3]; float seconds = (float)UpTime(); float cpu_utilization = ((total_time / sysconf(_SC_CLK_TCK)) / seconds); return cpu_utilization; } string Process::Command() { return LinuxParser::Command(pid_); } string Process::Ram() { return LinuxParser::Ram(pid_); } string Process::User() { return LinuxParser::User(pid_); } long int Process::UpTime() { return LinuxParser::UpTime(pid_); } bool Process::operator>(Process const& a) const { return (cpu_utilization_ > a.cpu_utilization_); }
1,029
371
#include "GameCardProcess.h" #include <tc/crypto.h> #include <tc/io/IOUtil.h> #include <nn/hac/GameCardUtil.h> #include <nn/hac/ContentMetaUtil.h> #include <nn/hac/ContentArchiveUtil.h> #include <nn/hac/GameCardFsMetaGenerator.h> #include "FsProcess.h" nstool::GameCardProcess::GameCardProcess() : mModuleName("nstool::GameCardProcess"), mFile(), mCliOutputMode(true, false, false, false), mVerify(false), mListFs(false), mProccessExtendedHeader(false), mRootPfs(), mExtractJobs() { } void nstool::GameCardProcess::process() { importHeader(); // validate header signature if (mVerify) validateXciSignature(); // display header if (mCliOutputMode.show_basic_info) displayHeader(); // process nested HFS0 processRootPfs(); } void nstool::GameCardProcess::setInputFile(const std::shared_ptr<tc::io::IStream>& file) { mFile = file; } void nstool::GameCardProcess::setKeyCfg(const KeyBag& keycfg) { mKeyCfg = keycfg; } void nstool::GameCardProcess::setCliOutputMode(CliOutputMode type) { mCliOutputMode = type; } void nstool::GameCardProcess::setVerifyMode(bool verify) { mVerify = verify; } void nstool::GameCardProcess::setExtractJobs(const std::vector<nstool::ExtractJob> extract_jobs) { mExtractJobs = extract_jobs; } void nstool::GameCardProcess::setShowFsTree(bool show_fs_tree) { mListFs = show_fs_tree; } void nstool::GameCardProcess::importHeader() { if (mFile == nullptr) { throw tc::Exception(mModuleName, "No file reader set."); } if (mFile->canRead() == false || mFile->canSeek() == false) { throw tc::NotSupportedException(mModuleName, "Input stream requires read/seek permissions."); } // check stream is large enough for header if (mFile->length() < tc::io::IOUtil::castSizeToInt64(sizeof(nn::hac::sSdkGcHeader))) { throw tc::Exception(mModuleName, "Corrupt GameCard Image: File too small."); } // allocate memory for header tc::ByteData scratch = tc::ByteData(sizeof(nn::hac::sSdkGcHeader)); // read header region mFile->seek(0, tc::io::SeekOrigin::Begin); mFile->read(scratch.data(), scratch.size()); // determine if this is a SDK XCI or a "Community" XCI if (((nn::hac::sSdkGcHeader*)scratch.data())->signed_header.header.st_magic.unwrap() == nn::hac::gc::kGcHeaderStructMagic) { mIsTrueSdkXci = true; mGcHeaderOffset = sizeof(nn::hac::sGcKeyDataRegion); } else if (((nn::hac::sGcHeader_Rsa2048Signed*)scratch.data())->header.st_magic.unwrap() == nn::hac::gc::kGcHeaderStructMagic) { mIsTrueSdkXci = false; mGcHeaderOffset = 0; } else { throw tc::Exception(mModuleName, "Corrupt GameCard Image: Unexpected magic bytes."); } nn::hac::sGcHeader_Rsa2048Signed* hdr_ptr = (nn::hac::sGcHeader_Rsa2048Signed*)(scratch.data() + mGcHeaderOffset); // generate hash of raw header tc::crypto::GenerateSha256Hash(mHdrHash.data(), (byte_t*)&hdr_ptr->header, sizeof(nn::hac::sGcHeader)); // save the signature memcpy(mHdrSignature.data(), hdr_ptr->signature.data(), mHdrSignature.size()); // decrypt extended header byte_t xci_header_key_index = hdr_ptr->header.key_flag & 7; if (mKeyCfg.xci_header_key.find(xci_header_key_index) != mKeyCfg.xci_header_key.end()) { nn::hac::GameCardUtil::decryptXciHeader(&hdr_ptr->header, mKeyCfg.xci_header_key[xci_header_key_index].data()); mProccessExtendedHeader = true; } // deserialise header mHdr.fromBytes((byte_t*)&hdr_ptr->header, sizeof(nn::hac::sGcHeader)); } void nstool::GameCardProcess::displayHeader() { const nn::hac::sGcHeader* raw_hdr = (const nn::hac::sGcHeader*)mHdr.getBytes().data(); fmt::print("[GameCard/Header]\n"); fmt::print(" CardHeaderVersion: {:d}\n", mHdr.getCardHeaderVersion()); fmt::print(" RomSize: {:s}", nn::hac::GameCardUtil::getRomSizeAsString((nn::hac::gc::RomSize)mHdr.getRomSizeType())); if (mCliOutputMode.show_extended_info) fmt::print(" (0x{:x})", mHdr.getRomSizeType()); fmt::print("\n"); fmt::print(" PackageId: 0x{:016x}\n", mHdr.getPackageId()); fmt::print(" Flags: 0x{:02x}\n", *((byte_t*)&raw_hdr->flags)); for (auto itr = mHdr.getFlags().begin(); itr != mHdr.getFlags().end(); itr++) { fmt::print(" {:s}\n", nn::hac::GameCardUtil::getHeaderFlagsAsString((nn::hac::gc::HeaderFlags)*itr)); } if (mCliOutputMode.show_extended_info) { fmt::print(" KekIndex: {:s} ({:d})\n", nn::hac::GameCardUtil::getKekIndexAsString((nn::hac::gc::KekIndex)mHdr.getKekIndex()), mHdr.getKekIndex()); fmt::print(" TitleKeyDecIndex: {:d}\n", mHdr.getTitleKeyDecIndex()); fmt::print(" InitialData:\n"); fmt::print(" Hash:\n"); fmt::print(" {:s}", tc::cli::FormatUtil::formatBytesAsStringWithLineLimit(mHdr.getInitialDataHash().data(), mHdr.getInitialDataHash().size(), true, "", 0x10, 6, false)); } if (mCliOutputMode.show_extended_info) { fmt::print(" Extended Header AesCbc IV:\n"); fmt::print(" {:s}\n", tc::cli::FormatUtil::formatBytesAsString(mHdr.getAesCbcIv().data(), mHdr.getAesCbcIv().size(), true, "")); } fmt::print(" SelSec: 0x{:x}\n", mHdr.getSelSec()); fmt::print(" SelT1Key: 0x{:x}\n", mHdr.getSelT1Key()); fmt::print(" SelKey: 0x{:x}\n", mHdr.getSelKey()); if (mCliOutputMode.show_layout) { fmt::print(" RomAreaStartPage: 0x{:x}", mHdr.getRomAreaStartPage()); if (mHdr.getRomAreaStartPage() != (uint32_t)(-1)) fmt::print(" (0x{:x})", nn::hac::GameCardUtil::blockToAddr(mHdr.getRomAreaStartPage())); fmt::print("\n"); fmt::print(" BackupAreaStartPage: 0x{:x}", mHdr.getBackupAreaStartPage()); if (mHdr.getBackupAreaStartPage() != (uint32_t)(-1)) fmt::print(" (0x{:x})", nn::hac::GameCardUtil::blockToAddr(mHdr.getBackupAreaStartPage())); fmt::print("\n"); fmt::print(" ValidDataEndPage: 0x{:x}", mHdr.getValidDataEndPage()); if (mHdr.getValidDataEndPage() != (uint32_t)(-1)) fmt::print(" (0x{:x})", nn::hac::GameCardUtil::blockToAddr(mHdr.getValidDataEndPage())); fmt::print("\n"); fmt::print(" LimArea: 0x{:x}", mHdr.getLimAreaPage()); if (mHdr.getLimAreaPage() != (uint32_t)(-1)) fmt::print(" (0x{:x})", nn::hac::GameCardUtil::blockToAddr(mHdr.getLimAreaPage())); fmt::print("\n"); fmt::print(" PartitionFs Header:\n"); fmt::print(" Offset: 0x{:x}\n", mHdr.getPartitionFsAddress()); fmt::print(" Size: 0x{:x}\n", mHdr.getPartitionFsSize()); if (mCliOutputMode.show_extended_info) { fmt::print(" Hash:\n"); fmt::print(" {:s}", tc::cli::FormatUtil::formatBytesAsStringWithLineLimit(mHdr.getPartitionFsHash().data(), mHdr.getPartitionFsHash().size(), true, "", 0x10, 6, false)); } } if (mProccessExtendedHeader) { fmt::print("[GameCard/ExtendedHeader]\n"); fmt::print(" FwVersion: v{:d} ({:s})\n", mHdr.getFwVersion(), nn::hac::GameCardUtil::getCardFwVersionDescriptionAsString((nn::hac::gc::FwVersion)mHdr.getFwVersion())); fmt::print(" AccCtrl1: 0x{:x}\n", mHdr.getAccCtrl1()); fmt::print(" CardClockRate: {:s}\n", nn::hac::GameCardUtil::getCardClockRateAsString((nn::hac::gc::CardClockRate)mHdr.getAccCtrl1())); fmt::print(" Wait1TimeRead: 0x{:x}\n", mHdr.getWait1TimeRead()); fmt::print(" Wait2TimeRead: 0x{:x}\n", mHdr.getWait2TimeRead()); fmt::print(" Wait1TimeWrite: 0x{:x}\n", mHdr.getWait1TimeWrite()); fmt::print(" Wait2TimeWrite: 0x{:x}\n", mHdr.getWait2TimeWrite()); fmt::print(" SdkAddon Version: {:s} (v{:d})\n", nn::hac::ContentArchiveUtil::getSdkAddonVersionAsString(mHdr.getFwMode()), mHdr.getFwMode()); fmt::print(" CompatibilityType: {:s} ({:d})\n", nn::hac::GameCardUtil::getCompatibilityTypeAsString((nn::hac::gc::CompatibilityType)mHdr.getCompatibilityType()), mHdr.getCompatibilityType()); fmt::print(" Update Partition Info:\n"); fmt::print(" CUP Version: {:s} (v{:d})\n", nn::hac::ContentMetaUtil::getVersionAsString(mHdr.getUppVersion()), mHdr.getUppVersion()); fmt::print(" CUP TitleId: 0x{:016x}\n", mHdr.getUppId()); fmt::print(" CUP Digest: {:s}\n", tc::cli::FormatUtil::formatBytesAsString(mHdr.getUppHash().data(), mHdr.getUppHash().size(), true, "")); } } bool nstool::GameCardProcess::validateRegionOfFile(int64_t offset, int64_t len, const byte_t* test_hash, bool use_salt, byte_t salt) { // read region into memory tc::ByteData scratch = tc::ByteData(tc::io::IOUtil::castInt64ToSize(len)); mFile->seek(offset, tc::io::SeekOrigin::Begin); mFile->read(scratch.data(), scratch.size()); // update hash tc::crypto::Sha256Generator sha256_gen; sha256_gen.initialize(); sha256_gen.update(scratch.data(), scratch.size()); if (use_salt) sha256_gen.update(&salt, sizeof(salt)); // calculate hash nn::hac::detail::sha256_hash_t calc_hash; sha256_gen.getHash(calc_hash.data()); return memcmp(calc_hash.data(), test_hash, calc_hash.size()) == 0; } bool nstool::GameCardProcess::validateRegionOfFile(int64_t offset, int64_t len, const byte_t* test_hash) { return validateRegionOfFile(offset, len, test_hash, false, 0); } void nstool::GameCardProcess::validateXciSignature() { if (mKeyCfg.xci_header_sign_key.isSet()) { if (tc::crypto::VerifyRsa2048Pkcs1Sha256(mHdrSignature.data(), mHdrHash.data(), mKeyCfg.xci_header_sign_key.get()) == false) { fmt::print("[WARNING] GameCard Header Signature: FAIL\n"); } } else { fmt::print("[WARNING] GameCard Header Signature: FAIL (Failed to load rsa public key.)\n"); } } void nstool::GameCardProcess::processRootPfs() { if (mVerify && validateRegionOfFile(mHdr.getPartitionFsAddress(), mHdr.getPartitionFsSize(), mHdr.getPartitionFsHash().data(), mHdr.getCompatibilityType() != nn::hac::gc::COMPAT_GLOBAL, mHdr.getCompatibilityType()) == false) { fmt::print("[WARNING] GameCard Root HFS0: FAIL (bad hash)\n"); } std::shared_ptr<tc::io::IStream> gc_fs_raw = std::make_shared<tc::io::SubStream>(tc::io::SubStream(mFile, mHdr.getPartitionFsAddress(), nn::hac::GameCardUtil::blockToAddr(mHdr.getValidDataEndPage()+1) - mHdr.getPartitionFsAddress())); auto gc_vfs_meta = nn::hac::GameCardFsMetaGenerator(gc_fs_raw, mHdr.getPartitionFsSize(), mVerify ? nn::hac::GameCardFsMetaGenerator::ValidationMode_Warn : nn::hac::GameCardFsMetaGenerator::ValidationMode_None); std::shared_ptr<tc::io::IStorage> gc_vfs = std::make_shared<tc::io::VirtualFileSystem>(tc::io::VirtualFileSystem(gc_vfs_meta) ); FsProcess fs_proc; fs_proc.setInputFileSystem(gc_vfs); fs_proc.setFsFormatName("PartitionFs"); fs_proc.setFsProperties({ fmt::format("Type: Nested HFS0"), fmt::format("DirNum: {:d}", gc_vfs_meta.dir_entries.empty() ? 0 : gc_vfs_meta.dir_entries.size() - 1), // -1 to not include root directory fmt::format("FileNum: {:d}", gc_vfs_meta.file_entries.size()) }); fs_proc.setShowFsInfo(mCliOutputMode.show_basic_info); fs_proc.setShowFsTree(mListFs); fs_proc.setFsRootLabel(kXciMountPointName); fs_proc.setExtractJobs(mExtractJobs); fs_proc.process(); }
11,055
4,517
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #include <sfx2/sidebar/ResourceDefinitions.hrc> #include <sfx2/sidebar/Theme.hxx> #include <sfx2/sidebar/ControlFactory.hxx> #include <sfx2/sidebar/Layouter.hxx> #include "PosSizePropertyPanel.hxx" #include "PosSizePropertyPanel.hrc" #include <svx/sidebar/SidebarDialControl.hxx> #include <svx/dialogs.hrc> #include <svx/dialmgr.hxx> #include <sfx2/dispatch.hxx> #include <sfx2/bindings.hxx> #include <sfx2/viewsh.hxx> #include <sfx2/objsh.hxx> #include <sfx2/imagemgr.hxx> #include <svx/dlgutil.hxx> #include <unotools/viewoptions.hxx> #include <vcl/virdev.hxx> #include <vcl/svapp.hxx> #include <vcl/field.hxx> #include <vcl/fixed.hxx> #include <vcl/toolbox.hxx> #include <svx/svdview.hxx> #include <svl/aeitem.hxx> using namespace css; using namespace cssu; using ::sfx2::sidebar::Layouter; using ::sfx2::sidebar::Theme; #define A2S(pString) (::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(pString))) #define USERITEM_NAME rtl::OUString::createFromAscii("FitItem") #define NO_SELECT (65535) namespace svx { namespace sidebar { PosSizePropertyPanel::PosSizePropertyPanel( Window* pParent, const cssu::Reference<css::frame::XFrame>& rxFrame, SfxBindings* pBindings, const cssu::Reference<css::ui::XSidebar>& rxSidebar) : Control( pParent, SVX_RES(RID_SIDEBAR_POSSIZE_PANEL)), mpFtPosX(new FixedText(this, SVX_RES(FT_SBSHAPE_HORIZONTAL))), mpMtrPosX(new MetricField(this, SVX_RES(MF_SBSHAPE_HORIZONTAL))), mpFtPosY(new FixedText(this, SVX_RES(FT_SBSHAPE_VERTICAL))), mpMtrPosY(new MetricField(this, SVX_RES(MF_SBSHAPE_VERTICAL))), mpFtWidth(new FixedText(this, SVX_RES(FT_WIDTH))), mpMtrWidth(new MetricField(this, SVX_RES(MTR_FLD_WIDTH))), mpFtHeight(new FixedText(this, SVX_RES(FT_HEIGHT))), mpMtrHeight(new MetricField(this, SVX_RES(MTR_FLD_HEIGHT))), mpCbxScale(new CheckBox(this, SVX_RES(CBX_SCALE))), mpFtAngle(new FixedText(this, SVX_RES(FT_ANGLE))), mpMtrAngle(new MetricBox(this, SVX_RES(MTR_FLD_ANGLE))), mpDial(new SidebarDialControl(this, SVX_RES(DIAL_CONTROL))), mpFtFlip(new FixedText(this, SVX_RES(FT_FLIP))), mpFlipTbxBackground(sfx2::sidebar::ControlFactory::CreateToolBoxBackground(this)), mpFlipTbx(sfx2::sidebar::ControlFactory::CreateToolBox(mpFlipTbxBackground.get(), SVX_RES(TBX_FLIP))), maRect(), mpView(0), mlOldWidth(1), mlOldHeight(1), meRP(RP_LT), maAnchorPos(), mlRotX(0), mlRotY(0), maUIScale(), mePoolUnit(), // #124409# init with fallback default meDlgUnit(FUNIT_INCH), maTransfPosXControl(SID_ATTR_TRANSFORM_POS_X, *pBindings, *this), maTransfPosYControl(SID_ATTR_TRANSFORM_POS_Y, *pBindings, *this), maTransfWidthControl(SID_ATTR_TRANSFORM_WIDTH, *pBindings, *this), maTransfHeightControl(SID_ATTR_TRANSFORM_HEIGHT, *pBindings, *this), maSvxAngleControl( SID_ATTR_TRANSFORM_ANGLE, *pBindings, *this), maRotXControl(SID_ATTR_TRANSFORM_ROT_X, *pBindings, *this), maRotYControl(SID_ATTR_TRANSFORM_ROT_Y, *pBindings, *this), maProPosControl(SID_ATTR_TRANSFORM_PROTECT_POS, *pBindings, *this), maProSizeControl(SID_ATTR_TRANSFORM_PROTECT_SIZE, *pBindings, *this), maAutoWidthControl(SID_ATTR_TRANSFORM_AUTOWIDTH, *pBindings, *this), maAutoHeightControl(SID_ATTR_TRANSFORM_AUTOHEIGHT, *pBindings, *this), m_aMetricCtl(SID_ATTR_METRIC, *pBindings, *this), mxFrame(rxFrame), maContext(), mpBindings(pBindings), maFtWidthOrigPos(mpFtWidth->GetPosPixel()), maMtrWidthOrigPos(mpMtrWidth->GetPosPixel()), maFtHeightOrigPos(mpFtHeight->GetPosPixel()), maMtrHeightOrigPos(mpMtrHeight->GetPosPixel()), maCbxScaleOrigPos(mpCbxScale->GetPosPixel()), maFtAngleOrigPos(mpFtAngle->GetPosPixel()), maMtrAnglOrigPos(mpMtrAngle->GetPosPixel()), maFlipTbxOrigPos(mpFlipTbx->GetPosPixel()), maDialOrigPos(mpDial->GetPosPixel()), maFtFlipOrigPos(mpFtFlip->GetPosPixel()), mbMtrPosXMirror(false), mbSizeProtected(false), mbPositionProtected(false), mbAutoWidth(false), mbAutoHeight(false), mbAdjustEnabled(false), mbIsFlip(false), mxSidebar(rxSidebar), maLayouter(*this) { Initialize(); FreeResource(); mpBindings->Update( SID_ATTR_TRANSFORM_WIDTH ); mpBindings->Update( SID_ATTR_TRANSFORM_HEIGHT ); mpBindings->Update( SID_ATTR_TRANSFORM_PROTECT_SIZE ); mpBindings->Update( SID_ATTR_METRIC ); // Setup the grid layouter. const sal_Int32 nMappedMboxWidth (Layouter::MapWidth(*this, MBOX_WIDTH)); maLayouter.GetCell(0,0).SetControl(*mpFtPosX); maLayouter.GetCell(1,0).SetControl(*mpMtrPosX); maLayouter.GetCell(0,2).SetControl(*mpFtPosY); maLayouter.GetCell(1,2).SetControl(*mpMtrPosY); maLayouter.GetCell(2,0).SetControl(*mpFtWidth); maLayouter.GetCell(3,0).SetControl(*mpMtrWidth); maLayouter.GetCell(2,2).SetControl(*mpFtHeight); maLayouter.GetCell(3,2).SetControl(*mpMtrHeight); maLayouter.GetCell(4,0).SetControl(*mpCbxScale).SetGridWidth(3); maLayouter.GetCell(5,0).SetControl(*mpFtAngle).SetGridWidth(3); maLayouter.GetColumn(0) .SetWeight(1) .SetLeftPadding(Layouter::MapWidth(*this,SECTIONPAGE_MARGIN_HORIZONTAL)) .SetMinimumWidth(nMappedMboxWidth); maLayouter.GetColumn(1) .SetWeight(0) .SetMinimumWidth(Layouter::MapWidth(*this, CONTROL_SPACING_HORIZONTAL)); maLayouter.GetColumn(2) .SetWeight(1) .SetRightPadding(Layouter::MapWidth(*this,SECTIONPAGE_MARGIN_HORIZONTAL)) .SetMinimumWidth(nMappedMboxWidth); // Make controls that display text handle short widths more // graceful. Layouter::PrepareForLayouting(*mpFtPosX); Layouter::PrepareForLayouting(*mpFtPosY); Layouter::PrepareForLayouting(*mpFtWidth); Layouter::PrepareForLayouting(*mpFtHeight); Layouter::PrepareForLayouting(*mpCbxScale); Layouter::PrepareForLayouting(*mpFtAngle); } PosSizePropertyPanel::~PosSizePropertyPanel() { // Destroy the background windows of the toolboxes. mpFlipTbx.reset(); mpFlipTbxBackground.reset(); } void PosSizePropertyPanel::ShowMenu (void) { if (mpBindings != NULL) { SfxDispatcher* pDispatcher = mpBindings->GetDispatcher(); if (pDispatcher != NULL) pDispatcher->Execute(SID_ATTR_TRANSFORM, SFX_CALLMODE_ASYNCHRON); } } namespace { bool hasText(const SdrView& rSdrView) { const SdrMarkList& rMarkList = rSdrView.GetMarkedObjectList(); if(1 == rMarkList.GetMarkCount()) { const SdrObject* pObj = rMarkList.GetMark(0)->GetMarkedSdrObj(); const SdrObjKind eKind((SdrObjKind)pObj->GetObjIdentifier()); if((pObj->GetObjInventor() == SdrInventor) && (OBJ_TEXT == eKind || OBJ_TITLETEXT == eKind || OBJ_OUTLINETEXT == eKind)) { const SdrTextObj* pSdrTextObj = dynamic_cast< const SdrTextObj* >(pObj); if(pSdrTextObj && pSdrTextObj->HasText()) { return true; } } } return false; } } // end of anonymous namespace void PosSizePropertyPanel::Resize (void) { maLayouter.Layout(); } void PosSizePropertyPanel::Initialize() { mpFtPosX->SetBackground(Wallpaper()); mpFtPosY->SetBackground(Wallpaper()); mpFtWidth->SetBackground(Wallpaper()); mpFtHeight->SetBackground(Wallpaper()); mpFtAngle->SetBackground(Wallpaper()); mpFtFlip->SetBackground(Wallpaper()); //Position : Horizontal / Vertical mpMtrPosX->SetModifyHdl( LINK( this, PosSizePropertyPanel, ChangePosXHdl ) ); mpMtrPosY->SetModifyHdl( LINK( this, PosSizePropertyPanel, ChangePosYHdl ) ); mpMtrPosX->SetAccessibleName(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Horizontal"))); //wj acc mpMtrPosY->SetAccessibleName(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Vertical"))); //wj acc //Size : Width / Height mpMtrWidth->SetModifyHdl( LINK( this, PosSizePropertyPanel, ChangeWidthHdl ) ); mpMtrHeight->SetModifyHdl( LINK( this, PosSizePropertyPanel, ChangeHeightHdl ) ); mpMtrWidth->SetAccessibleName(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Width"))); //wj acc mpMtrHeight->SetAccessibleName(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Height"))); //wj acc //Size : Keep ratio mpCbxScale->SetClickHdl( LINK( this, PosSizePropertyPanel, ClickAutoHdl ) ); //rotation: mpMtrAngle->SetModifyHdl(LINK( this, PosSizePropertyPanel, AngleModifiedHdl)); mpMtrAngle->EnableAutocomplete( false ); mpMtrAngle->SetAccessibleName(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Rotation"))); //wj acc //rotation control mpDial->SetModifyHdl(LINK( this, PosSizePropertyPanel, RotationHdl)); //flip: mpFlipTbx->SetSelectHdl( LINK( this, PosSizePropertyPanel, FlipHdl) ); mpFlipTbx->SetItemImage( FLIP_HORIZONTAL, GetImage(mxFrame, A2S(".uno:FlipHorizontal"), sal_False, Theme::IsHighContrastMode())); mpFlipTbx->SetItemImage( FLIP_VERTICAL, GetImage(mxFrame, A2S(".uno:FlipVertical"), sal_False, Theme::IsHighContrastMode())); mpFlipTbx->SetQuickHelpText(FLIP_HORIZONTAL,String(SVX_RES(STR_QH_HORI_FLIP))); //Add mpFlipTbx->SetQuickHelpText(FLIP_VERTICAL,String(SVX_RES(STR_QH_VERT_FLIP))); //Add mpMtrPosX->SetAccessibleRelationLabeledBy(mpFtPosX.get()); mpMtrPosY->SetAccessibleRelationLabeledBy(mpFtPosY.get()); mpMtrWidth->SetAccessibleRelationLabeledBy(mpFtWidth.get()); mpMtrHeight->SetAccessibleRelationLabeledBy(mpFtHeight.get()); mpMtrAngle->SetAccessibleRelationLabeledBy(mpFtAngle.get()); #ifdef HAS_IA2 mpMtrAngle->SetMpSubEditAccLableBy(mpFtAngle.get()); #endif mpFlipTbx->SetAccessibleRelationLabeledBy(mpFtFlip.get()); mpMtrAngle->InsertValue(0, FUNIT_CUSTOM); mpMtrAngle->InsertValue(4500, FUNIT_CUSTOM); mpMtrAngle->InsertValue(9000, FUNIT_CUSTOM); mpMtrAngle->InsertValue(13500, FUNIT_CUSTOM); mpMtrAngle->InsertValue(18000, FUNIT_CUSTOM); mpMtrAngle->InsertValue(22500, FUNIT_CUSTOM); mpMtrAngle->InsertValue(27000, FUNIT_CUSTOM); mpMtrAngle->InsertValue(31500, FUNIT_CUSTOM); mpMtrAngle->AdaptDropDownLineCountToMaximum(); SfxViewShell* pCurSh = SfxViewShell::Current(); if ( pCurSh ) mpView = pCurSh->GetDrawView(); else mpView = NULL; if ( mpView != NULL ) { maUIScale = mpView->GetModel()->GetUIScale(); mbAdjustEnabled = hasText(*mpView); } mePoolUnit = maTransfWidthControl.GetCoreMetric(); // #124409# no need to do this, the mpBindings->Update( SID_ATTR_METRIC ) // call in the constructor will trigger MetricState and will get the correct unit // // meDlgUnit = GetModuleFieldUnit(); // SetFieldUnit( *mpMtrPosX, meDlgUnit, true ); // SetFieldUnit( *mpMtrPosY, meDlgUnit, true ); // SetFieldUnit( *mpMtrWidth, meDlgUnit, true ); // SetFieldUnit( *mpMtrHeight, meDlgUnit, true ); } void PosSizePropertyPanel::SetupIcons(void) { if(Theme::GetBoolean(Theme::Bool_UseSymphonyIcons)) { // todo } else { // todo } } PosSizePropertyPanel* PosSizePropertyPanel::Create ( Window* pParent, const cssu::Reference<css::frame::XFrame>& rxFrame, SfxBindings* pBindings, const cssu::Reference<css::ui::XSidebar>& rxSidebar) { if (pParent == NULL) throw lang::IllegalArgumentException(A2S("no parent Window given to PosSizePropertyPanel::Create"), NULL, 0); if ( ! rxFrame.is()) throw lang::IllegalArgumentException(A2S("no XFrame given to PosSizePropertyPanel::Create"), NULL, 1); if (pBindings == NULL) throw lang::IllegalArgumentException(A2S("no SfxBindings given to PosSizePropertyPanel::Create"), NULL, 2); return new PosSizePropertyPanel( pParent, rxFrame, pBindings, rxSidebar); } void PosSizePropertyPanel::DataChanged( const DataChangedEvent& rEvent) { (void)rEvent; SetupIcons(); } void PosSizePropertyPanel::AdaptWidthHeightScalePosition(bool bOriginal) { if(bOriginal) { mpFtWidth->SetPosPixel(maFtWidthOrigPos); mpMtrWidth->SetPosPixel(maMtrWidthOrigPos); mpFtHeight->SetPosPixel(maFtHeightOrigPos); mpMtrHeight->SetPosPixel(maMtrHeightOrigPos); mpCbxScale->SetPosPixel(maCbxScaleOrigPos); } else { mpFtWidth->SetPosPixel(Point(LogicToPixel(Point(FT_POSITION_X_X,FT_POSITION_X_Y), MAP_APPFONT))); mpMtrWidth->SetPosPixel(Point(LogicToPixel(Point(MF_POSITION_X_X,MF_POSITION_X_Y), MAP_APPFONT))); mpFtHeight->SetPosPixel(Point(LogicToPixel(Point(FT_POSITION_Y_X,FT_POSITION_Y_Y), MAP_APPFONT))); mpMtrHeight->SetPosPixel(Point(LogicToPixel(Point(MF_POSITION_Y_X,MF_POSITION_Y_Y), MAP_APPFONT))); mpCbxScale->SetPosPixel(Point(LogicToPixel(Point(FT_WIDTH_X,FT_WIDTH_Y), MAP_APPFONT))); } } void PosSizePropertyPanel::AdaptAngleFlipDialPosition(bool bOriginal) { if(bOriginal) { mpFtAngle->SetPosPixel(maFtAngleOrigPos); mpMtrAngle->SetPosPixel(maMtrAnglOrigPos); mpFlipTbx->SetPosPixel(maFlipTbxOrigPos); mpDial->SetPosPixel(maDialOrigPos); mpFtFlip->SetPosPixel(maFtFlipOrigPos); } else { mpFtAngle->SetPosPixel(Point(LogicToPixel(Point(FT_ANGLE_X,FT_ANGLE_Y), MAP_APPFONT))); mpMtrAngle->SetPosPixel(Point(LogicToPixel(Point(MF_ANGLE_X2,MF_ANGLE_Y2), MAP_APPFONT))); mpFlipTbx->SetPosPixel(Point(LogicToPixel(Point(FLIP_HORI_X2,FLIP_HORI_Y2), MAP_APPFONT))); mpDial->SetPosPixel(Point(LogicToPixel(Point(ROTATE_CONTROL_X2,ROTATE_CONTROL_Y2), MAP_APPFONT))); mpFtFlip->SetPosPixel(Point(LogicToPixel(Point(FT_FLIP_X2,FT_FLIP_Y2), MAP_APPFONT))); } } void PosSizePropertyPanel::HandleContextChange( const ::sfx2::sidebar::EnumContext aContext) { if(maContext == aContext) { // Nothing to do. return; } maContext = aContext; sal_Int32 nLayoutMode (0); switch (maContext.GetCombinedContext_DI()) { case CombinedEnumContext(Application_WriterVariants, Context_Draw): nLayoutMode = 0; break; case CombinedEnumContext(Application_WriterVariants, Context_Graphic): case CombinedEnumContext(Application_WriterVariants, Context_Media): case CombinedEnumContext(Application_WriterVariants, Context_Frame): case CombinedEnumContext(Application_WriterVariants, Context_OLE): case CombinedEnumContext(Application_WriterVariants, Context_Form): nLayoutMode = 1; break; case CombinedEnumContext(Application_Calc, Context_Draw): case CombinedEnumContext(Application_Calc, Context_Graphic): case CombinedEnumContext(Application_DrawImpress, Context_Draw): case CombinedEnumContext(Application_DrawImpress, Context_TextObject): case CombinedEnumContext(Application_DrawImpress, Context_Graphic): nLayoutMode = 2; break; case CombinedEnumContext(Application_Calc, Context_Chart): case CombinedEnumContext(Application_Calc, Context_Form): case CombinedEnumContext(Application_Calc, Context_Media): case CombinedEnumContext(Application_Calc, Context_OLE): case CombinedEnumContext(Application_Calc, Context_MultiObject): case CombinedEnumContext(Application_DrawImpress, Context_Media): case CombinedEnumContext(Application_DrawImpress, Context_Form): case CombinedEnumContext(Application_DrawImpress, Context_OLE): case CombinedEnumContext(Application_DrawImpress, Context_3DObject): case CombinedEnumContext(Application_DrawImpress, Context_MultiObject): nLayoutMode = 3; break; } switch (nLayoutMode) { case 0: { mpMtrWidth->SetMin( 2 ); mpMtrHeight->SetMin( 2 ); mpFtPosX->Hide(); mpMtrPosX->Hide(); mpFtPosY->Hide(); mpMtrPosY->Hide(); //rotation mpFtAngle->Show(); mpMtrAngle->Show(); mpDial->Show(); //flip mpFtFlip->Show(); mpFlipTbx->Show(); Size aTbxSize = mpFlipTbx->CalcWindowSizePixel(); mpFlipTbx->SetOutputSizePixel( aTbxSize ); mbIsFlip = true; AdaptWidthHeightScalePosition(false); AdaptAngleFlipDialPosition(false); mpFtAngle->SetPosPixel(Point(LogicToPixel(Point(FT_ANGLE_X,FT_ANGLE_Y), MAP_APPFONT))); mpMtrAngle->SetPosPixel(Point(LogicToPixel(Point(MF_ANGLE_X2,MF_ANGLE_Y2), MAP_APPFONT))); mpFlipTbx->SetPosPixel(Point(LogicToPixel(Point(FLIP_HORI_X2,FLIP_HORI_Y2), MAP_APPFONT))); mpDial->SetPosPixel(Point(LogicToPixel(Point(ROTATE_CONTROL_X2,ROTATE_CONTROL_Y2), MAP_APPFONT))); mpFtFlip->SetPosPixel(Point(LogicToPixel(Point(FT_FLIP_X2,FT_FLIP_Y2), MAP_APPFONT))); Size aSize(GetOutputSizePixel().Width(),PS_SECTIONPAGE_HEIGHT2); aSize = LogicToPixel( aSize, MapMode(MAP_APPFONT) ); SetSizePixel(aSize); if (mxSidebar.is()) mxSidebar->requestLayout(); } break; case 1: { mpMtrWidth->SetMin( 2 ); mpMtrHeight->SetMin( 2 ); mpFtPosX->Hide(); mpMtrPosX->Hide(); mpFtPosY->Hide(); mpMtrPosY->Hide(); //rotation mpFtAngle->Hide(); mpMtrAngle->Hide(); mpDial->Hide(); //flip mpFlipTbx->Hide(); mpFtFlip->Hide(); mbIsFlip = false; AdaptWidthHeightScalePosition(false); AdaptAngleFlipDialPosition(true); Size aSize(GetOutputSizePixel().Width(),PS_SECTIONPAGE_HEIGHT3); aSize = LogicToPixel( aSize, MapMode(MAP_APPFONT) ); SetSizePixel(aSize); if (mxSidebar.is()) mxSidebar->requestLayout(); } break; case 2: { mpMtrWidth->SetMin( 1 ); mpMtrHeight->SetMin( 1 ); mpFtPosX->Show(); mpMtrPosX->Show(); mpFtPosY->Show(); mpMtrPosY->Show(); //rotation mpFtAngle->Show(); mpMtrAngle->Show(); mpDial->Show(); //flip mpFlipTbx->Show(); mpFtFlip->Show(); Size aTbxSize = mpFlipTbx->CalcWindowSizePixel(); mpFlipTbx->SetOutputSizePixel( aTbxSize ); mbIsFlip = true; AdaptWidthHeightScalePosition(true); AdaptAngleFlipDialPosition(true); Size aSize(GetOutputSizePixel().Width(),PS_SECTIONPAGE_HEIGHT); aSize = LogicToPixel( aSize, MapMode(MAP_APPFONT) ); SetSizePixel(aSize); if (mxSidebar.is()) mxSidebar->requestLayout(); } break; case 3: { mpMtrWidth->SetMin( 1 ); mpMtrHeight->SetMin( 1 ); mpFtPosX->Show(); mpMtrPosX->Show(); mpFtPosY->Show(); mpMtrPosY->Show(); //rotation mpFtAngle->Hide(); mpMtrAngle->Hide(); mpDial->Hide(); //flip mpFlipTbx->Hide(); mpFtFlip->Hide(); mbIsFlip = false; AdaptWidthHeightScalePosition(true); AdaptAngleFlipDialPosition(true); Size aSize(GetOutputSizePixel().Width(),PS_SECTIONPAGE_HEIGHT4); aSize = LogicToPixel( aSize, MapMode(MAP_APPFONT) ); SetSizePixel(aSize); if (mxSidebar.is()) mxSidebar->requestLayout(); } break; } //Added for windows classic theme mpFlipTbx->SetBackground(Wallpaper()); mpFlipTbx->SetPaintTransparent(true); } IMPL_LINK( PosSizePropertyPanel, ChangeWidthHdl, void*, /*pBox*/ ) { if( mpCbxScale->IsChecked() && mpCbxScale->IsEnabled() ) { long nHeight = (long) ( ((double) mlOldHeight * (double) mpMtrWidth->GetValue()) / (double) mlOldWidth ); if( nHeight <= mpMtrHeight->GetMax( FUNIT_NONE ) ) { mpMtrHeight->SetUserValue( nHeight, FUNIT_NONE ); } else { nHeight = (long)mpMtrHeight->GetMax( FUNIT_NONE ); mpMtrHeight->SetUserValue( nHeight ); const long nWidth = (long) ( ((double) mlOldWidth * (double) nHeight) / (double) mlOldHeight ); mpMtrWidth->SetUserValue( nWidth, FUNIT_NONE ); } } executeSize(); return 0; } IMPL_LINK( PosSizePropertyPanel, ChangeHeightHdl, void *, EMPTYARG ) { if( mpCbxScale->IsChecked() && mpCbxScale->IsEnabled() ) { long nWidth = (long) ( ((double)mlOldWidth * (double)mpMtrHeight->GetValue()) / (double)mlOldHeight ); if( nWidth <= mpMtrWidth->GetMax( FUNIT_NONE ) ) { mpMtrWidth->SetUserValue( nWidth, FUNIT_NONE ); } else { nWidth = (long)mpMtrWidth->GetMax( FUNIT_NONE ); mpMtrWidth->SetUserValue( nWidth ); const long nHeight = (long) ( ((double)mlOldHeight * (double)nWidth) / (double)mlOldWidth ); mpMtrHeight->SetUserValue( nHeight, FUNIT_NONE ); } } executeSize(); return 0; } IMPL_LINK( PosSizePropertyPanel, ChangePosXHdl, void *, EMPTYARG ) { executePosX(); return 0; } IMPL_LINK( PosSizePropertyPanel, ChangePosYHdl, void *, EMPTYARG ) { executePosY(); return 0; } IMPL_LINK( PosSizePropertyPanel, ClickAutoHdl, void *, EMPTYARG ) { if ( mpCbxScale->IsChecked() ) { mlOldWidth = Max( GetCoreValue( *mpMtrWidth, mePoolUnit ), 1L ); mlOldHeight = Max( GetCoreValue( *mpMtrHeight, mePoolUnit ), 1L ); } // mpCbxScale must synchronized with that on Position and Size tabpage on Shape Properties dialog SvtViewOptions aPageOpt( E_TABPAGE, String::CreateFromInt32( RID_SVXPAGE_POSITION_SIZE ) ); aPageOpt.SetUserItem( USERITEM_NAME, ::com::sun::star::uno::makeAny( ::rtl::OUString( String::CreateFromInt32( mpCbxScale->IsChecked() ) ) ) ); return 0; } IMPL_LINK( PosSizePropertyPanel, AngleModifiedHdl, void *, EMPTYARG ) { String sTmp = mpMtrAngle->GetText(); bool bNegative = 0; sal_Unicode nChar = sTmp.GetChar( 0 ); if( nChar == '-' ) { bNegative = 1; nChar = sTmp.GetChar( 1 ); } if( (nChar < '0') || (nChar > '9') ) return 0; double dTmp = sTmp.ToDouble(); if(bNegative) { while(dTmp<0) dTmp += 360; } sal_Int64 nTmp = dTmp*100; // #123993# Need to take UIScale into account when executing rotations const double fUIScale(mpView && mpView->GetModel() ? double(mpView->GetModel()->GetUIScale()) : 1.0); SfxInt32Item aAngleItem( SID_ATTR_TRANSFORM_ANGLE,(sal_uInt32) nTmp); SfxInt32Item aRotXItem( SID_ATTR_TRANSFORM_ROT_X, basegfx::fround(mlRotX * fUIScale)); SfxInt32Item aRotYItem( SID_ATTR_TRANSFORM_ROT_Y, basegfx::fround(mlRotY * fUIScale)); GetBindings()->GetDispatcher()->Execute( SID_ATTR_TRANSFORM, SFX_CALLMODE_RECORD, &aAngleItem, &aRotXItem, &aRotYItem, 0L ); return 0; } IMPL_LINK( PosSizePropertyPanel, RotationHdl, void *, EMPTYARG ) { sal_Int32 nTmp = mpDial->GetRotation(); // #123993# Need to take UIScale into account when executing rotations const double fUIScale(mpView && mpView->GetModel() ? double(mpView->GetModel()->GetUIScale()) : 1.0); SfxInt32Item aAngleItem( SID_ATTR_TRANSFORM_ANGLE,(sal_uInt32) nTmp); SfxInt32Item aRotXItem( SID_ATTR_TRANSFORM_ROT_X, basegfx::fround(mlRotX * fUIScale)); SfxInt32Item aRotYItem( SID_ATTR_TRANSFORM_ROT_Y, basegfx::fround(mlRotY * fUIScale)); GetBindings()->GetDispatcher()->Execute( SID_ATTR_TRANSFORM, SFX_CALLMODE_RECORD, &aAngleItem, &aRotXItem, &aRotYItem, 0L ); return 0; } IMPL_LINK( PosSizePropertyPanel, FlipHdl, ToolBox*, pBox ) { switch (pBox->GetCurItemId()) { case FLIP_HORIZONTAL: { SfxVoidItem aHoriItem (SID_FLIP_HORIZONTAL); GetBindings()->GetDispatcher()->Execute( SID_FLIP_HORIZONTAL, SFX_CALLMODE_RECORD, &aHoriItem, 0L ); } break; case FLIP_VERTICAL: { SfxVoidItem aVertItem (SID_FLIP_VERTICAL ); GetBindings()->GetDispatcher()->Execute( SID_FLIP_VERTICAL, SFX_CALLMODE_RECORD, &aVertItem, 0L ); } break; } return 0; } void PosSizePropertyPanel::NotifyItemUpdate( sal_uInt16 nSID, SfxItemState eState, const SfxPoolItem* pState, const bool /* bIsEnabled */) { mpFtAngle->Enable(); mpMtrAngle->Enable(); mpDial->Enable(); mpFtFlip->Enable(); mpFlipTbx->Enable(); const SfxUInt32Item* pWidthItem; const SfxUInt32Item* pHeightItem; SfxViewShell* pCurSh = SfxViewShell::Current(); if ( pCurSh ) mpView = pCurSh->GetDrawView(); else mpView = NULL; if ( mpView == NULL ) return; mbAdjustEnabled = hasText(*mpView); // Pool unit and dialog unit may have changed, make sure that we // have the current values. mePoolUnit = maTransfWidthControl.GetCoreMetric(); // #124409# do not change; GetModuleFieldUnit uses SfxModule::GetCurrentFieldUnit() // which uses GetActiveModule() and if no items are set there (which is the case e.g. // for writer), will just return the system fallback of FUNIT_INCH which is wrong. // Anyways, with multiple open views the static call GetActiveModule is ambigious // // meDlgUnit = GetModuleFieldUnit(); switch (nSID) { case SID_ATTR_TRANSFORM_WIDTH: if ( SFX_ITEM_AVAILABLE == eState ) { pWidthItem = dynamic_cast< const SfxUInt32Item* >(pState); if(pWidthItem) { long mlOldWidth1 = pWidthItem->GetValue(); mlOldWidth1 = Fraction( mlOldWidth1 ) / maUIScale; SetFieldUnit( *mpMtrWidth, meDlgUnit, true ); SetMetricValue( *mpMtrWidth, mlOldWidth1, mePoolUnit ); mlOldWidth = mlOldWidth1; break; } } mpMtrWidth->SetText( String()); break; case SID_ATTR_TRANSFORM_HEIGHT: if ( SFX_ITEM_AVAILABLE == eState ) { pHeightItem = dynamic_cast< const SfxUInt32Item* >(pState); if(pHeightItem) { long mlOldHeight1 = pHeightItem->GetValue(); mlOldHeight1 = Fraction( mlOldHeight1 ) / maUIScale; SetFieldUnit( *mpMtrHeight, meDlgUnit, true ); SetMetricValue( *mpMtrHeight, mlOldHeight1, mePoolUnit ); mlOldHeight = mlOldHeight1; break; } } mpMtrHeight->SetText( String()); break; case SID_ATTR_TRANSFORM_POS_X: if(SFX_ITEM_AVAILABLE == eState) { const SfxInt32Item* pItem = dynamic_cast< const SfxInt32Item* >(pState); if(pItem) { long nTmp = pItem->GetValue(); nTmp = Fraction( nTmp ) / maUIScale; SetFieldUnit( *mpMtrPosX, meDlgUnit, true ); SetMetricValue( *mpMtrPosX, nTmp, mePoolUnit ); break; } } mpMtrPosX->SetText( String()); break; case SID_ATTR_TRANSFORM_POS_Y: if(SFX_ITEM_AVAILABLE == eState) { const SfxInt32Item* pItem = dynamic_cast< const SfxInt32Item* >(pState); if(pItem) { long nTmp = pItem->GetValue(); nTmp = Fraction( nTmp ) / maUIScale; SetFieldUnit( *mpMtrPosY, meDlgUnit, true ); SetMetricValue( *mpMtrPosY, nTmp, mePoolUnit ); break; } } mpMtrPosY->SetText( String()); break; case SID_ATTR_TRANSFORM_ROT_X: if (SFX_ITEM_AVAILABLE == eState) { const SfxInt32Item* pItem = dynamic_cast< const SfxInt32Item* >(pState); if(pItem) { mlRotX = pItem->GetValue(); mlRotX = Fraction( mlRotX ) / maUIScale; } } break; case SID_ATTR_TRANSFORM_ROT_Y: if (SFX_ITEM_AVAILABLE == eState) { const SfxInt32Item* pItem = dynamic_cast< const SfxInt32Item* >(pState); if(pItem) { mlRotY = pItem->GetValue(); mlRotY = Fraction( mlRotY ) / maUIScale; } } break; case SID_ATTR_TRANSFORM_PROTECT_POS: if(SFX_ITEM_AVAILABLE == eState) { const SfxBoolItem* pItem = dynamic_cast< const SfxBoolItem* >(pState); if(pItem) { // record the state of position protect mbPositionProtected = pItem->GetValue(); break; } } mbPositionProtected = false; break; case SID_ATTR_TRANSFORM_PROTECT_SIZE: if(SFX_ITEM_AVAILABLE == eState) { const SfxBoolItem* pItem = dynamic_cast< const SfxBoolItem* >(pState); if(pItem) { // record the state of size protect mbSizeProtected = pItem->GetValue(); break; } } mbSizeProtected = false; break; case SID_ATTR_TRANSFORM_AUTOWIDTH: if(SFX_ITEM_AVAILABLE == eState) { const SfxBoolItem* pItem = dynamic_cast< const SfxBoolItem* >(pState); if(pItem) { mbAutoWidth = pItem->GetValue(); } } break; case SID_ATTR_TRANSFORM_AUTOHEIGHT: if(SFX_ITEM_AVAILABLE == eState) { const SfxBoolItem* pItem = dynamic_cast< const SfxBoolItem* >(pState); if(pItem) { mbAutoHeight = pItem->GetValue(); } } break; case SID_ATTR_TRANSFORM_ANGLE: if (eState >= SFX_ITEM_AVAILABLE) { const SfxInt32Item* pItem = dynamic_cast< const SfxInt32Item* >(pState); if(pItem) { long nTmp = pItem->GetValue(); mpMtrAngle->SetValue( nTmp ); mpDial->SetRotation( nTmp ); switch(nTmp) { case 0: mpMtrAngle->SelectEntryPos(0); break; case 4500: mpMtrAngle->SelectEntryPos(1); break; case 9000: mpMtrAngle->SelectEntryPos(2); break; case 13500: mpMtrAngle->SelectEntryPos(3); break; case 18000: mpMtrAngle->SelectEntryPos(4); break; case 22500: mpMtrAngle->SelectEntryPos(5); break; case 27000: mpMtrAngle->SelectEntryPos(6); break; case 315000: mpMtrAngle->SelectEntryPos(7); break; } break; } } mpMtrAngle->SetText( String() ); mpDial->SetRotation( 0 ); break; case SID_ATTR_METRIC: MetricState( eState, pState ); UpdateUIScale(); break; default: break; } const sal_Int32 nCombinedContext(maContext.GetCombinedContext_DI()); const SdrMarkList& rMarkList = mpView->GetMarkedObjectList(); switch (rMarkList.GetMarkCount()) { case 0: break; case 1: { const SdrObject* pObj = rMarkList.GetMark(0)->GetMarkedSdrObj(); const SdrObjKind eKind((SdrObjKind)pObj->GetObjIdentifier()); if(((nCombinedContext == CombinedEnumContext(Application_DrawImpress, Context_Draw) || nCombinedContext == CombinedEnumContext(Application_DrawImpress, Context_TextObject) ) && OBJ_EDGE == eKind) || OBJ_CAPTION == eKind) { mpFtAngle->Disable(); mpMtrAngle->Disable(); mpDial->Disable(); mpFlipTbx->Disable(); mpFtFlip->Disable(); } break; } default: { sal_uInt16 nMarkObj = 0; bool isNoEdge = true; while(isNoEdge && rMarkList.GetMark(nMarkObj)) { const SdrObject* pObj = rMarkList.GetMark(nMarkObj)->GetMarkedSdrObj(); const SdrObjKind eKind((SdrObjKind)pObj->GetObjIdentifier()); if(((nCombinedContext == CombinedEnumContext(Application_DrawImpress, Context_Draw) || nCombinedContext == CombinedEnumContext(Application_DrawImpress, Context_TextObject) ) && OBJ_EDGE == eKind) || OBJ_CAPTION == eKind) { isNoEdge = false; break; } nMarkObj++; } if(!isNoEdge) { mpFtAngle->Disable(); mpMtrAngle->Disable(); mpDial->Disable(); mpFlipTbx->Disable(); mpFtFlip->Disable(); } break; } } if(nCombinedContext == CombinedEnumContext(Application_DrawImpress, Context_TextObject)) { mpFlipTbx->Disable(); mpFtFlip->Disable(); } DisableControls(); // mpCbxScale must synchronized with that on Position and Size tabpage on Shape Properties dialog SvtViewOptions aPageOpt( E_TABPAGE, String::CreateFromInt32( RID_SVXPAGE_POSITION_SIZE ) ); String sUserData; ::com::sun::star::uno::Any aUserItem = aPageOpt.GetUserItem( USERITEM_NAME ); ::rtl::OUString aTemp; if ( aUserItem >>= aTemp ) sUserData = String( aTemp ); mpCbxScale->Check( (bool)sUserData.ToInt32() ); } SfxBindings* PosSizePropertyPanel::GetBindings() { return mpBindings; } void PosSizePropertyPanel::executeSize() { if ( mpMtrWidth->IsValueModified() || mpMtrHeight->IsValueModified()) { Fraction aUIScale = mpView->GetModel()->GetUIScale(); // get Width double nWidth = (double)mpMtrWidth->GetValue( meDlgUnit ); nWidth = MetricField::ConvertDoubleValue( nWidth, mpMtrWidth->GetBaseValue(), mpMtrWidth->GetDecimalDigits(), meDlgUnit, FUNIT_100TH_MM ); long lWidth = (long)(nWidth * (double)aUIScale); lWidth = OutputDevice::LogicToLogic( lWidth, MAP_100TH_MM, (MapUnit)mePoolUnit ); lWidth = (long)mpMtrWidth->Denormalize( lWidth ); // get Height double nHeight = (double)mpMtrHeight->GetValue( meDlgUnit ); nHeight = MetricField::ConvertDoubleValue( nHeight, mpMtrHeight->GetBaseValue(), mpMtrHeight->GetDecimalDigits(), meDlgUnit, FUNIT_100TH_MM ); long lHeight = (long)(nHeight * (double)aUIScale); lHeight = OutputDevice::LogicToLogic( lHeight, MAP_100TH_MM, (MapUnit)mePoolUnit ); lHeight = (long)mpMtrWidth->Denormalize( lHeight ); // put Width & Height to itemset SfxUInt32Item aWidthItem( SID_ATTR_TRANSFORM_WIDTH, (sal_uInt32) lWidth); SfxUInt32Item aHeightItem( SID_ATTR_TRANSFORM_HEIGHT, (sal_uInt32) lHeight); SfxAllEnumItem aPointItem (SID_ATTR_TRANSFORM_SIZE_POINT, (sal_uInt16)meRP); const sal_Int32 nCombinedContext(maContext.GetCombinedContext_DI()); if( nCombinedContext == CombinedEnumContext(Application_WriterVariants, Context_Graphic) || nCombinedContext == CombinedEnumContext(Application_WriterVariants, Context_OLE) ) { GetBindings()->GetDispatcher()->Execute(SID_ATTR_TRANSFORM, SFX_CALLMODE_RECORD, &aWidthItem, &aHeightItem, &aPointItem, 0L ); } else { if ( (mpMtrWidth->IsValueModified()) && (mpMtrHeight->IsValueModified())) GetBindings()->GetDispatcher()->Execute(SID_ATTR_TRANSFORM, SFX_CALLMODE_RECORD, &aWidthItem, &aHeightItem, &aPointItem, 0L ); else if( mpMtrWidth->IsValueModified()) GetBindings()->GetDispatcher()->Execute(SID_ATTR_TRANSFORM, SFX_CALLMODE_RECORD, &aWidthItem, &aPointItem, 0L ); else if ( mpMtrHeight->IsValueModified()) GetBindings()->GetDispatcher()->Execute(SID_ATTR_TRANSFORM, SFX_CALLMODE_RECORD, &aHeightItem, &aPointItem, 0L ); } } } void PosSizePropertyPanel::executePosX() { if ( mpMtrPosX->IsValueModified()) { long lX = GetCoreValue( *mpMtrPosX, mePoolUnit ); if( mbMtrPosXMirror ) lX = -lX; long lY = GetCoreValue( *mpMtrPosY, mePoolUnit ); Size aPageSize; Rectangle aRect; maRect = mpView->GetAllMarkedRect(); aRect = mpView->GetAllMarkedRect(); Fraction aUIScale = mpView->GetModel()->GetUIScale(); lX += maAnchorPos.X(); lX = Fraction( lX ) * aUIScale; lY += maAnchorPos.Y(); lY = Fraction( lY ) * aUIScale; SfxInt32Item aPosXItem( SID_ATTR_TRANSFORM_POS_X,(sal_uInt32) lX); SfxInt32Item aPosYItem( SID_ATTR_TRANSFORM_POS_Y,(sal_uInt32) lY); GetBindings()->GetDispatcher()->Execute( SID_ATTR_TRANSFORM, SFX_CALLMODE_RECORD, &aPosXItem, 0L ); } } void PosSizePropertyPanel::executePosY() { if ( mpMtrPosY->IsValueModified() ) { long lX = GetCoreValue( *mpMtrPosX, mePoolUnit ); long lY = GetCoreValue( *mpMtrPosY, mePoolUnit ); Size aPageSize; Rectangle aRect; maRect = mpView->GetAllMarkedRect(); aRect = mpView->GetAllMarkedRect(); Fraction aUIScale = mpView->GetModel()->GetUIScale(); lX += maAnchorPos.X(); lX = Fraction( lX ) * aUIScale; lY += maAnchorPos.Y(); lY = Fraction( lY ) * aUIScale; SfxInt32Item aPosXItem( SID_ATTR_TRANSFORM_POS_X,(sal_uInt32) lX); SfxInt32Item aPosYItem( SID_ATTR_TRANSFORM_POS_Y,(sal_uInt32) lY); GetBindings()->GetDispatcher()->Execute( SID_ATTR_TRANSFORM, SFX_CALLMODE_RECORD, &aPosYItem, 0L ); } } void PosSizePropertyPanel::MetricState( SfxItemState eState, const SfxPoolItem* pState ) { bool bPosXBlank = false; bool bPosYBlank = false; bool bWidthBlank = false; bool bHeightBlank = false; String sNull = String::CreateFromAscii(""); // #124409# use the given Item to get the correct UI unit and initialize it // and the Fields using it meDlgUnit = GetCurrentUnit(eState,pState); if( mpMtrPosX->GetText() == sNull ) bPosXBlank = true; SetFieldUnit( *mpMtrPosX, meDlgUnit, true ); if(bPosXBlank) mpMtrPosX->SetText(String()); if( mpMtrPosY->GetText() == sNull ) bPosYBlank = true; SetFieldUnit( *mpMtrPosY, meDlgUnit, true ); if(bPosYBlank) mpMtrPosY->SetText(String()); if( mpMtrWidth->GetText() == sNull ) bWidthBlank = true; SetFieldUnit( *mpMtrWidth, meDlgUnit, true ); if(bWidthBlank) mpMtrWidth->SetText(String()); if( mpMtrHeight->GetText() == sNull ) bHeightBlank = true; SetFieldUnit( *mpMtrHeight, meDlgUnit, true ); if(bHeightBlank) mpMtrHeight->SetText(String()); } FieldUnit PosSizePropertyPanel::GetCurrentUnit( SfxItemState eState, const SfxPoolItem* pState ) { FieldUnit eUnit = FUNIT_NONE; if ( pState && eState >= SFX_ITEM_DEFAULT ) { eUnit = (FieldUnit)( (const SfxUInt16Item*)pState )->GetValue(); } else { SfxViewFrame* pFrame = SfxViewFrame::Current(); SfxObjectShell* pSh = NULL; if ( pFrame ) pSh = pFrame->GetObjectShell(); if ( pSh ) { SfxModule* pModule = pSh->GetModule(); if ( pModule ) { const SfxPoolItem* pItem = pModule->GetItem( SID_ATTR_METRIC ); if ( pItem ) eUnit = (FieldUnit)( (SfxUInt16Item*)pItem )->GetValue(); } else { DBG_ERRORFILE( "GetModuleFieldUnit(): no module found" ); } } } return eUnit; } void PosSizePropertyPanel::DisableControls() { if( mbPositionProtected ) { // the position is protected("Position protect" option in modal dialog is checked), // disable all the Position controls in sidebar mpFtPosX->Disable(); mpMtrPosX->Disable(); mpFtPosY->Disable(); mpMtrPosY->Disable(); mpFtAngle->Disable(); mpMtrAngle->Disable(); mpDial->Disable(); mpFtFlip->Disable(); mpFlipTbx->Disable(); mpFtWidth->Disable(); mpMtrWidth->Disable(); mpFtHeight->Disable(); mpMtrHeight->Disable(); mpCbxScale->Disable(); } else { mpFtPosX->Enable(); mpMtrPosX->Enable(); mpFtPosY->Enable(); mpMtrPosY->Enable(); //mpFtAngle->Enable(); //mpMtrAngle->Enable(); //mpDial->Enable(); //mpFtFlip->Enable(); //mpFlipTbx->Enable(); if( mbSizeProtected ) { mpFtWidth->Disable(); mpMtrWidth->Disable(); mpFtHeight->Disable(); mpMtrHeight->Disable(); mpCbxScale->Disable(); } else { if( mbAdjustEnabled ) { if( mbAutoWidth ) { mpFtWidth->Disable(); mpMtrWidth->Disable(); mpCbxScale->Disable(); } else { mpFtWidth->Enable(); mpMtrWidth->Enable(); } if( mbAutoHeight ) { mpFtHeight->Disable(); mpMtrHeight->Disable(); mpCbxScale->Disable(); } else { mpFtHeight->Enable(); mpMtrHeight->Enable(); } if( !mbAutoWidth && !mbAutoHeight ) mpCbxScale->Enable(); } else { mpFtWidth->Enable(); mpMtrWidth->Enable(); mpFtHeight->Enable(); mpMtrHeight->Enable(); mpCbxScale->Enable(); } } } } void PosSizePropertyPanel::UpdateUIScale (void) { const Fraction aUIScale (mpView->GetModel()->GetUIScale()); if (maUIScale != aUIScale) { // UI scale has changed. // Remember the new UI scale. maUIScale = aUIScale; // The content of the position and size boxes is only updated when item changes are notified. // Request such notifications without changing the actual item values. GetBindings()->Invalidate(SID_ATTR_TRANSFORM_POS_X, sal_True, sal_False); GetBindings()->Invalidate(SID_ATTR_TRANSFORM_POS_Y, sal_True, sal_False); GetBindings()->Invalidate(SID_ATTR_TRANSFORM_WIDTH, sal_True, sal_False); GetBindings()->Invalidate(SID_ATTR_TRANSFORM_HEIGHT, sal_True, sal_False); } } } } // end of namespace svx::sidebar // eof
46,076
15,930
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <vector> #include <queue> #include <algorithm> #include <assert.h> using namespace std; struct Edge { int from, to; int64_t c; Edge(int from=0, int to=0, int64_t c=0): from(from), to(to), c(c) {} }; const int MAXN = 50005; static vector<Edge> g[MAXN]; static int indeg[MAXN]; static int64_t toST[MAXN], diffST[MAXN]; static int64_t toED[MAXN], diffED[MAXN]; static vector<int> order; static vector<Edge> in; static int n; void topo() { memset(toST, 0, sizeof(toST)); memset(diffST, 0, sizeof(diffST)); memset(toED, 0, sizeof(toED)); memset(diffED, 0, sizeof(diffED)); order.clear(); queue<int> Q; for (int i = 1; i <= n; i++) { if (indeg[i] == 0) Q.push(i); } while (!Q.empty()) { int u = Q.front(); Q.pop(); order.push_back(u); for (auto e : g[u]) { if (toST[e.to] && toST[e.to] != toST[u] + e.c) diffST[e.to]++; diffST[e.to] = diffST[e.to] + diffST[u]; toST[e.to] = max(toST[e.to], toST[u] + e.c); if (--indeg[e.to] == 0) Q.push(e.to); } } assert(order.size() == n); for (int i = (int) order.size()-1; i >= 0; i--) { int u = order[i]; if (u == n) continue; for (auto e : g[u]) { toED[u] = max(toED[u], toED[e.to] + e.c); diffED[u] += diffED[e.to]; } if (g[u].size()) { Edge e = g[u][0]; int64_t dd = toED[e.to] + e.c; for (int j = 1; j < g[u].size(); j++) diffED[u] += (toED[g[u][j].to] + g[u][j].c != dd); } } for (int i = 1; i <= n; i++) { if (diffST[i] > 0 && diffED[i] > 0) { puts("No solution"); return ; } } vector< pair<int, int64_t> > ret; for (int i = 0; i < in.size(); i++) { Edge e = in[i]; if (diffST[e.from] == 0 && diffST[e.to] > 0) { int64_t cc = toST[n] - (toST[e.from] + toED[e.to] + e.c); assert(cc >= 0); if (cc > 0) ret.push_back(make_pair(i+1, cc)); } } printf("%d %lld\n", (int) ret.size(), toST[n]); for (auto e : ret) printf("%d %lld\n", e.first, e.second); } int main() { int cases = 0; int m; while (scanf("%d %d", &n, &m) == 2 && n) { for (int i = 0; i <= n; i++) g[i].clear(); in.clear(); memset(indeg, 0, sizeof(indeg)); for (int i = 0; i < m; i++) { int x, y, c; scanf("%d %d %d", &x, &y, &c); g[x].push_back(Edge(x, y, c)); in.push_back(Edge(x, y, c)); indeg[y]++; } printf("Case %d: ", ++cases); topo(); } return 0; } /* 3 3 1 3 10 1 2 3 2 3 5 4 5 1 3 5 3 2 1 2 4 6 1 4 10 3 4 3 3 4 1 2 1 1 2 2 2 3 1 2 3 2 0 0 */
3,059
1,325
/****************************************************** Flag.cpp This is the implementation file for the Flag class. ******************************************************/ #include "headers/Flag.h" //***************************************************** Flag::Flag(Player* owner, int xPos, int yPos, int boardSpace) : Piece(owner, xPos, yPos, "lib/images/flag.png"){ setBoardSpace(boardSpace); setRank(12); } //***************************************************** Flag::Flag(Player* owner, std::string filename) : Piece(owner, 0, 0, filename.c_str()){ setBoardSpace(-1); setRank(12); } //***************************************************** Piece* Flag::move(Piece* const destination){ return 0; }
734
217
/** * @file * * @brief tests for the storage service * * @copyright BSD License (see doc/LICENSE.md or http://www.libelektra.org) */ #include <gtest/gtest.h> #include <config.hpp> #include <kdb_includes.hpp> #include <model_entry.hpp> #include <model_user.hpp> #include <service.hpp> /** * TESTS for kdbrest::service::StorageEngine */ TEST (kdbrestServicesStorageengineTest, CreateEntryCheck) { using namespace kdb; using namespace kdbrest::model; using namespace kdbrest::service; std::string testKey = "test/test/test/entry1"; std::string testSubKey1 = kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + "test/test/test/entry1/confkey1"; std::string testSubKey2 = kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + "test/test/test/entry1/conf/iguration/key1"; Key subKey1 (testSubKey1, KEY_END); Key subKey2 (testSubKey2, KEY_END); Entry testEntry (testKey); testEntry.addSubkey (subKey1); testEntry.addSubkey (subKey2); testEntry.setTitle ("test-title"); testEntry.setDescription ("test-description"); testEntry.setAuthor ("test-author"); auto tags = testEntry.getTags (); tags.push_back ("test-tag"); tags.push_back ("test-tag2"); testEntry.setTags (tags); // ensure entry is not in database { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.cut (testEntry); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } // do storage StorageEngine::instance ().createEntry (testEntry); // ensure that entry has been saved { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); Key k = ks.lookup (testEntry); if (k) { ASSERT_EQ (k.getName (), testEntry.getName ()); ASSERT_TRUE (k.hasMeta (ELEKTRA_REST_MODEL_ENTRY_META_AUTHOR)); ASSERT_TRUE (k.hasMeta (ELEKTRA_REST_MODEL_ENTRY_META_TITLE)); ASSERT_TRUE (k.hasMeta (ELEKTRA_REST_MODEL_ENTRY_META_DESCRIPTION)); ASSERT_TRUE (k.hasMeta (ELEKTRA_REST_MODEL_ENTRY_META_TAGS)); ASSERT_EQ (k.getMeta<std::string> (ELEKTRA_REST_MODEL_ENTRY_META_AUTHOR), testEntry.getAuthor ()); ASSERT_EQ (k.getMeta<std::string> (ELEKTRA_REST_MODEL_ENTRY_META_TITLE), testEntry.getTitle ()); ASSERT_EQ (k.getMeta<std::string> (ELEKTRA_REST_MODEL_ENTRY_META_DESCRIPTION), testEntry.getDescription ()); ASSERT_EQ (k.getMeta<std::string> (ELEKTRA_REST_MODEL_ENTRY_META_TAGS), testEntry.getTags ().at (0) + " " + testEntry.getTags ().at (1)); ASSERT_TRUE (ks.lookup (subKey1)); ASSERT_TRUE (ks.lookup (subKey2)); } else { ASSERT_TRUE (false); // force error } } // delete entry after test { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.cut (testEntry); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } } TEST (kdbrestServicesStorageengineTest, UpdateEntryCheck) { using namespace kdb; using namespace kdbrest::exception; using namespace kdbrest::model; using namespace kdbrest::service; std::string testKey = "test/test/test/entry1"; std::string testSubKey1 = kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + "test/test/test/entry1/confkey1"; std::string testSubKey2 = kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + "test/test/test/entry1/conf/iguration/key1"; std::string testSubKeyNew1 = kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + "test/test/test/entry1/configuration/k1"; std::string testSubKeyNew2 = kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + "test/test/test/entry1/co/nf/ig/u/ra/ti/on/key1"; Key subKey1 (testSubKey1, KEY_END); Key subKey2 (testSubKey2, KEY_END); Key newSubKey1 (testSubKeyNew1, KEY_END); Key newSubKey2 (testSubKeyNew2, KEY_END); Entry testEntry (testKey); testEntry.addSubkey (subKey1); testEntry.addSubkey (subKey2); testEntry.setTitle ("test-title"); testEntry.setAuthor ("test-author"); // ensure entry is not in database { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.cut (testEntry); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } // create entry { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.append (testEntry); ks.append (testEntry.getSubkeys ()); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } // ensure that entry has been saved { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); Key k = ks.lookup (testEntry); if (!k) { ASSERT_TRUE (false); // force error } } // force re-fetching of entry cache (void)StorageEngine::instance ().getAllEntriesRef (true); // update the entry testEntry.setTitle ("new-test-title"); testEntry.setAuthor ("new-test-author"); testEntry.getSubkeys ().clear (); ASSERT_EQ (testEntry.getSubkeys ().size (), 0); testEntry.addSubkey (newSubKey1); testEntry.addSubkey (newSubKey2); try { StorageEngine::instance ().updateEntry (testEntry); } catch (EntryNotFoundException & e) { ASSERT_TRUE (false); } // ensure that entry has been updated { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); Key k = ks.lookup (testEntry); if (k) { ASSERT_EQ (k.getName (), testEntry.getName ()); ASSERT_TRUE (k.hasMeta (ELEKTRA_REST_MODEL_ENTRY_META_TITLE)); ASSERT_TRUE (k.hasMeta (ELEKTRA_REST_MODEL_ENTRY_META_AUTHOR)); ASSERT_EQ (k.getMeta<std::string> (ELEKTRA_REST_MODEL_ENTRY_META_TITLE), testEntry.getTitle ()); ASSERT_EQ (k.getMeta<std::string> (ELEKTRA_REST_MODEL_ENTRY_META_AUTHOR), testEntry.getAuthor ()); ASSERT_TRUE (ks.lookup (newSubKey1)); ASSERT_TRUE (ks.lookup (newSubKey2)); } else { ASSERT_TRUE (false); // force error } } // delete entry after test { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.cut (testEntry); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } } TEST (kdbrestServicesStorageengineTest, DeleteEntryCheck) { using namespace kdb; using namespace kdbrest::model; using namespace kdbrest::service; std::string testKey = "test/test/test/entry1"; std::string testSubKey1 = kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + "test/test/test/entry1/confkey1"; std::string testSubKey2 = kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + "test/test/test/entry1/conf/iguration/key1"; Key subKey1 (testSubKey1, KEY_END); Key subKey2 (testSubKey2, KEY_END); Entry testEntry (testKey); testEntry.addSubkey (subKey1); testEntry.addSubkey (subKey2); testEntry.setAuthor ("test-author"); // ensure entry is not in database { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.cut (testEntry); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } // force re-fetching of entry cache (void)StorageEngine::instance ().getAllEntriesRef (true); // do storage StorageEngine::instance ().createEntry (testEntry); // ensure that entry has been saved { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); Key k = ks.lookup (testEntry); if (k) { ASSERT_EQ (k.getName (), testEntry.getName ()); ASSERT_TRUE (k.hasMeta (ELEKTRA_REST_MODEL_ENTRY_META_AUTHOR)); ASSERT_EQ (k.getMeta<std::string> (ELEKTRA_REST_MODEL_ENTRY_META_AUTHOR), testEntry.getAuthor ()); ASSERT_TRUE (ks.lookup (subKey1)); ASSERT_TRUE (ks.lookup (subKey2)); } else { ASSERT_TRUE (false); // force error } } // delete entry by storage engine StorageEngine::instance ().deleteEntry (testEntry); // ensure entry is not in database ASSERT_FALSE (StorageEngine::instance ().entryExists (testEntry.getPublicName ())); { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.cut (testEntry); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } } TEST (kdbrestServicesStorageengineTest, EntryExistsCheck) { using namespace kdb; using namespace kdbrest::service; std::string testKey = "test/test/test/entry1"; Key testKeyAbs = Key (kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + testKey, KEY_VALUE, "testvalue", KEY_END); // ensure entry is not in database { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.cut (testKeyAbs); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } // create key { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.append (testKeyAbs); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } // make sure that entry cache is re-fetched (void)StorageEngine::instance ().getAllEntriesRef (true); // check if exists now ASSERT_TRUE (StorageEngine::instance ().entryExists (testKey)); // delete test key { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.lookup (testKeyAbs, KDB_O_POP); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } } TEST (kdbrestServicesStorageengineTest, GetEntryCheck) { using namespace kdb; using namespace kdbrest::service; std::string testKey = "test/test/test/entry1"; Key testKeyAbs = Key (kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + testKey, KEY_VALUE, "testvalue", KEY_END); // create key { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.append (testKeyAbs); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } // make sure that entry cache is re-fetched (void)StorageEngine::instance ().getAllEntriesRef (true); // find entry, check function try { kdbrest::model::Entry entry = StorageEngine::instance ().getEntry (testKey); ASSERT_TRUE (entry.isValid ()); ASSERT_EQ (entry.getName (), testKeyAbs.getName ()); ASSERT_EQ (entry.get<std::string> (), testKeyAbs.get<std::string> ()); } catch (kdbrest::exception::EntryNotFoundException & e) { ASSERT_TRUE (false); } // delete test key { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.lookup (testKeyAbs, KDB_O_POP); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } } TEST (kdbrestServicesStorageengineTest, CreateUserCheck) { using namespace kdb; using namespace kdbrest::model; using namespace kdbrest::service; std::string username = "test-username"; std::string passwordHash = "p455w0rdh45h"; std::string email = "random@email.org"; int rank = 2; long created_at = 123872923; User testUser (username); testUser.setPasswordHash (passwordHash); testUser.setEmail (email); testUser.setRank (rank); testUser.setCreatedAt (created_at); // ensure entry is not in database { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (testUser); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } // do storage StorageEngine::instance ().createUser (testUser); // ensure that entry has been saved { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); Key k = ks.lookup (testUser); if (k) { ASSERT_EQ (k.getName (), testUser.getName ()); ASSERT_EQ (k.get<std::string> (), passwordHash); ASSERT_TRUE (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_EMAIL)); ASSERT_TRUE (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_RANK)); ASSERT_TRUE (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_CREATEDAT)); ASSERT_EQ (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_EMAIL) .get<std::string> (), email); ASSERT_EQ (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_RANK).get<int> (), rank); ASSERT_EQ ( ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_CREATEDAT).get<long> (), created_at); } else { ASSERT_TRUE (false); // force error } } // delete entry after test { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (testUser); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } } TEST (kdbrestServicesStorageengineTest, UpdateUserCheck) { using namespace kdb; using namespace kdbrest::model; using namespace kdbrest::service; std::string username = "test-username"; std::string passwordHash = "p455w0rdh45h"; std::string email = "random@email.org"; int rank = 2; long created_at = 123872923; User testUser (username); testUser.setPasswordHash (passwordHash); testUser.setEmail (email); testUser.setRank (rank); testUser.setCreatedAt (created_at); // ensure entry is not in database { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (testUser); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } // force re-fetching of user cache (void)StorageEngine::instance ().getAllUsersRef (true); // do storage StorageEngine::instance ().createUser (testUser); // ensure that entry has been saved { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); Key k = ks.lookup (testUser); if (!k) { ASSERT_TRUE (false); // force error } } // change user data std::string newPasswordHash = "alskdjgasdlkj"; std::string newEmail = "new@email.org"; int newRank = 1; long newCreated_at = 1238799237; testUser.setPasswordHash (newPasswordHash); testUser.setEmail (newEmail); testUser.setRank (newRank); testUser.setCreatedAt (newCreated_at); StorageEngine::instance ().updateUser (testUser); // check that update has been successful { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); Key k = ks.lookup (testUser); if (k) { ASSERT_EQ (k.getName (), testUser.getName ()); ASSERT_EQ (k.get<std::string> (), newPasswordHash); ASSERT_TRUE (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_EMAIL)); ASSERT_TRUE (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_RANK)); ASSERT_TRUE (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_CREATEDAT)); ASSERT_EQ (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_EMAIL) .get<std::string> (), newEmail); ASSERT_EQ (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_RANK).get<int> (), newRank); ASSERT_EQ ( ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_CREATEDAT).get<long> (), newCreated_at); } else { ASSERT_TRUE (false); // force error } } // delete entry after test { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (testUser); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } } TEST (kdbrestServicesStorageengineTest, DeleteUserCheck) { using namespace kdb; using namespace kdbrest::model; using namespace kdbrest::service; std::string username = "test-username"; std::string passwordHash = "p455w0rdh45h"; std::string email = "random@email.org"; int rank = 2; long created_at = 123872923; User testUser (username); testUser.setPasswordHash (passwordHash); testUser.setEmail (email); testUser.setRank (rank); testUser.setCreatedAt (created_at); // ensure entry is not in database { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (testUser); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } // force re-fetching of user cache (void)StorageEngine::instance ().getAllUsersRef (true); // do storage StorageEngine::instance ().createUser (testUser); // ensure that entry has been saved { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); Key k = ks.lookup (testUser); if (k) { ASSERT_EQ (k.getName (), testUser.getName ()); ASSERT_EQ (k.get<std::string> (), passwordHash); ASSERT_TRUE (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_EMAIL)); ASSERT_TRUE (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_RANK)); ASSERT_TRUE (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_CREATEDAT)); ASSERT_EQ (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_EMAIL) .get<std::string> (), email); ASSERT_EQ (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_RANK).get<int> (), rank); ASSERT_EQ ( ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_CREATEDAT).get<long> (), created_at); } else { ASSERT_TRUE (false); // force error } } // delete user by storage engine StorageEngine::instance ().deleteUser (testUser); // ensure entry is not in database ASSERT_FALSE (StorageEngine::instance ().userExists (testUser.getUsername ())); { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (testUser); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } } TEST (kdbrestServicesStorageengineTest, UserExistsCheck) { using namespace kdb; using namespace kdbrest::service; std::string username = "test-username"; kdbrest::model::User user (username); // ensure entry is not in database { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (user); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } // force re-fetching of user cache (void)StorageEngine::instance ().getAllUsersRef (true); // check exists before creating key ASSERT_FALSE (StorageEngine::instance ().userExists (username)); // create key { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.append (user); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } // force re-fetching of user cache (void)StorageEngine::instance ().getAllUsersRef (true); // check if exists now ASSERT_TRUE (StorageEngine::instance ().userExists (username)); // delete test key { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (user); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } } TEST (kdbrestServicesStorageengineTest, GetUserCheck) { using namespace kdb; using namespace kdbrest::service; std::string username = "test-username"; std::string passwordHash = "p455w0rdh45h"; std::string email = "random@email.org"; int rank = 2; long created_at = 123872923; kdbrest::model::User user (username); user.setPasswordHash (passwordHash); user.setEmail (email); user.setRank (rank); user.setCreatedAt (created_at); // ensure entry is not in database { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (user); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } // force re-fetching of user cache (void)StorageEngine::instance ().getAllUsersRef (true); // check exists before creating key ASSERT_FALSE (StorageEngine::instance ().userExists (username)); // create key { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.append (user); ks.append (user.getSubkeys ()); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } // force re-fetching of user cache (void)StorageEngine::instance ().getAllUsersRef (true); // check if exists now ASSERT_TRUE (StorageEngine::instance ().userExists (username)); // find entry, check function kdbrest::model::User findUser = StorageEngine::instance ().getUser (username); ASSERT_TRUE (findUser.isValid ()); ASSERT_EQ (findUser.getName (), user.getName ()); ASSERT_EQ (findUser.getPasswordHash (), passwordHash); ASSERT_EQ (findUser.getEmail (), email); ASSERT_EQ (findUser.getRank (), rank); ASSERT_EQ (findUser.getCreatedAt (), created_at); // delete test key { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (user); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } } int main (int argc, char * argv[]) { testing::InitGoogleTest (&argc, argv); // initialize test config cppcms::json::value config = kdbrest::service::ConfigEngine::instance ().loadApplicationConfiguration (); (void)kdbrest::Config::instance ().initializeConfiguration (config); // force default config kdbrest::Config::instance ().setValue<std::string> ("kdb.path.configs", std::string (ELEKTRA_REST_DEFAULT_PATH_CONFIGS)); kdbrest::Config::instance ().setValue<std::string> ("kdb.path.users", std::string (ELEKTRA_REST_DEFAULT_PATH_USERS)); return RUN_ALL_TESTS (); }
23,292
9,470
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "ProfilerPrivatePCH.h" #include "SSearchBox.h" #define LOCTEXT_NAMESPACE "SFiltersAndPresets" struct SFiltersAndPresetsHelper { static const FSlateBrush* GetIconForGroup() { return FEditorStyle::GetBrush( TEXT( "Profiler.Misc.GenericGroup" ) ); } static const FSlateBrush* GetIconForStatType( const EProfilerSampleTypes::Type StatType ) { const FSlateBrush* HierarchicalTimeIcon = FEditorStyle::GetBrush( TEXT( "Profiler.Type.Hierarchical" ) ); const FSlateBrush* NumberIntIcon = FEditorStyle::GetBrush( TEXT( "Profiler.Type.NumberInt" ) ); const FSlateBrush* NumberFloatIcon = FEditorStyle::GetBrush( TEXT( "Profiler.Type.NumberFloat" ) ); const FSlateBrush* MemoryIcon = FEditorStyle::GetBrush( TEXT( "Profiler.Type.Memory" ) ); const FSlateBrush* const StatIcons[ EProfilerSampleTypes::InvalidOrMax ] = { HierarchicalTimeIcon, NumberIntIcon, NumberFloatIcon, MemoryIcon }; return StatIcons[ (int32)StatType ]; } }; /*----------------------------------------------------------------------------- Filter and presets tooltip -----------------------------------------------------------------------------*/ class SFiltersAndPresetsTooltip { const uint32 StatID; FProfilerSessionPtr ProfilerSession; public: SFiltersAndPresetsTooltip( const uint32 InStatID ) : StatID( InStatID ) { // TODO: At this moment only single profiler instance is supported. const int32 NumInstances = FProfilerManager::Get()->GetProfilerInstancesNum(); if( NumInstances == 1 ) { ProfilerSession = FProfilerManager::Get()->GetProfilerInstancesIterator().Value(); } } BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION TSharedRef<SToolTip> GetTooltip() { if( ProfilerSession.IsValid() ) { const TSharedRef<SGridPanel> ToolTipGrid = SNew(SGridPanel); int CurrentRowPos = 0; AddHeader( ToolTipGrid, CurrentRowPos ); AddDescription( ToolTipGrid, CurrentRowPos ); const FProfilerAggregatedStat* AggregatedPtr = ProfilerSession->GetAggregatedStat( StatID ); if( AggregatedPtr ) { AddValuesInformation( ToolTipGrid, CurrentRowPos, *AggregatedPtr ); AddCallsInformation( ToolTipGrid, CurrentRowPos, *AggregatedPtr ); } else { AddNoDataInformation( ToolTipGrid, CurrentRowPos ); } return SNew(SToolTip) [ ToolTipGrid ]; } else { return SNew(SToolTip) .Text( LOCTEXT("NotImplemented","Tooltip for multiple profiler instances has not been implemented yet") ); } } protected: void AddNoDataInformation( const TSharedRef<SGridPanel>& Grid, int32& RowPos ) { Grid->AddSlot( 0, RowPos ) .Padding( 2.0f ) .ColumnSpan( 3 ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.TooltipBold") ) .Text( LOCTEXT("NoStatData","There is no data for this stat") ) ]; RowPos++; } void AddHeader( const TSharedRef<SGridPanel>& Grid, int32& RowPos ) { const FString InstanceName = ProfilerSession->GetSessionType() == EProfilerSessionTypes::StatsFile ? FPaths::GetBaseFilename( ProfilerSession->GetName() ) : ProfilerSession->GetName(); Grid->AddSlot( 0, RowPos++ ) .Padding( 2.0f ) .ColumnSpan( 3 ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.TooltipBold") ) .Text( LOCTEXT("StatInstance","Stat information for profiler instance") ) ]; Grid->AddSlot( 0, RowPos++ ) .Padding( 2.0f ) .ColumnSpan( 3 ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .Text( FText::FromString(InstanceName) ) ]; AddSeparator( Grid, RowPos ); } void AddDescription( const TSharedRef<SGridPanel>& Grid, int32& RowPos ) { const FProfilerStat& ProfilerStat = ProfilerSession->GetMetaData()->GetStatByID( StatID ); const EProfilerSampleTypes::Type SampleType = ProfilerSession->GetMetaData()->GetSampleTypeForStatID( StatID ); const FSlateBrush* const StatIcon = SFiltersAndPresetsHelper::GetIconForStatType( SampleType ); Grid->AddSlot( 0, RowPos ) .Padding( 2.0f ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.TooltipBold") ) .Text( LOCTEXT("GroupDesc","Group:") ) ]; Grid->AddSlot( 1, RowPos ) .Padding( 2.0f ) .ColumnSpan( 2 ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .Text( FText::FromName(ProfilerStat.OwningGroup().Name() )) ]; RowPos++; Grid->AddSlot( 0, RowPos ) .Padding( 2.0f ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.TooltipBold") ) .Text( LOCTEXT("NameDesc","Name:") ) ]; Grid->AddSlot( 1, RowPos ) .Padding( 2.0f ) .ColumnSpan( 2 ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .Text( FText::FromName(ProfilerStat.Name()) ) ]; RowPos++; Grid->AddSlot( 0, RowPos ) .Padding( 2.0f ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.TooltipBold") ) .Text( LOCTEXT("TypeDesc","Type:") ) ]; Grid->AddSlot( 1, RowPos ) .Padding( 2.0f ) .ColumnSpan( 2 ) [ SNew(SHorizontalBox) +SHorizontalBox::Slot() .AutoWidth() [ SNew( SImage ) .Image( StatIcon ) ] +SHorizontalBox::Slot() .AutoWidth() .HAlign(HAlign_Left) .VAlign(VAlign_Center) [ SNew(STextBlock) .Text( FText::FromString(EProfilerSampleTypes::ToDescription(SampleType)) ) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) ] ]; RowPos++; AddSeparator( Grid, RowPos ); } void AddValuesInformation( const TSharedRef<SGridPanel>& Grid, int32& RowPos, const FProfilerAggregatedStat& Aggregated ) { Grid->AddSlot( 0, RowPos ) .Padding( 2.0f ) .ColumnSpan( 3 ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.TooltipBold") ) .Text( LOCTEXT("ValueDesc","Value") ) ]; RowPos++; Grid->AddSlot( 0, RowPos ) .Padding( 2.0f ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .Text(FText::Format(LOCTEXT("MinDesc", "Min: {0}"), FText::FromString(Aggregated.GetFormattedValue(FProfilerAggregatedStat::EMinValue)))) ]; Grid->AddSlot( 1, RowPos ) .Padding( 2.0f ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .Text(FText::Format(LOCTEXT("AvgDesc", "Avg: {0}"), FText::FromString(Aggregated.GetFormattedValue(FProfilerAggregatedStat::EAvgValue)))) ]; Grid->AddSlot( 2, RowPos ) .Padding( 2.0f ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .Text(FText::Format(LOCTEXT("MaxDesc", "Max: {0}"), FText::FromString(Aggregated.GetFormattedValue(FProfilerAggregatedStat::EMaxValue)))) ]; RowPos++; AddSeparator( Grid, RowPos ); } void AddCallsInformation( const TSharedRef<SGridPanel>& Grid, int32& RowPos, const FProfilerAggregatedStat& Aggregated ) { if( !Aggregated.HasCalls() ) { return; } Grid->AddSlot( 0, RowPos ) .Padding( 2.0f ) .ColumnSpan( 3 ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.TooltipBold") ) .Text(FText::Format(LOCTEXT("CallsFramesPctDesc", "Calls Frames with call: {0}"), FText::FromString(Aggregated.GetFormattedValue(FProfilerAggregatedStat::EFramesWithCallPct)))) ]; RowPos++; Grid->AddSlot( 0, RowPos ) .Padding( 2.0f ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .Text(FText::Format(LOCTEXT("MinDesc", "Min: {0}"), FText::FromString(Aggregated.GetFormattedValue(FProfilerAggregatedStat::EMinNumCalls)))) ]; Grid->AddSlot( 1, RowPos ) .Padding( 2.0f ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .Text(FText::Format(LOCTEXT("AvgDesc", "Avg: {0}"), FText::FromString(Aggregated.GetFormattedValue(FProfilerAggregatedStat::EAvgNumCalls)))) ]; Grid->AddSlot( 2, RowPos ) .Padding( 2.0f ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .Text(FText::Format(LOCTEXT("MaxDesc", "Max: {0}"), FText::FromString(Aggregated.GetFormattedValue(FProfilerAggregatedStat::EMaxNumCalls)))) ]; RowPos++; AddSeparator( Grid, RowPos ); } void AddSeparator( const TSharedRef<SGridPanel>& Grid, int32& RowPos ) { Grid->AddSlot( 0, RowPos++ ) .Padding( 2.0f ) .ColumnSpan( 3 ) [ SNew(SSeparator) .Orientation( Orient_Horizontal ) ]; } END_SLATE_FUNCTION_BUILD_OPTIMIZATION }; /*----------------------------------------------------------------------------- EStatGroupingOrSortingMode -----------------------------------------------------------------------------*/ FText EStatGroupingOrSortingMode::ToName( const Type StatGroupingOrSortingMode ) { switch( StatGroupingOrSortingMode ) { case GroupName: return LOCTEXT("GroupingOrSorting_Name_GroupName", "Group Name"); case StatName: return LOCTEXT("GroupingOrSorting_Name_StatName", "Stat Name"); case StatType: return LOCTEXT("GroupingOrSorting_Name_StatType", "Stat Type"); case StatValue: return LOCTEXT("GroupingOrSorting_Name_StatValue", "Stat Value"); default: return LOCTEXT("InvalidOrMax", "InvalidOrMax"); } } FText EStatGroupingOrSortingMode::ToDescription(const Type StatGroupingOrSortingMode) { switch( StatGroupingOrSortingMode ) { case GroupName: return LOCTEXT("GroupingOrSorting_Desc_GroupName", "Creates groups based on stat metadata groups"); case StatName: return LOCTEXT("GroupingOrSorting_Desc_StatName", "Creates one group for one letter"); case StatType: return LOCTEXT("GroupingOrSorting_Desc_StatType", "Creates one group for each stat type"); case StatValue: return LOCTEXT("GroupingOrSorting_Desc_StatValue", "Creates one group for each logarithmic range ie. 0.001 - 0.01, 0.01 - 0.1, 0.1 - 1.0, 1.0 - 10.0 etc"); default: return LOCTEXT("InvalidOrMax", "InvalidOrMax"); } } FName EStatGroupingOrSortingMode::ToBrushName( const Type StatGroupingOrSortingMode ) { switch( StatGroupingOrSortingMode ) { case GroupName: return TEXT("Profiler.FiltersAndPresets.GroupNameIcon"); case StatName: return TEXT("Profiler.FiltersAndPresets.StatNameIcon"); case StatType: return TEXT("Profiler.FiltersAndPresets.StatTypeIcon"); case StatValue: return TEXT("Profiler.FiltersAndPresets.StatValueIcon"); default: return NAME_None; } } /*----------------------------------------------------------------------------- SGroupAndStatTableRow -----------------------------------------------------------------------------*/ DECLARE_DELEGATE_RetVal_OneParam( bool, FShouldBeEnabledDelegate, const uint32 /*StatID*/ ); /** Widget that represents a table row in the groups and stats' tree control. Generates widgets for each column on demand. */ class SGroupAndStatTableRow : public STableRow< FGroupOrStatNodePtr > { public: SLATE_BEGIN_ARGS( SGroupAndStatTableRow ) {} /** Text to be highlighted. */ SLATE_ATTRIBUTE( FText, HighlightText ) SLATE_EVENT( FShouldBeEnabledDelegate, OnShouldBeEnabled ) SLATE_END_ARGS() public: /** * Construct this widget. Called by the SNew() Slate macro. * * @param InArgs - Declaration used by the SNew() macro to construct this widget. * @param InOwnerTableView - The owner table into which this row is being placed. */ BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION void Construct( const FArguments& InArgs, const TSharedRef<STableViewBase>& InOwnerTableView, const TSharedRef<FGroupOrStatNode>& InGroupOrStatNode ) { GroupOrStatNode = InGroupOrStatNode; OnShouldBeEnabled = InArgs._OnShouldBeEnabled; SetEnabled( TAttribute<bool>( this, &SGroupAndStatTableRow::HandleShouldBeEnabled ) ); const FSlateBrush* const IconForGroupOrStat = InGroupOrStatNode->IsGroup() ? SFiltersAndPresetsHelper::GetIconForGroup() : SFiltersAndPresetsHelper::GetIconForStatType( InGroupOrStatNode->GetStatType() ); const TSharedRef<SToolTip> Tooltip = InGroupOrStatNode->IsGroup() ? SNew(SToolTip) : SFiltersAndPresetsTooltip(InGroupOrStatNode->GetStatID()).GetTooltip(); ChildSlot [ SNew(SHorizontalBox) // Expander arrow. +SHorizontalBox::Slot() .AutoWidth() .HAlign(HAlign_Right) .VAlign(VAlign_Center) [ SNew( SExpanderArrow, SharedThis(this) ) ] // Icon to visualize group or stat type. +SHorizontalBox::Slot() .AutoWidth() .Padding( 0.0f, 0.0f, 8.0f, 0.0f ) [ SNew( SImage ) .Image( IconForGroupOrStat ) .ToolTip( Tooltip ) ] // Description text. +SHorizontalBox::Slot() .AutoWidth() .VAlign( VAlign_Center ) .HAlign( HAlign_Left ) .Padding( FMargin( 2.0f, 0.0f ) ) [ SNew( STextBlock ) .Text( this, &SGroupAndStatTableRow::GetText ) .HighlightText( InArgs._HighlightText ) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .ColorAndOpacity( this, &SGroupAndStatTableRow::GetColorAndOpacity ) ] +SHorizontalBox::Slot() .AutoWidth() .HAlign( HAlign_Center ) .VAlign( VAlign_Top ) .Padding( 0.0f, 1.0f, 0.0f, 0.0f ) [ SNew( SImage ) .Visibility( !InGroupOrStatNode->IsGroup() ? EVisibility::Visible : EVisibility::Collapsed ) .Image( FEditorStyle::GetBrush("Profiler.Tooltip.HintIcon10") ) .ToolTip( Tooltip ) ] ]; STableRow< FGroupOrStatNodePtr >::ConstructInternal( STableRow::FArguments() .ShowSelection(true), InOwnerTableView ); } END_SLATE_FUNCTION_BUILD_OPTIMIZATION /** * Called when Slate detects that a widget started to be dragged. * Usage: * A widget can ask Slate to detect a drag. * OnMouseDown() reply with FReply::Handled().DetectDrag( SharedThis(this) ). * Slate will either send an OnDragDetected() event or do nothing. * If the user releases a mouse button or leaves the widget before * a drag is triggered (maybe user started at the very edge) then no event will be * sent. * * @param InMyGeometry Widget geometry * @param InMouseEvent MouseMove that triggered the drag * */ virtual FReply OnDragDetected( const FGeometry& MyGeometry, const FPointerEvent& MouseEvent ) override { if( MouseEvent.IsMouseButtonDown( EKeys::LeftMouseButton )) { if( GroupOrStatNode->IsGroup() ) { // Add all stat IDs for the group. TArray<int32> StatIDs; const TArray<FGroupOrStatNodePtr>& FilteredChildren = GroupOrStatNode->GetFilteredChildren(); const int32 NumFilteredChildren = FilteredChildren.Num(); StatIDs.Reserve( NumFilteredChildren ); for( int32 Nx = 0; Nx < NumFilteredChildren; ++Nx ) { StatIDs.Add( FilteredChildren[Nx]->GetStatID() ); } return FReply::Handled().BeginDragDrop( FStatIDDragDropOp::NewGroup( StatIDs, GroupOrStatNode->GetName().GetPlainNameString() ) ); } else { return FReply::Handled().BeginDragDrop( FStatIDDragDropOp::NewSingle( GroupOrStatNode->GetStatID(), GroupOrStatNode->GetName().GetPlainNameString() ) ); } } return STableRow< FGroupOrStatNodePtr >::OnDragDetected(MyGeometry,MouseEvent); } protected: /** * @return a text which describes this table row, refers to both groups and stats */ FText GetText() const { FText Text = FText::GetEmpty(); if( GroupOrStatNode->IsGroup() ) { int32 NumDisplayedStats = 0; const TArray<FGroupOrStatNodePtr>& Children = GroupOrStatNode->GetChildren(); const int32 NumChildren = Children.Num(); for( int32 Nx = 0; Nx < NumChildren; ++Nx ) { const bool bIsStatTracked = FProfilerManager::Get()->IsStatTracked( Children[Nx]->GetStatID() ); if( bIsStatTracked ) { NumDisplayedStats ++; } } Text = FText::Format(LOCTEXT("GroupAndStat_GroupNodeTextFmt", "{0} ({1}) ({2})"), FText::FromName(GroupOrStatNode->GetName()), FText::AsNumber(GroupOrStatNode->GetChildren().Num()), FText::AsNumber(NumDisplayedStats)); } else { const bool bIsStatTracked = FProfilerManager::Get()->IsStatTracked( GroupOrStatNode->GetStatID() ); if(bIsStatTracked) { Text = FText::Format(LOCTEXT("GroupAndStat_GroupNodeTrackedTextFmt", "{0}*"), FText::FromName(GroupOrStatNode->GetName())); } else { Text = FText::FromName(GroupOrStatNode->GetName()); } } return Text; } /** * @return a color and opacity value used to draw this table row, refers to both groups and stats */ FSlateColor GetColorAndOpacity() const { const bool bIsStatTracked = FProfilerManager::Get()->IsStatTracked( GroupOrStatNode->GetStatID() ); const FSlateColor Color = bIsStatTracked ? FProfilerManager::Get()->GetColorForStatID( GroupOrStatNode->GetStatID() ) : FLinearColor::White; return Color; //FProfilerManager::GetSettings().GetColorForStat( FName StatName ) } /** * @return a font style which is used to draw this table row, refers to both groups and stats */ FSlateFontInfo GetFont() const { const bool bIsStatTracked = FProfilerManager::Get()->IsStatTracked( GroupOrStatNode->GetStatID() ); const FSlateFontInfo FontInfo = bIsStatTracked ? FEditorStyle::GetFontStyle("BoldFont") : FEditorStyle::GetFontStyle("NormalFont"); return FontInfo; } bool HandleShouldBeEnabled() const { bool bResult = false; if( GroupOrStatNode->IsGroup() ) { bResult = true; } else { if( OnShouldBeEnabled.IsBound() ) { bResult = OnShouldBeEnabled.Execute( GroupOrStatNode->GetStatID() ); } } return bResult; } /** The tree item associated with this row of data. */ FGroupOrStatNodePtr GroupOrStatNode; FShouldBeEnabledDelegate OnShouldBeEnabled; }; /*----------------------------------------------------------------------------- SFiltersAndPresets -----------------------------------------------------------------------------*/ SFiltersAndPresets::SFiltersAndPresets() : GroupingMode( EStatGroupingOrSortingMode::GroupName ) , SortingMode( EStatGroupingOrSortingMode::StatName ) , bExpansionSaved( false ) { FMemory::Memset( bStatTypeIsVisible, 1 ); } SFiltersAndPresets::~SFiltersAndPresets() { // Remove ourselves from the profiler manager. if( FProfilerManager::Get().IsValid() ) { FProfilerManager::Get()->OnRequestFilterAndPresetsUpdate().RemoveAll( this ); } } BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION void SFiltersAndPresets::Construct( const FArguments& InArgs ) { ChildSlot [ SNew(SVerticalBox) // Search box +SVerticalBox::Slot() .VAlign(VAlign_Center) .AutoHeight() [ SNew( SBorder ) .BorderImage( FEditorStyle::GetBrush("ToolPanel.GroupBorder") ) .Padding( 2.0f ) [ SNew(SVerticalBox) // Search box +SVerticalBox::Slot() .VAlign(VAlign_Center) .Padding( 2.0f ) .AutoHeight() [ SAssignNew( GroupAndStatSearchBox, SSearchBox ) .HintText( LOCTEXT("SearchBoxHint", "Search stats or groups") ) .OnTextChanged( this, &SFiltersAndPresets::SearchBox_OnTextChanged ) .IsEnabled( this, &SFiltersAndPresets::SearchBox_IsEnabled ) .ToolTipText( LOCTEXT("FilterSearchHint", "Type here to search stats or group") ) ] // Group by and Sort By +SVerticalBox::Slot() .VAlign(VAlign_Center) .Padding( 2.0f ) .AutoHeight() [ SNew(SHorizontalBox) +SHorizontalBox::Slot() .FillWidth( 1.0f ) .VAlign(VAlign_Center) [ SNew(STextBlock) .Text( LOCTEXT("GroupByText", "Group by") ) ] +SHorizontalBox::Slot() .FillWidth( 2.0f ) .VAlign(VAlign_Center) [ SAssignNew( GroupByComboBox, SComboBox< TSharedPtr<EStatGroupingOrSortingMode::Type> > ) .ToolTipText( this, &SFiltersAndPresets::GroupBy_GetSelectedTooltipText ) .OptionsSource( &GroupByOptionsSource ) .OnSelectionChanged( this, &SFiltersAndPresets::GroupBy_OnSelectionChanged ) .OnGenerateWidget( this, &SFiltersAndPresets::GroupBy_OnGenerateWidget ) [ SNew( STextBlock ) .Text( this, &SFiltersAndPresets::GroupBy_GetSelectedText ) ] ] ] // Sort by +SVerticalBox::Slot() .VAlign(VAlign_Center) .Padding( 2.0f ) .AutoHeight() [ SNew(SHorizontalBox) +SHorizontalBox::Slot() .FillWidth( 1.0f ) .VAlign(VAlign_Center) [ SNew(STextBlock) .Text( LOCTEXT("SortByText", "Sort by") ) ] +SHorizontalBox::Slot() .FillWidth( 2.0f ) .VAlign(VAlign_Center) [ SAssignNew( SortByComboBox, SComboBox< TSharedPtr<EStatGroupingOrSortingMode::Type> > ) .OptionsSource( &SortByOptionsSource ) .OnSelectionChanged( this, &SFiltersAndPresets::SortBy_OnSelectionChanged ) .OnGenerateWidget( this, &SFiltersAndPresets::SortBy_OnGenerateWidget ) [ SNew( STextBlock ) .Text( this, &SFiltersAndPresets::SortBy_GetSelectedText ) ] ] ] // Check boxes for: HierarchicalTime NumberFloat, NumberInt, Memory +SVerticalBox::Slot() .VAlign(VAlign_Center) .Padding( 2.0f ) .AutoHeight() [ SNew(SHorizontalBox) +SHorizontalBox::Slot() .Padding( FMargin(0.0f,0.0f,1.0f,0.0f) ) .FillWidth( 1.0f ) [ GetToggleButtonForStatType( EProfilerSampleTypes::HierarchicalTime ) ] +SHorizontalBox::Slot() .Padding( FMargin(1.0f,0.0f,1.0f,0.0f) ) .FillWidth( 1.0f ) [ GetToggleButtonForStatType( EProfilerSampleTypes::NumberFloat ) ] +SHorizontalBox::Slot() .Padding( FMargin(1.0f,0.0f,1.0f,0.0f) ) .FillWidth( 1.0f ) [ GetToggleButtonForStatType( EProfilerSampleTypes::NumberInt ) ] +SHorizontalBox::Slot() .Padding( FMargin(1.0f,0.0f,0.0f,0.0f) ) .FillWidth( 1.0f ) [ GetToggleButtonForStatType( EProfilerSampleTypes::Memory ) ] ] ] ] // Stat groups tree +SVerticalBox::Slot() .FillHeight( 1.0f ) .Padding(0.0f, 6.0f, 0.0f, 0.0f) [ SNew( SBorder ) .BorderImage( FEditorStyle::GetBrush("ToolPanel.GroupBorder") ) .Padding( 2.0f ) [ SAssignNew( GroupAndStatTree, STreeView< FGroupOrStatNodePtr > ) .SelectionMode(ESelectionMode::Single) .TreeItemsSource( &FilteredGroupNodes ) .OnGetChildren( this, &SFiltersAndPresets::GroupAndStatTree_OnGetChildren ) .OnGenerateRow( this, &SFiltersAndPresets::GroupAndStatTree_OnGenerateRow ) .OnMouseButtonDoubleClick( this, &SFiltersAndPresets::GroupAndStatTree_OnMouseButtonDoubleClick ) //.OnSelectionChanged( this, &SFiltersAndPresets::GroupAndStatTree_OnSelectionChanged ) .ItemHeight( 12 ) ] ] ]; // Register ourselves with the profiler manager. FProfilerManager::Get()->OnRequestFilterAndPresetsUpdate().AddSP( this, &SFiltersAndPresets::ProfilerManager_OnRequestFilterAndPresetsUpdate ); // Create the search filters: text based, stat type based etc. // @TODO: HandleItemToStringArray should be moved somewhere else GroupAndStatTextFilter = MakeShareable( new FGroupAndStatTextFilter( FGroupAndStatTextFilter::FItemToStringArray::CreateSP( this, &SFiltersAndPresets::HandleItemToStringArray ) ) ); GroupAndStatFilters = MakeShareable( new FGroupAndStatFilterCollection() ); GroupAndStatFilters->Add( GroupAndStatTextFilter ); CreateGroupByOptionsSources(); RecreateSortByOptionsSources(); } void SFiltersAndPresets::ProfilerManager_OnRequestFilterAndPresetsUpdate() { auto It = FProfilerManager::Get()->GetProfilerInstancesIterator(); UpdateGroupAndStatTree(It.Value()); } void SFiltersAndPresets::UpdateGroupAndStatTree( const FProfilerSessionPtr InProfilerSession ) { const bool bRebuild = InProfilerSession != ProfilerSession; if( bRebuild ) { StatNodesMap.Empty( StatNodesMap.Num() ); } ProfilerSession = InProfilerSession; const FProfilerStatMetaDataRef StatMetaData = ProfilerSession->GetMetaData(); // Create all stat nodes. for( auto It = StatMetaData->GetStatIterator(); It; ++It ) { const FProfilerStat& ProfilerStat = *It.Value(); const FName StatName = ProfilerStat.Name(); FGroupOrStatNodePtr* StatPtr = StatNodesMap.Find( StatName ); if( !StatPtr ) { StatPtr = &StatNodesMap.Add( StatName, MakeShareable( new FGroupOrStatNode( ProfilerStat.OwningGroup().Name(), StatName, ProfilerStat.ID(), ProfilerStat.Type() ) ) ); } // Update stat value ? } // Create groups, sort stats within the group and apply filtering. CreateGroups(); SortStats(); ApplyFiltering(); } void SFiltersAndPresets::CreateGroups() { // Creates groups based on stat metadata groups. TMap< FName, FGroupOrStatNodePtr > GroupNodeSet; if( GroupingMode == EStatGroupingOrSortingMode::GroupName ) { for( auto It = StatNodesMap.CreateIterator(); It; ++It ) { const FGroupOrStatNodePtr& StatNodePtr = It.Value(); const FName GroupName = StatNodePtr->GetMetaGropName(); FGroupOrStatNodePtr* GroupPtr = GroupNodeSet.Find( GroupName ); if( !GroupPtr ) { GroupPtr = &GroupNodeSet.Add( GroupName, MakeShareable(new FGroupOrStatNode( GroupName )) ); } (*GroupPtr)->AddChildAndSetGroupPtr( StatNodePtr ); } } // Creates one group for each stat type. else if( GroupingMode == EStatGroupingOrSortingMode::StatType ) { for( auto It = StatNodesMap.CreateIterator(); It; ++It ) { const FGroupOrStatNodePtr& StatNodePtr = It.Value(); const FName GroupName = *EProfilerSampleTypes::ToName( StatNodePtr->GetStatType() ); FGroupOrStatNodePtr* GroupPtr = GroupNodeSet.Find( GroupName ); if( !GroupPtr ) { GroupPtr = &GroupNodeSet.Add( GroupName, MakeShareable(new FGroupOrStatNode( GroupName )) ); } (*GroupPtr)->AddChildAndSetGroupPtr( StatNodePtr ); } } // Creates one group for each logarithmic range ie. 0.001 - 0.01, 0.01 - 0.1, 0.1 - 1.0, 1.0 - 10.0 etc. else if( GroupingMode == EStatGroupingOrSortingMode::StatValue ) { // TODO: } // Creates one group for one letter. else if( GroupingMode == EStatGroupingOrSortingMode::StatName ) { for( auto It = StatNodesMap.CreateIterator(); It; ++It ) { const FGroupOrStatNodePtr& StatNodePtr = It.Value(); const FName GroupName = *StatNodePtr->GetName().GetPlainNameString().Left(1); FGroupOrStatNodePtr* GroupPtr = GroupNodeSet.Find( GroupName ); if( !GroupPtr ) { GroupPtr = &GroupNodeSet.Add( GroupName, MakeShareable(new FGroupOrStatNode( GroupName )) ); } (*GroupPtr)->AddChildAndSetGroupPtr( StatNodePtr ); } } GroupNodeSet.GenerateValueArray( GroupNodes ); // Sort by a fake group name. GroupNodes.Sort( FGroupAndStatSorting::ByStatName() ); } void SFiltersAndPresets::SortStats() { const int32 NumGroups = GroupNodes.Num(); // Sorts stats inside group by a group name. if( SortingMode == EStatGroupingOrSortingMode::GroupName ) { for( int32 ID = 0; ID < NumGroups; ++ID ) { GroupNodes[ID]->SortChildren( FGroupAndStatSorting::ByGroupName() ); } } // Sorts stats inside group by a stat type. else if( SortingMode == EStatGroupingOrSortingMode::StatType ) { for( int32 ID = 0; ID < NumGroups; ++ID ) { GroupNodes[ID]->SortChildren( FGroupAndStatSorting::ByStatType() ); } } // Sorts stats inside group by a stat value. else if( SortingMode == EStatGroupingOrSortingMode::StatValue ) { } // Sorts stats inside group by a stat name. else if( SortingMode == EStatGroupingOrSortingMode::StatName ) { for( int32 ID = 0; ID < NumGroups; ++ID ) { GroupNodes[ID]->SortChildren( FGroupAndStatSorting::ByStatName() ); } } } void SFiltersAndPresets::ApplyFiltering() { FilteredGroupNodes.Reset(); // Apply filter to all groups and its children. const int32 NumGroups = GroupNodes.Num(); for( int32 ID = 0; ID < NumGroups; ++ID ) { FGroupOrStatNodePtr& GroupPtr = GroupNodes[ID]; GroupPtr->ClearFilteredChildren(); const bool bIsGroupVisible = GroupAndStatFilters->PassesAllFilters( GroupPtr ); const TArray<FGroupOrStatNodePtr>& GroupChildren = GroupPtr->GetChildren(); const int32 NumChildren = GroupChildren.Num(); int32 NumVisibleChildren = 0; for( int32 Cx = 0; Cx < NumChildren; ++Cx ) { // Add a child. const FGroupOrStatNodePtr& StatPtr = GroupChildren[Cx]; const bool bIsChildVisible = GroupAndStatFilters->PassesAllFilters( StatPtr ) && bStatTypeIsVisible[StatPtr->GetStatType()]; if( bIsChildVisible ) { GroupPtr->AddFilteredChild( StatPtr ); } NumVisibleChildren += bIsChildVisible ? 1 : 0; } if( bIsGroupVisible || NumVisibleChildren>0 ) { // Add a group. FilteredGroupNodes.Add( GroupPtr ); GroupPtr->bForceExpandGroupNode = true; } else { GroupPtr->bForceExpandGroupNode = false; } } // Only expand group and stat nodes if we have a text filter. const bool bNonEmptyTextFilter = !GroupAndStatTextFilter->GetRawFilterText().IsEmpty(); if( bNonEmptyTextFilter ) { if( !bExpansionSaved ) { ExpandedNodes.Empty(); GroupAndStatTree->GetExpandedItems( ExpandedNodes ); bExpansionSaved = true; } for( int32 Fx = 0; Fx < FilteredGroupNodes.Num(); Fx++ ) { const FGroupOrStatNodePtr& GroupPtr = FilteredGroupNodes[Fx]; GroupAndStatTree->SetItemExpansion( GroupPtr, GroupPtr->bForceExpandGroupNode ); } } else { if( bExpansionSaved ) { // Restore previously expanded nodes when the text filter is disabled. GroupAndStatTree->ClearExpandedItems(); for( auto It = ExpandedNodes.CreateConstIterator(); It; ++It ) { GroupAndStatTree->SetItemExpansion( *It, true ); } bExpansionSaved = false; } } // Request tree refresh GroupAndStatTree->RequestTreeRefresh(); } void SFiltersAndPresets::HandleItemToStringArray( const FGroupOrStatNodePtr& GroupOrStatNodePtr, TArray< FString >& out_SearchStrings ) const { // Add group or stat name. out_SearchStrings.Add( GroupOrStatNodePtr->GetName().GetPlainNameString() ); } void SFiltersAndPresets::CreateGroupByOptionsSources() { GroupByOptionsSource.Reset( 4 ); // Must be added in order of elements in the EStatGroupingOrSortingMode. GroupByOptionsSource.Add( MakeShareable( new EStatGroupingOrSortingMode::Type( EStatGroupingOrSortingMode::GroupName ) ) ); GroupByOptionsSource.Add( MakeShareable( new EStatGroupingOrSortingMode::Type( EStatGroupingOrSortingMode::StatName ) ) ); GroupByOptionsSource.Add( MakeShareable( new EStatGroupingOrSortingMode::Type( EStatGroupingOrSortingMode::StatType ) ) ); //GroupByOptionsSource.Add( MakeShareable( new EStatGroupingOrSortingMode::Type( EStatGroupingOrSortingMode::StatValue ) ) ); GroupByComboBox->SetSelectedItem( GroupByOptionsSource[EStatGroupingOrSortingMode::GroupName] ); GroupByComboBox->RefreshOptions(); } void SFiltersAndPresets::RecreateSortByOptionsSources() { SortByOptionsSource.Reset( 4 ); // Must be added in order of elements in the EStatGroupingOrSortingMode. SortByOptionsSource.Add( MakeShareable( new EStatGroupingOrSortingMode::Type( EStatGroupingOrSortingMode::GroupName ) ) ); SortByOptionsSource.Add( MakeShareable( new EStatGroupingOrSortingMode::Type( EStatGroupingOrSortingMode::StatName ) ) ); SortByOptionsSource.Add( MakeShareable( new EStatGroupingOrSortingMode::Type( EStatGroupingOrSortingMode::StatType ) ) ); //SortByOptionsSource.Add( MakeShareable( new EStatGroupingOrSortingMode::Type( EStatGroupingOrSortingMode::StatValue ) ) ); // @TODO: Remove useless stat sorting ie: when grouped by group name, sorting by group name doesn't change anything. // Select default sorting mode based on the grouping mode. if( GroupingMode == EStatGroupingOrSortingMode::GroupName ) { SortingMode = EStatGroupingOrSortingMode::StatName; SortByComboBox->SetSelectedItem( SortByOptionsSource[SortingMode] ); SortByOptionsSource.RemoveAtSwap( (int32)GroupingMode ); } else if( GroupingMode == EStatGroupingOrSortingMode::StatName ) { SortingMode = EStatGroupingOrSortingMode::StatName; SortByComboBox->SetSelectedItem( SortByOptionsSource[SortingMode] ); } else if( GroupingMode == EStatGroupingOrSortingMode::StatType ) { SortingMode = EStatGroupingOrSortingMode::StatName; SortByComboBox->SetSelectedItem( SortByOptionsSource[SortingMode] ); } else if( GroupingMode == EStatGroupingOrSortingMode::StatValue ) { // TODO: } SortByComboBox->RefreshOptions(); } TSharedRef<SWidget> SFiltersAndPresets::GetToggleButtonForStatType( const EProfilerSampleTypes::Type StatType ) { return SNew( SCheckBox ) .Style( FEditorStyle::Get(), "ToggleButtonCheckbox" ) .HAlign( HAlign_Center ) .Padding( 2.0f ) .OnCheckStateChanged( this, &SFiltersAndPresets::FilterByStatType_OnCheckStateChanged, StatType ) .IsChecked( this, &SFiltersAndPresets::FilterByStatType_IsChecked, StatType ) .ToolTipText( FText::FromString(EProfilerSampleTypes::ToDescription( StatType )) ) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .VAlign( VAlign_Center ) [ SNew(SImage) .Image( SFiltersAndPresetsHelper::GetIconForStatType( StatType ) ) ] +SHorizontalBox::Slot() .Padding(2.0f, 0.0f, 0.0f, 0.0f) .VAlign( VAlign_Center ) [ SNew( STextBlock ) .Text( FText::FromString(EProfilerSampleTypes::ToName( StatType )) ) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Caption") ) ] ]; } void SFiltersAndPresets::FilterByStatType_OnCheckStateChanged( ECheckBoxState NewRadioState, const EProfilerSampleTypes::Type InStatType ) { bStatTypeIsVisible[InStatType] = NewRadioState == ECheckBoxState::Checked; ApplyFiltering(); } ECheckBoxState SFiltersAndPresets::FilterByStatType_IsChecked( const EProfilerSampleTypes::Type InStatType ) const { return bStatTypeIsVisible[InStatType] ? ECheckBoxState::Checked : ECheckBoxState::Unchecked; } /*----------------------------------------------------------------------------- GroupAndStatTree -----------------------------------------------------------------------------*/ TSharedRef< ITableRow > SFiltersAndPresets::GroupAndStatTree_OnGenerateRow( FGroupOrStatNodePtr GroupOrStatNode, const TSharedRef< STableViewBase >& OwnerTable ) { TSharedRef< ITableRow > TableRow = SNew(SGroupAndStatTableRow, OwnerTable, GroupOrStatNode.ToSharedRef()) .OnShouldBeEnabled( this, &SFiltersAndPresets::GroupAndStatTableRow_ShouldBeEnabled ) .HighlightText( this, &SFiltersAndPresets::GroupAndStatTableRow_GetHighlightText ); return TableRow; } void SFiltersAndPresets::GroupAndStatTree_OnGetChildren( FGroupOrStatNodePtr InParent, TArray< FGroupOrStatNodePtr >& out_Children ) { out_Children = InParent->GetFilteredChildren(); } void SFiltersAndPresets::GroupAndStatTree_OnMouseButtonDoubleClick( FGroupOrStatNodePtr GroupOrStatNode ) { // @TODO: Add mechanism which will synchronize displayed stats between: GraphPanel, FilterAndPresets and ProfilerManager if( !GroupOrStatNode->IsGroup() ) { const bool bIsStatTracked = FProfilerManager::Get()->IsStatTracked( GroupOrStatNode->GetStatID() ); if( !bIsStatTracked ) { // Add a new graph. FProfilerManager::Get()->TrackStat( GroupOrStatNode->GetStatID() ); } else { // Remove a graph FProfilerManager::Get()->UntrackStat( GroupOrStatNode->GetStatID() ); } } else { const bool bIsGroupExpanded = GroupAndStatTree->IsItemExpanded( GroupOrStatNode ); GroupAndStatTree->SetItemExpansion( GroupOrStatNode, !bIsGroupExpanded ); } } FText SFiltersAndPresets::GroupAndStatTableRow_GetHighlightText() const { return GroupAndStatSearchBox->GetText(); } bool SFiltersAndPresets::GroupAndStatTableRow_ShouldBeEnabled( const uint32 StatID ) const { return ProfilerSession->GetAggregatedStat( StatID ) != nullptr; } /*----------------------------------------------------------------------------- SearchBox -----------------------------------------------------------------------------*/ void SFiltersAndPresets::SearchBox_OnTextChanged( const FText& InFilterText ) { GroupAndStatTextFilter->SetRawFilterText( InFilterText ); GroupAndStatSearchBox->SetError( GroupAndStatTextFilter->GetFilterErrorText() ); ApplyFiltering(); } bool SFiltersAndPresets::SearchBox_IsEnabled() const { return StatNodesMap.Num() > 0; } /*----------------------------------------------------------------------------- GroupBy -----------------------------------------------------------------------------*/ void SFiltersAndPresets::GroupBy_OnSelectionChanged( TSharedPtr<EStatGroupingOrSortingMode::Type> NewGroupingMode, ESelectInfo::Type SelectInfo ) { if( SelectInfo != ESelectInfo::Direct ) { GroupingMode = *NewGroupingMode; // Create groups, sort stats within the group and apply filtering. CreateGroups(); SortStats(); ApplyFiltering(); RecreateSortByOptionsSources(); } } TSharedRef<SWidget> SFiltersAndPresets::GroupBy_OnGenerateWidget( TSharedPtr<EStatGroupingOrSortingMode::Type> InGroupingMode ) const { return SNew( STextBlock ) .Text( EStatGroupingOrSortingMode::ToName( *InGroupingMode ) ) .ToolTipText( EStatGroupingOrSortingMode::ToDescription( *InGroupingMode ) ); } FText SFiltersAndPresets::GroupBy_GetSelectedText() const { return EStatGroupingOrSortingMode::ToName( GroupingMode ); } FText SFiltersAndPresets::GroupBy_GetSelectedTooltipText() const { return EStatGroupingOrSortingMode::ToDescription( GroupingMode ); } /*----------------------------------------------------------------------------- SortBy -----------------------------------------------------------------------------*/ void SFiltersAndPresets::SortBy_OnSelectionChanged( TSharedPtr<EStatGroupingOrSortingMode::Type> NewSortingMode, ESelectInfo::Type SelectInfo ) { if( SelectInfo != ESelectInfo::Direct ) { SortingMode = *NewSortingMode; // Create groups, sort stats within the group and apply filtering. SortStats(); ApplyFiltering(); } } TSharedRef<SWidget> SFiltersAndPresets::SortBy_OnGenerateWidget( TSharedPtr<EStatGroupingOrSortingMode::Type> InSortingMode ) const { return SNew( STextBlock ) .Text( EStatGroupingOrSortingMode::ToName( *InSortingMode ) ) .ToolTipText( EStatGroupingOrSortingMode::ToDescription( *InSortingMode ) ); } FText SFiltersAndPresets::SortBy_GetSelectedText() const { return EStatGroupingOrSortingMode::ToName( SortingMode ); } #undef LOCTEXT_NAMESPACE
37,939
14,598
#include <iostream> #include <sstream> #include <cstdio> #include <cmath> #include <vector> #include <string> #include <algorithm> #include <map> #include <set> #include <queue> #define FOR(idx, begin, end) for(int idx = (int)(begin); idx < (int)(end); ++idx) #ifdef _DEBUG #define DMP(x) cerr << #x << ": " << x << "\n" #else #define DMP(x) ((void)0) #endif using namespace std; typedef long long lint; const int MOD = 100000007; const int INF = 1 << 29; const double EPS = 1e-9; int main() { cin.tie(0); lint X, Y, Z, K; cin >> X >> Y >> Z >> K; vector<lint> A(X), B(Y), C(Z), ans(K); FOR(i, 0, X)cin >> A[i]; FOR(i, 0, Y)cin >> B[i]; FOR(i, 0, Z)cin >> C[i]; sort(A.begin(), A.end(), greater<lint>()); sort(B.begin(), B.end(), greater<lint>()); sort(C.begin(), C.end(), greater<lint>()); FOR(a,0,X)FOR(b,0,Y)FOR(c,0,Z){ if ((a + 1)*(b + 1)*(c+1)<=K) ans.emplace_back(A[a] + B[b] + C[c]); } sort(ans.begin(), ans.end(), greater<lint>()); FOR(i, 0, K) cout << ans[i] << "\n"; return 0; }
1,018
491
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/developer/debug/zxdb/symbols/dwarf_lang.h" namespace zxdb { bool DwarfLangIsCFamily(DwarfLang lang) { // clang-format off return lang == DwarfLang::kC89 || lang == DwarfLang::kC || lang == DwarfLang::kCpp || lang == DwarfLang::kC99 || lang == DwarfLang::kObjC || lang == DwarfLang::kObjCpp || lang == DwarfLang::kCpp03 || lang == DwarfLang::kCpp11 || lang == DwarfLang::kC11 || lang == DwarfLang::kCpp14; // clang-format on } const char* DwarfLangToString(DwarfLang lang) { // clang-format off switch (lang) { case DwarfLang::kNone: return "None"; case DwarfLang::kC89: return "C89"; case DwarfLang::kC: return "C"; case DwarfLang::kAda83: return "Ada83"; case DwarfLang::kCpp: return "C++"; case DwarfLang::kCobol74: return "Cobol74"; case DwarfLang::kCobol85: return "Cobol85"; case DwarfLang::kFortran77: return "Fortran77"; case DwarfLang::kFortran90: return "Fortran90"; case DwarfLang::kPascal83: return "Pascal83"; case DwarfLang::kModula2: return "Modula2"; case DwarfLang::kJava: return "Java"; case DwarfLang::kC99: return "C99"; case DwarfLang::kAda95: return "Ada95"; case DwarfLang::kFortran95: return "Fortran95"; case DwarfLang::kPLI: return "PLI"; case DwarfLang::kObjC: return "ObjC"; case DwarfLang::kObjCpp: return "ObjC++"; case DwarfLang::kUPC: return "UPC"; case DwarfLang::kD: return "D"; case DwarfLang::kPython: return "Python"; case DwarfLang::kOpenCL: return "OpenCL"; case DwarfLang::kGo: return "Go"; case DwarfLang::kModula3: return "Modula3"; case DwarfLang::kHaskell: return "Haskell"; case DwarfLang::kCpp03: return "C++03"; case DwarfLang::kCpp11: return "C++11"; case DwarfLang::kOCaml: return "OCaml"; case DwarfLang::kRust: return "Rust"; case DwarfLang::kC11: return "C11"; case DwarfLang::kSwift: return "Swift"; case DwarfLang::kJulia: return "Julia"; case DwarfLang::kDylan: return "Dylan"; case DwarfLang::kCpp14: return "C++14"; case DwarfLang::kFortran03: return "Fortran03"; case DwarfLang::kFortran08: return "Fortran08"; case DwarfLang::kRenderScript: return "RenderScript"; case DwarfLang::kBLISS: return "BLISS"; default: return "<Unknown>"; } // clang-format on } } // namespace zxdb
2,569
1,095
#include <babylon/gizmos/plane_drag_gizmo.h> #include <babylon/babylon_stl_util.h> #include <babylon/engines/scene.h> #include <babylon/gizmos/position_gizmo.h> #include <babylon/lights/hemispheric_light.h> #include <babylon/materials/standard_material.h> #include <babylon/meshes/builders/mesh_builder_options.h> #include <babylon/meshes/builders/plane_builder.h> #include <babylon/meshes/instanced_mesh.h> #include <babylon/meshes/mesh.h> #include <babylon/meshes/transform_node.h> namespace BABYLON { TransformNodePtr PlaneDragGizmo::_CreatePlane(Scene* scene, const StandardMaterialPtr& material) { auto plane = TransformNode::New("plane", scene); // make sure plane is double sided PlaneOptions options; options.width = 0.1375f; options.height = 0.1375f; options.sideOrientation = 2u; auto dragPlane = PlaneBuilder::CreatePlane("dragPlane", options, scene); dragPlane->material = material; dragPlane->parent = plane.get(); return plane; } PlaneDragGizmo::PlaneDragGizmo(const Vector3& dragPlaneNormal, const Color3& color, const UtilityLayerRendererPtr& iGizmoLayer, PositionGizmo* parent) : Gizmo{iGizmoLayer} , snapDistance{0.f} , isEnabled{this, &PlaneDragGizmo::get_isEnabled, &PlaneDragGizmo::set_isEnabled} , _pointerObserver{nullptr} , _gizmoMesh{nullptr} , _coloredMaterial{nullptr} , _hoverMaterial{nullptr} , _disableMaterial{nullptr} , _isEnabled{false} , _parent{nullptr} , _dragging{false} , tmpSnapEvent{SnapEvent{0.f}} { _parent = parent; // Create Material _coloredMaterial = StandardMaterial::New("", iGizmoLayer->utilityLayerScene.get()); _coloredMaterial->diffuseColor = color; _coloredMaterial->specularColor = color.subtract(Color3(0.1f, 0.1f, 0.1f)); _hoverMaterial = StandardMaterial::New("", iGizmoLayer->utilityLayerScene.get()); _hoverMaterial->diffuseColor = Color3::Yellow(); _disableMaterial = StandardMaterial::New("", gizmoLayer->utilityLayerScene.get()); _disableMaterial->diffuseColor = Color3::Gray(); _disableMaterial->alpha = 0.4f; // Build plane mesh on root node _gizmoMesh = PlaneDragGizmo::_CreatePlane(gizmoLayer->utilityLayerScene.get(), _coloredMaterial); _gizmoMesh->lookAt(_rootMesh->position().add(dragPlaneNormal)); _gizmoMesh->scaling().scaleInPlace(1.f / 3.f); _gizmoMesh->parent = _rootMesh.get(); currentSnapDragDistance = 0.f; // Add dragPlaneNormal drag behavior to handle events when the gizmo is dragged PointerDragBehaviorOptions options; options.dragPlaneNormal = dragPlaneNormal; dragBehavior = std::make_shared<PointerDragBehavior>(options); dragBehavior->moveAttached = false; // _rootMesh->addBehavior(dragBehavior); dragBehavior->onDragObservable.add([this](DragMoveEvent* event, EventState& /*es*/) -> void { if (attachedNode()) { _handlePivot(); // Keep world translation and use it to update world transform // if the node has parent, the local transform properties (position, rotation, scale) // will be recomputed in _matrixChanged function // Snapping logic if (snapDistance == 0.f) { attachedNode()->getWorldMatrix().addTranslationFromFloats(event->delta.x, event->delta.y, event->delta.z); } else { currentSnapDragDistance += event->dragDistance; if (std::abs(currentSnapDragDistance) > snapDistance) { auto dragSteps = std::floor(std::abs(currentSnapDragDistance) / snapDistance); currentSnapDragDistance = std::fmod(currentSnapDragDistance, snapDistance); event->delta.normalizeToRef(tmpVector); tmpVector.scaleInPlace(snapDistance * dragSteps); attachedNode()->getWorldMatrix().addTranslationFromFloats(tmpVector.x, tmpVector.y, tmpVector.z); tmpSnapEvent.snapDistance = snapDistance * dragSteps; onSnapObservable.notifyObservers(&tmpSnapEvent); } } _matrixChanged(); } }); dragBehavior->onDragStartObservable.add( [this](DragStartOrEndEvent* /*evt*/, EventState& /*es*/) -> void { _dragging = true; }); dragBehavior->onDragEndObservable.add( [this](DragStartOrEndEvent* /*evt*/, EventState& /*es*/) -> void { _dragging = false; }); auto light = gizmoLayer->_getSharedGizmoLight(); light->includedOnlyMeshes = stl_util::concat(light->includedOnlyMeshes(), _rootMesh->getChildMeshes(false)); const auto toMeshArray = [](const std::vector<AbstractMeshPtr>& meshes) -> std::vector<MeshPtr> { std::vector<MeshPtr> meshArray; meshArray.reserve(meshes.size()); for (const auto& mesh : meshes) { meshArray.emplace_back(std::static_pointer_cast<Mesh>(mesh)); } return meshArray; }; _cache.gizmoMeshes = toMeshArray(_gizmoMesh->getChildMeshes()); _cache.colliderMeshes = toMeshArray(_gizmoMesh->getChildMeshes()); _cache.material = _coloredMaterial; _cache.hoverMaterial = _hoverMaterial; _cache.disableMaterial = _disableMaterial; _cache.active = false; _cache.dragBehavior = dragBehavior; if (_parent) { _parent->addToAxisCache(static_cast<Mesh*>(_gizmoMesh.get()), _cache); } _pointerObserver = gizmoLayer->utilityLayerScene->onPointerObservable.add( [this](PointerInfo* pointerInfo, EventState& /*es*/) -> void { if (_customMeshSet) { return; } auto pickedMesh = std::static_pointer_cast<Mesh>(pointerInfo->pickInfo.pickedMesh); _isHovered = stl_util::contains(_cache.colliderMeshes, pickedMesh); if (!_parent) { const auto material = _cache.dragBehavior->enabled ? (_isHovered || _dragging ? _hoverMaterial : _coloredMaterial) : _disableMaterial; _setGizmoMeshMaterial(_cache.gizmoMeshes, material); } }); dragBehavior->onEnabledObservable.add([this](bool* newState, EventState& /*es*/) -> void { _setGizmoMeshMaterial(_cache.gizmoMeshes, *newState ? _coloredMaterial : _disableMaterial); }); } PlaneDragGizmo::~PlaneDragGizmo() = default; void PlaneDragGizmo::_attachedNodeChanged(const NodePtr& value) { dragBehavior->enabled = value ? true : false; } void PlaneDragGizmo::set_isEnabled(bool value) { _isEnabled = value; if (!value) { attachedNode = nullptr; } else { if (_parent) { attachedNode = _parent->attachedNode(); } } } bool PlaneDragGizmo::get_isEnabled() const { return _isEnabled; } void PlaneDragGizmo::dispose(bool /*doNotRecurse*/, bool /*disposeMaterialAndTextures*/) { onSnapObservable.clear(); gizmoLayer->utilityLayerScene->onPointerObservable.remove(_pointerObserver); dragBehavior->detach(); Gizmo::dispose(); if (_gizmoMesh) { _gizmoMesh->dispose(); } for (const auto& matl : {_coloredMaterial, _hoverMaterial, _disableMaterial}) { if (matl) { matl->dispose(); } } } } // namespace BABYLON
7,191
2,391
#ifndef ASPARSERATIONS_TABLE_ITEM_SET_H_ #define ASPARSERATIONS_TABLE_ITEM_SET_H_ #include "item.hpp" #include <set> namespace asparserations { namespace table { class Item_Set { friend bool operator<(const Item_Set&, const Item_Set&); public: Item_Set(const std::set<Item>&); const std::set<Item>& items() const; void insert(const Item&); bool merge(const Item_Set&); private: std::set<Item> m_items; }; bool operator<(const Item_Set&, const Item_Set&); } } #endif
534
192
/* VKGL (c) 2018 Dominik Witczak * * This code is licensed under MIT license (see LICENSE.txt for details) */ #include "Common/macros.h" #include "OpenGL/frontend/gl_formats.h" typedef struct InternalFormatData { OpenGL::FormatDataType data_type; uint32_t n_components; /* For base and compressed internal formats, "1" indicates the component is used. * For sized internal formats, non-zero value indicates the component is used and describes the component size in bits. */ uint32_t component_size_r; uint32_t component_size_g; uint32_t component_size_b; uint32_t component_size_a; uint32_t component_size_depth; uint32_t component_size_stencil; uint32_t component_size_shared; bool is_base_internal_format; bool is_compressed_internal_format; bool is_sized_internal_format; InternalFormatData() { memset(this, 0, sizeof(*this) ); } InternalFormatData(const OpenGL::FormatDataType& in_data_type, const uint32_t& in_n_components, const uint32_t& in_component_size_r, const uint32_t& in_component_size_g, const uint32_t& in_component_size_b, const uint32_t& in_component_size_a, const uint32_t& in_component_size_depth, const uint32_t& in_component_size_stencil, const uint32_t& in_component_size_shared, const bool& in_is_base_internal_format, const bool& in_is_compressed_internal_format, const bool& in_is_sized_internal_format) :data_type (in_data_type), n_components (in_n_components), component_size_r (in_component_size_r), component_size_g (in_component_size_g), component_size_b (in_component_size_b), component_size_a (in_component_size_a), component_size_depth (in_component_size_depth), component_size_stencil (in_component_size_stencil), component_size_shared (in_component_size_shared), is_base_internal_format (in_is_base_internal_format), is_compressed_internal_format(in_is_compressed_internal_format), is_sized_internal_format (in_is_sized_internal_format) { /* Stub */ } } InternalFormatData; OpenGL::PixelFormat; static const std::unordered_map<OpenGL::InternalFormat, InternalFormatData> g_gl_internalformat_data = { /* Base internal formats */ /* Format | data_type | n_components | r size | g size | b size | a size | d size | s size | shared size | is base? | is compressed? | is sized? */ {OpenGL::InternalFormat::Depth_Component, InternalFormatData(OpenGL::FormatDataType::Unknown, 1, 0, 0, 0, 0, 1, 0, 0, true, false, false)}, {OpenGL::InternalFormat::Depth_Stencil, InternalFormatData(OpenGL::FormatDataType::Unknown, 2, 0, 0, 0, 0, 1, 1, 0, true, false, false)}, {OpenGL::InternalFormat::Red, InternalFormatData(OpenGL::FormatDataType::Unknown, 1, 1, 0, 0, 0, 0, 0, 0, true, false, false)}, {OpenGL::InternalFormat::RG, InternalFormatData(OpenGL::FormatDataType::Unknown, 2, 1, 1, 0, 0, 0, 0, 0, true, false, false)}, {OpenGL::InternalFormat::RGB, InternalFormatData(OpenGL::FormatDataType::Unknown, 3, 1, 1, 1, 0, 0, 0, 0, true, false, false)}, {OpenGL::InternalFormat::RGBA, InternalFormatData(OpenGL::FormatDataType::Unknown, 4, 1, 1, 1, 1, 0, 0, 0, true, false, false)}, /* Sized internal formats */ /* Format | data_type | n_components | r size | g size | b size | a size | d size | s size | shared size | is base? | is compressed? | is sized? */ {OpenGL::InternalFormat::R11F_G11F_B10F, InternalFormatData(OpenGL::FormatDataType::SFloat, 3, 11, 11, 10, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R16, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R16_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R16F, InternalFormatData(OpenGL::FormatDataType::SFloat, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R16I, InternalFormatData(OpenGL::FormatDataType::SInt, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R16UI, InternalFormatData(OpenGL::FormatDataType::UInt, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R3_G3_B2, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 3, 3, 2, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R32F, InternalFormatData(OpenGL::FormatDataType::SFloat, 1, 32, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R32I, InternalFormatData(OpenGL::FormatDataType::SInt, 1, 32, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R32UI, InternalFormatData(OpenGL::FormatDataType::UInt, 1, 32, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R8, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 8, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R8_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 1, 8, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R8I, InternalFormatData(OpenGL::FormatDataType::SInt, 1, 8, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R8UI, InternalFormatData(OpenGL::FormatDataType::UInt, 1, 8, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG16, InternalFormatData(OpenGL::FormatDataType::UNorm, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG16_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG16F, InternalFormatData(OpenGL::FormatDataType::SFloat, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG16I, InternalFormatData(OpenGL::FormatDataType::SInt, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG16UI, InternalFormatData(OpenGL::FormatDataType::UInt, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG32F, InternalFormatData(OpenGL::FormatDataType::SFloat, 2, 32, 32, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG32I, InternalFormatData(OpenGL::FormatDataType::SInt, 2, 32, 32, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG32UI, InternalFormatData(OpenGL::FormatDataType::UInt, 2, 32, 32, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG8, InternalFormatData(OpenGL::FormatDataType::UNorm, 2, 8, 8, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG8_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 2, 8, 8, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG8I, InternalFormatData(OpenGL::FormatDataType::SInt, 2, 8, 8, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG8UI, InternalFormatData(OpenGL::FormatDataType::UInt, 2, 8, 8, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB10, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 10, 10, 10, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB10_A2, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 10, 10, 10, 2, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB10_A2UI, InternalFormatData(OpenGL::FormatDataType::UInt, 4, 10, 10, 10, 2, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB12, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 12, 12, 12, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB16_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 3, 16, 16, 16, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB16F, InternalFormatData(OpenGL::FormatDataType::SFloat, 3, 16, 16, 16, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB16I, InternalFormatData(OpenGL::FormatDataType::SInt, 3, 16, 16, 16, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB16UI, InternalFormatData(OpenGL::FormatDataType::UInt, 3, 16, 16, 16, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB32F, InternalFormatData(OpenGL::FormatDataType::SFloat, 3, 32, 32, 32, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB32I, InternalFormatData(OpenGL::FormatDataType::SInt, 3, 32, 32, 32, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB32UI, InternalFormatData(OpenGL::FormatDataType::UInt, 3, 32, 32, 32, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB4, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 4, 4, 4, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB5, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 5, 5, 5, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB5_A1, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 5, 5, 5, 1, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB8, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB8_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB8I, InternalFormatData(OpenGL::FormatDataType::SInt, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB8UI, InternalFormatData(OpenGL::FormatDataType::UInt, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB9_E5, InternalFormatData(OpenGL::FormatDataType::SFloat, 4, 9, 9, 9, 0, 0, 0, 5, false, false, true)}, {OpenGL::InternalFormat::RGBA12, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 12, 12, 12, 12, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA16, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 16, 16, 16, 16, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA16F, InternalFormatData(OpenGL::FormatDataType::SFloat, 4, 16, 16, 16, 16, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA16I, InternalFormatData(OpenGL::FormatDataType::SInt, 4, 16, 16, 16, 16, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA16UI, InternalFormatData(OpenGL::FormatDataType::UInt, 4, 16, 16, 16, 16, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA2, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 2, 2, 2, 2, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA32F, InternalFormatData(OpenGL::FormatDataType::SFloat, 4, 32, 32, 32, 32, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA32I, InternalFormatData(OpenGL::FormatDataType::SInt, 4, 32, 32, 32, 32, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA32UI, InternalFormatData(OpenGL::FormatDataType::UInt, 4, 32, 32, 32, 32, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA4, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 4, 4, 4, 4, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA8, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA8_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA8I, InternalFormatData(OpenGL::FormatDataType::SInt, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA8UI, InternalFormatData(OpenGL::FormatDataType::UInt, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::SRGB8, InternalFormatData(OpenGL::FormatDataType::SRGB, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::SRGB8_Alpha8, InternalFormatData(OpenGL::FormatDataType::SRGB, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)}, /* Format | data_type | n_components | r size | g size | b size | a size | d size | s size | shared size | is base? | is compressed? | is sized? */ {OpenGL::InternalFormat::Depth_Component16, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 0, 0, 0, 0, 16, 0, 0, false, false, true) }, {OpenGL::InternalFormat::Depth_Component24, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 0, 0, 0, 0, 24, 0, 0, false, false, true) }, {OpenGL::InternalFormat::Depth_Component32, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 0, 0, 0, 0, 32, 0, 0, false, false, true) }, {OpenGL::InternalFormat::Depth_Component32_Float, InternalFormatData(OpenGL::FormatDataType::UFloat, 1, 0, 0, 0, 0, 32, 0, 0, false, false, true) }, {OpenGL::InternalFormat::Depth24_Stencil8, InternalFormatData(OpenGL::FormatDataType::UNorm_UInt, 2, 0, 0, 0, 0, 24, 8, 0, false, false, true) }, {OpenGL::InternalFormat::Depth32_Float_Stencil8, InternalFormatData(OpenGL::FormatDataType::UFloat_UInt, 2, 0, 0, 0, 0, 32, 8, 0, false, false, true) }, /* Compressed internal formats */ /* Format | data_type | n_components | r size | g size | b size | a size | d size | s size | shared size | is base? | is compressed? | is sized? */ {OpenGL::InternalFormat::Compressed_Red, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 1, 0, 0, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_Red_RGTC1, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 1, 0, 0, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_RG, InternalFormatData(OpenGL::FormatDataType::UNorm, 2, 1, 1, 0, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_RG_RGTC2, InternalFormatData(OpenGL::FormatDataType::UNorm, 2, 1, 1, 0, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_RGB, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 1, 1, 1, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_RGB_BPTC_Signed_Float, InternalFormatData(OpenGL::FormatDataType::SFloat, 3, 1, 1, 1, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_RGB_BPTC_Unsigned_Float, InternalFormatData(OpenGL::FormatDataType::UFloat, 3, 1, 1, 1, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_RGBA, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 1, 1, 1, 1, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_RGBA_BPTC_UNorm, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 1, 1, 1, 1, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_Signed_Red_RGTC1, InternalFormatData(OpenGL::FormatDataType::SNorm, 1, 1, 0, 0, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_Signed_RG_RGTC2, InternalFormatData(OpenGL::FormatDataType::SNorm, 2, 1, 1, 0, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_SRGB, InternalFormatData(OpenGL::FormatDataType::SRGB, 3, 1, 1, 1, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_SRGB_Alpha, InternalFormatData(OpenGL::FormatDataType::SRGB, 4, 1, 1, 1, 1, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_SRGB_Alpha_BPTC_UNorm, InternalFormatData(OpenGL::FormatDataType::SRGB, 4, 1, 1, 1, 1, 0, 0, 0, false, true, false)}, }; static const std::vector<OpenGL::InternalFormat> g_color_sized_internalformats = { OpenGL::InternalFormat::R11F_G11F_B10F, OpenGL::InternalFormat::R16, OpenGL::InternalFormat::R16_SNorm, OpenGL::InternalFormat::R16F, OpenGL::InternalFormat::R16I, OpenGL::InternalFormat::R16UI, OpenGL::InternalFormat::R3_G3_B2, OpenGL::InternalFormat::R32F, OpenGL::InternalFormat::R32I, OpenGL::InternalFormat::R32UI, OpenGL::InternalFormat::R8, OpenGL::InternalFormat::R8_SNorm, OpenGL::InternalFormat::R8I, OpenGL::InternalFormat::R8UI, OpenGL::InternalFormat::RG16, OpenGL::InternalFormat::RG16_SNorm, OpenGL::InternalFormat::RG16F, OpenGL::InternalFormat::RG16I, OpenGL::InternalFormat::RG16UI, OpenGL::InternalFormat::RG32F, OpenGL::InternalFormat::RG32I, OpenGL::InternalFormat::RG32UI, OpenGL::InternalFormat::RG8, OpenGL::InternalFormat::RG8_SNorm, OpenGL::InternalFormat::RG8I, OpenGL::InternalFormat::RG8UI, OpenGL::InternalFormat::RGB10, OpenGL::InternalFormat::RGB10_A2, OpenGL::InternalFormat::RGB10_A2UI, OpenGL::InternalFormat::RGB12, OpenGL::InternalFormat::RGB16_SNorm, OpenGL::InternalFormat::RGB16F, OpenGL::InternalFormat::RGB16I, OpenGL::InternalFormat::RGB16UI, OpenGL::InternalFormat::RGB32F, OpenGL::InternalFormat::RGB32I, OpenGL::InternalFormat::RGB32UI, OpenGL::InternalFormat::RGB4, OpenGL::InternalFormat::RGB5, OpenGL::InternalFormat::RGB5_A1, OpenGL::InternalFormat::RGB8, OpenGL::InternalFormat::RGB8_SNorm, OpenGL::InternalFormat::RGB8I, OpenGL::InternalFormat::RGB8UI, OpenGL::InternalFormat::RGB9_E5, OpenGL::InternalFormat::RGBA12, OpenGL::InternalFormat::RGBA16, OpenGL::InternalFormat::RGBA16F, OpenGL::InternalFormat::RGBA16I, OpenGL::InternalFormat::RGBA16UI, OpenGL::InternalFormat::RGBA2, OpenGL::InternalFormat::RGBA32F, OpenGL::InternalFormat::RGBA32I, OpenGL::InternalFormat::RGBA32UI, OpenGL::InternalFormat::RGBA4, OpenGL::InternalFormat::RGBA8, OpenGL::InternalFormat::RGBA8_SNorm, OpenGL::InternalFormat::RGBA8I, OpenGL::InternalFormat::RGBA8UI, OpenGL::InternalFormat::SRGB8, OpenGL::InternalFormat::SRGB8_Alpha8, }; static const std::vector<OpenGL::InternalFormat> g_ds_sized_internalformats = { OpenGL::InternalFormat::Depth_Component16, OpenGL::InternalFormat::Depth_Component24, OpenGL::InternalFormat::Depth_Component32, OpenGL::InternalFormat::Depth_Component32_Float, OpenGL::InternalFormat::Depth24_Stencil8, OpenGL::InternalFormat::Depth32_Float_Stencil8, }; OpenGL::InternalFormat OpenGL::GLFormats::get_best_fit_ds_internal_format(const uint32_t& in_depth_bits, const uint32_t& in_stencil_bits) { OpenGL::InternalFormat result = OpenGL::InternalFormat::Unknown; uint32_t result_n_depth_bits = 0; uint32_t result_n_stencil_bits = 0; vkgl_assert(in_depth_bits != 0 || in_stencil_bits != 0); for (const auto& current_internalformat : g_ds_sized_internalformats) { const auto& internalformat_data_iterator = g_gl_internalformat_data.find(current_internalformat); vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() ); const auto& internalformat_data = internalformat_data_iterator->second; if ((in_depth_bits == 0 && internalformat_data.component_size_depth != 0) || (in_stencil_bits == 0 && internalformat_data.component_size_stencil != 0) ) { continue; } if ((in_depth_bits != 0 && internalformat_data.component_size_depth == 0) || (in_stencil_bits != 0 && internalformat_data.component_size_stencil == 0) ) { continue; } if (result == OpenGL::InternalFormat::Unknown) { result = current_internalformat; result_n_depth_bits = internalformat_data.component_size_depth; result_n_stencil_bits = internalformat_data.component_size_stencil; } else { const auto current_depth_diff = abs(static_cast<int32_t>(internalformat_data.component_size_depth) - static_cast<int32_t>(in_depth_bits) ); const auto current_stencil_diff = abs(static_cast<int32_t>(internalformat_data.component_size_stencil) - static_cast<int32_t>(in_stencil_bits) ); const auto result_depth_diff = abs(static_cast<int32_t>(result_n_depth_bits) - static_cast<int32_t>(in_depth_bits) ); const auto result_stencil_diff = abs(static_cast<int32_t>(result_n_stencil_bits) - static_cast<int32_t>(in_stencil_bits) ); if (current_depth_diff + current_stencil_diff < result_depth_diff + result_stencil_diff) { result = current_internalformat; result_n_depth_bits = internalformat_data.component_size_depth; result_n_stencil_bits = internalformat_data.component_size_stencil; } } } vkgl_assert(result != OpenGL::InternalFormat::Unknown); return result; } OpenGL::FormatDataType OpenGL::GLFormats::get_format_data_type_for_non_base_internal_format(const OpenGL::InternalFormat& in_format) { const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format); OpenGL::FormatDataType result = OpenGL::FormatDataType::Unknown; vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() ); if (internalformat_data_iterator != g_gl_internalformat_data.end() ) { result = internalformat_data_iterator->second.data_type; } return result; } uint32_t OpenGL::GLFormats::get_n_components_for_sized_internal_format(const OpenGL::InternalFormat& in_format) { const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format); uint32_t result = 0; vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() ); if (internalformat_data_iterator != g_gl_internalformat_data.end() ) { result = internalformat_data_iterator->second.n_components; } return result; } bool OpenGL::GLFormats::get_per_component_bit_size_for_sized_internal_format(const OpenGL::InternalFormat& in_format, uint32_t* out_rgba_bit_size_ptr, uint32_t* out_ds_size_ptr, uint32_t* out_shared_size_ptr) { const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format); bool result = false; vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() ); if (internalformat_data_iterator != g_gl_internalformat_data.end() ) { out_rgba_bit_size_ptr[0] = internalformat_data_iterator->second.component_size_r; out_rgba_bit_size_ptr[1] = internalformat_data_iterator->second.component_size_g; out_rgba_bit_size_ptr[2] = internalformat_data_iterator->second.component_size_b; out_rgba_bit_size_ptr[3] = internalformat_data_iterator->second.component_size_a; out_ds_size_ptr [0] = internalformat_data_iterator->second.component_size_depth; out_ds_size_ptr [1] = internalformat_data_iterator->second.component_size_stencil; *out_shared_size_ptr = internalformat_data_iterator->second.component_size_shared; result = true; } return result; } bool OpenGL::GLFormats::is_base_internal_format(const OpenGL::InternalFormat& in_format) { const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format); bool result = false; vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() ); if (internalformat_data_iterator != g_gl_internalformat_data.end() ) { result = internalformat_data_iterator->second.is_base_internal_format; } return result; } bool OpenGL::GLFormats::is_compressed_internal_format(const OpenGL::InternalFormat& in_format) { const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format); bool result = false; vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() ); if (internalformat_data_iterator != g_gl_internalformat_data.end() ) { result = internalformat_data_iterator->second.is_compressed_internal_format; } return result; } bool OpenGL::GLFormats::is_sized_internal_format(const OpenGL::InternalFormat& in_format) { const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format); bool result = false; vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() ); if (internalformat_data_iterator != g_gl_internalformat_data.end() ) { result = internalformat_data_iterator->second.is_sized_internal_format; } return result; }
32,603
9,737
#include "ThreadLocker.h" #ifdef _P_THREAD pthread_mutex_t Global_Mutex_Lock = PTHREAD_MUTEX_INITIALIZER; #elif defined(_BOOST_THREAD) boost::mutex Global_Mutex_Lock; #endif
175
77
// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "NavRoutingRouteModel.h" namespace ExampleApp { namespace NavRouting { namespace SdkModel { NavRoutingRouteModel::NavRoutingRouteModel() : m_duration(0) , m_distance(0) { } NavRoutingRouteModel::NavRoutingRouteModel(const double duration, const double distance, const std::vector<NavRoutingDirectionModel>& directions, const Eegeo::Routes::Webservice::RouteData& sourceRouteData) : m_duration(duration) , m_distance(distance) , m_directions(directions) , m_sourceRoute(sourceRouteData) { } const double NavRoutingRouteModel::GetDuration() const { return m_duration; } const double NavRoutingRouteModel::GetDistance() const { return m_distance; } const std::vector<NavRoutingDirectionModel>& NavRoutingRouteModel::GetDirections() const { return m_directions; } const Eegeo::Routes::Webservice::RouteData& NavRoutingRouteModel::GetSourceRouteData() const { return m_sourceRoute; } void NavRoutingRouteModel::UpdateDirection(int index, const NavRoutingDirectionModel& directionModel) { if (index >= 0 && index < m_directions.size()) { m_directions[index] = directionModel; } } } } }
1,812
436
/*---------------------------------------------------------------------------*\ Copyright (C) 2011 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS 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. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::functionObjectList Description List of function objects with start(), execute() and end() functions that is called for each object. See Also CML::functionObject and CML::OutputFilterFunctionObject SourceFiles functionObjectList.cpp \*---------------------------------------------------------------------------*/ #ifndef functionObjectList_H #define functionObjectList_H #include "PtrList.hpp" #include "functionObject.hpp" #include "SHA1Digest.hpp" #include "HashTable.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { /*---------------------------------------------------------------------------*\ Class functionObjectList Declaration \*---------------------------------------------------------------------------*/ class functionObjectList : private PtrList<functionObject> { // Private data //- A list of SHA1 digests for the function object dictionaries List<SHA1Digest> digests_; //- Quick lookup of the index into functions/digests HashTable<label> indices_; const Time& time_; //- The parent dictionary containing a "functions" entry // This entry can either be a list or a dictionary of // functionObject specifications. const dictionary& parentDict_; //- Switch for the execution of the functionObjects bool execution_; //- Tracks if read() was called while execution is on bool updated_; // Private Member Functions //- Remove and return the function object pointer by name, // and returns the old index via the parameter. // Returns a nullptr pointer (and index -1) if it didn't exist. functionObject* remove(const word&, label& oldIndex); //- Disallow default bitwise copy construct functionObjectList(const functionObjectList&); //- Disallow default bitwise assignment void operator=(const functionObjectList&); public: // Constructors //- Construct from Time and the execution setting // The functionObject specifications are read from the controlDict functionObjectList ( const Time&, const bool execution=true ); //- Construct from Time, a dictionary with "functions" entry // and the execution setting. // \param[in] parentDict - the parent dictionary containing // a "functions" entry, which can either be a list or a dictionary // of functionObject specifications. functionObjectList ( const Time&, const dictionary& parentDict, const bool execution=true ); //- Destructor virtual ~functionObjectList(); // Member Functions //- Return the number of elements in the List. using PtrList<functionObject>::size; //- Return true if the List is empty (ie, size() is zero). using PtrList<functionObject>::empty; //- Access to the functionObjects using PtrList<functionObject>::operator[]; //- Clear the list of function objects virtual void clear(); //- Find the ID of a given function object by name virtual label findObjectID(const word& name) const; //- Switch the function objects on virtual void on(); //- Switch the function objects off virtual void off(); //- Return the execution status (on/off) of the function objects virtual bool status() const; //- Called at the start of the time-loop virtual bool start(); //- Called at each ++ or += of the time-loop. forceWrite overrides // the usual outputControl behaviour and forces writing always // (used in postprocessing mode) virtual bool execute(const bool forceWrite = false); //- Called when Time::run() determines that the time-loop exits virtual bool end(); //- Called when time was set at the end of the Time::operator++ virtual bool timeSet(); //- Called at the end of Time::adjustDeltaT() if adjustTime is true virtual bool adjustTimeStep(); //- Read and set the function objects if their data have changed virtual bool read(); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace CML // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
5,525
1,414
// This is a minimal test case whose purpose is to check if the compiler // generates efficient assembly code. Should be built with -O3 optimization // and not through Bazel (is not set up to generate such optimized code). #include <stdio.h> #define NDEBUG // No asserts. #include "soa/soa.h" #include "soa/storage.h" using ikra::soa::SoaLayout; using ikra::soa::kAddressModeZero; using ikra::soa::DynamicStorage; using ikra::soa::StaticStorage; using ikra::soa::kLayoutModeAos; using ikra::soa::kLayoutModeSoa; // Compiler flags determine addressing mode and storage strategy. #ifndef ADDRESS_MODE #error Address mode undefined #endif #ifndef STORAGE_STRATEGY #error Storage strategy undefined #endif #ifndef LAYOUT_MODE #error Layout mode undefined #endif static const uint32_t kClassMaxInst = 0x1234; class TestClass : public SoaLayout<TestClass, kClassMaxInst, ADDRESS_MODE, STORAGE_STRATEGY, PP_CONCAT(kLayoutMode, LAYOUT_MODE)> { public: IKRA_INITIALIZE_CLASS int_ field0; int_ field1; void increase_field0() { field0 *= 0x5555; } void increase_field1() { field1 *= 0x4444; } }; IKRA_HOST_STORAGE(TestClass); class TestClassCompare { public: int field0; int field1; void increase_field0() { field0 *= 0x5555; } void increase_field1() { field1 *= 0x4444; } }; TestClassCompare test_compare_array[kClassMaxInst]; int main() { TestClass::initialize_storage(); TestClass* instance = new TestClass(); instance->field0 = 0x7777; instance->field1 = 0x8888; instance->increase_field0(); instance->increase_field1(); // Expected output: FIELD0: 668085635, FIELD1: 610821152 printf("FIELD0: %i, FIELD1: %i\n", (int) instance->field0, (int) instance->field1); // Return 0 if correct result. return !(instance->field0 == 668085635 && instance->field1 == 610821152); } // Extra methods for code isolation: Will show up in .S file. TestClass* new_instance() { return new TestClass(); } void write_field0(TestClass* instance) { instance->field0 = 0x7777; } int read_field0(TestClass* instance) { return instance->field0; } void write_field1(TestClass* instance) { instance->field1 = 0x7777; } int read_field1(TestClass* instance) { return instance->field1; } // Compare with explicit, hand-written SOA code. int explicit_field0[100]; void explicit_write_field0(uintptr_t id) { explicit_field0[id] = 0x7777; } int explicit_read_field0(uintptr_t id) { return explicit_field0[id]; } void explicit_write_field0_aos(TestClassCompare* obj) { obj->field0 = 0x7777; } int explicit_read_field0_aos(TestClassCompare* obj) { return obj->field0; } void explicit_write_field1_aos(TestClassCompare* obj) { obj->field1 = 0x7777; } int explicit_read_field1_aos(TestClassCompare* obj) { return obj->field1; }
2,913
1,109
#include "robot_interface/gripper.h" #include <iostream> using namespace baxter_core_msgs; using namespace std; Gripper::Gripper(std::string limb, bool no_robot) : _limb(limb), _no_robot(no_robot), _first_run(true) { if (no_robot) return; _pub_command = _nh.advertise<EndEffectorCommand>( "/robot/end_effector/" + _limb + "_gripper/command", 1); _sub_state = _nh.subscribe("/robot/end_effector/" + _limb + "_gripper/state", SUBSCRIBER_BUFFER, &Gripper::gripperCb, this); //Initially all the interesting properties of the state are unknown EndEffectorState initial_gripper_state; initial_gripper_state.calibrated= \ initial_gripper_state.enabled= \ initial_gripper_state.error= \ initial_gripper_state.gripping= \ initial_gripper_state.missed= \ initial_gripper_state.ready= \ initial_gripper_state.moving=EndEffectorState::STATE_UNKNOWN; _state = initial_gripper_state; pthread_mutex_init(&_mutex, NULL); } bool Gripper::gripObject() { suck(); // int cnt = 0; // while (!_gripper->is_sucking()) // { // ROS_WARN("Requested a suck to the gripper, but the gripper is not sucking."); // ++cnt; // if (cnt == 10) return false; // pause(); // ros::spinOnce(); // } return true; } bool Gripper::releaseObject() { if (is_sucking()) { blow(); return true; } ROS_WARN("[%s_gripper] Requested a release of the gripper, but the gripper is not sucking.", getGripperLimb().c_str()); return false; } void Gripper::gripperCb(const EndEffectorState &msg) { pthread_mutex_lock(&_mutex); _state = msg; pthread_mutex_unlock(&_mutex); if (_first_run) { if (!is_calibrated()) { ROS_INFO("[%s_gripper] Calibrating the gripper..", getGripperLimb().c_str()); calibrate(); } _first_run=false; } } void Gripper::calibrate() { EndEffectorCommand sucking_command; sucking_command.id=get_id(); sucking_command.command=EndEffectorCommand::CMD_CALIBRATE; _pub_command.publish(sucking_command); } void Gripper::suck() { EndEffectorCommand sucking_command; sucking_command.id=get_id(); sucking_command.command=EndEffectorCommand::CMD_GRIP; if (_limb == "left") { sucking_command.args="{\"grip_attempt_seconds\": 5.0}"; } _pub_command.publish(sucking_command); } void Gripper::blow() { EndEffectorCommand release_command; release_command.id=get_id(); release_command.command=EndEffectorCommand::CMD_RELEASE; _pub_command.publish(release_command); } int Gripper::get_id() { return _state.id; } bool Gripper::is_enabled() { return _state.enabled==EndEffectorState::STATE_TRUE; } bool Gripper::is_calibrated() { return _state.calibrated==EndEffectorState::STATE_TRUE; } bool Gripper::is_ready_to_grip() { return _state.ready==EndEffectorState::STATE_TRUE; } bool Gripper::has_error() { return _state.error==EndEffectorState::STATE_TRUE; } bool Gripper::is_sucking() { // ROS_INFO("force is: %g\n",_state.force); return _state.position<80; } bool Gripper::is_gripping() { return true; return _state.gripping==EndEffectorState::STATE_TRUE; }
3,371
1,287
#include "pch.h" #include <mmreg.h> #include <mmsystem.h> #include <mmdeviceapi.h> #include <audioclient.h> #include <mbctype.h> #include "output_wasapi.h" #include "synthesizer_vst.h" #include "display.h" #include "song.h" #include "config.h" #include "export.h" // pkey static const PROPERTYKEY PKEY_Device_FriendlyName = { { 0xa45c254e, 0xdf1c, 0x4efd, { 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0 } }, 14 }; // global wasapi client static IAudioClient *client = NULL; // global renderer client static IAudioRenderClient *render_client = NULL; // playing event and thread static HANDLE wasapi_thread = NULL; // format static WAVEFORMATEX *pwfx = NULL; // output buffer size static double buffer_time = 0.01; // class id and interface id static const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator); static const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator); static const IID IID_IAudioClient = __uuidof(IAudioClient); static const IID IID_IAudioRenderClient = __uuidof(IAudioRenderClient); // write buffer static void write_buffer(float *dst, float *left, float *right, int size) { float volume = config_get_output_volume() / 100.f; while (size--) { dst[0] = *left * volume; dst[1] = *right * volume; left++; right++; dst += 2; } } // playing thread static DWORD __stdcall wasapi_play_thread(void *param) { HRESULT hr; uint bufferFrameCount; BYTE *data; // Get the actual size of the allocated buffer. if (FAILED(hr = client->GetBufferSize(&bufferFrameCount))) return 0; // timer resolustion timeBeginPeriod(1); // temp buffer for vsti process float output_buffer[2][4096]; // start playing hr = client->Start(); while (wasapi_thread) { uint numFramesPadding; // See how much buffer space is available. if (SUCCEEDED(hr = client->GetCurrentPadding(&numFramesPadding))) { uint buffer_size = pwfx->nSamplesPerSec * buffer_time; if (numFramesPadding <= buffer_size) { uint numFramesAvailable = bufferFrameCount - numFramesPadding; uint numFramesProcess = 32; // write data at least 32 samles if (numFramesAvailable >= numFramesProcess) { //printf("write %d\n", numFramesAvailable); if (export_rendering()) { memset(output_buffer[0], 0, numFramesProcess * sizeof(float)); memset(output_buffer[1], 0, numFramesProcess * sizeof(float)); } else { // update song song_update(1000.0 * (double)32 / (double)pwfx->nSamplesPerSec); // update effect vsti_update_config((float)pwfx->nSamplesPerSec, 32); // call vsti process func vsti_process(output_buffer[0], output_buffer[1], numFramesProcess); } // Grab the entire buffer for the initial fill operation. if (SUCCEEDED(hr = render_client->GetBuffer(numFramesAvailable, &data))) { // write buffer write_buffer((float *)data, output_buffer[0], output_buffer[1], numFramesProcess); // release buffer render_client->ReleaseBuffer(numFramesProcess, 0); // continue processing continue; } } } } Sleep(1); } // stop playing client->Stop(); // stop vsti process vsti_stop_process(); return 0; } // open wasapi. int wasapi_open(const char *name) { HRESULT hr; IMMDeviceEnumerator *enumerator = NULL; IMMDevice *device = NULL; REFERENCE_TIME hnsRequestedDuration = 1000000; // close wasapi device wasapi_close(); // create enumerator if (FAILED(hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void * *)&enumerator))) goto error; if (name && name[0]) { struct enum_callback : public wasapi_enum_callback { void operator () (const char *name, void *device) { if (_stricmp(name, devname) == 0) { result = (IMMDevice *)device; result->AddRef(); } } const char *devname; IMMDevice *result; } callback; callback.devname = name; callback.result = 0; wasapi_enum_device(callback); device = callback.result; } else { // make a default name name = "Default"; // get default device if (FAILED(hr = enumerator->GetDefaultAudioEndpoint(eRender, eConsole, &device))) { fprintf(stderr, "WASAPI: Failed to get default endpoint. name=%s, hr=%x\n", name, hr); goto error; } } // no device if (device == NULL) { hr = E_FAIL; goto error; } // activate if (FAILED(hr = device->Activate(IID_IAudioClient, CLSCTX_ALL, NULL, (void **)&client))) { fprintf(stderr, "WASAPI: Failed to active audio client. name=%s, hr=%x\n", name, hr); goto error; } // get mix format if (FAILED(hr = client->GetMixFormat(&pwfx))) { fprintf(stderr, "WASAPI: Failed to get mix format. name=%s, hr=%x\n", name, hr); goto error; } bool supported = false; if (pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { WAVEFORMATEXTENSIBLE* format = (WAVEFORMATEXTENSIBLE*)pwfx; if (format->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) {\ if (pwfx->wBitsPerSample == 32) { supported = true; } } fprintf(stdout, "WASAPI: name=%s, format={%x, %x, %x, %x}, bits=%d, samplerate=%d\n", name, format->SubFormat.Data1, format->SubFormat.Data2, format->SubFormat.Data3, format->SubFormat.Data4, pwfx->wBitsPerSample, pwfx->nSamplesPerSec); } if (!supported) { fprintf(stderr, "WASAPI: current mix format is not supported. name=%s\n", name); goto error; } // initialize if (FAILED(hr = client->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, hnsRequestedDuration, 0, pwfx, NULL))) { fprintf(stderr, "WASAPI: Failed to initialize audio client. name=%s, hr=%x\n", name, hr); goto error; } // get render client if (FAILED(hr = client->GetService(IID_IAudioRenderClient, (void **)&render_client))) { fprintf(stderr, "WASAPI: Failed to get render client. name=%s, hr=%x\n", name, hr); goto error; } // create input thread wasapi_thread = CreateThread(NULL, 0, &wasapi_play_thread, NULL, NULL, NULL); // change thread priority to highest SetThreadPriority(wasapi_thread, THREAD_PRIORITY_TIME_CRITICAL); SAFE_RELEASE(device); SAFE_RELEASE(enumerator); return 0; error: SAFE_RELEASE(device); SAFE_RELEASE(enumerator); wasapi_close(); return hr; } // close wasapi device void wasapi_close() { // wait input thread exit if (wasapi_thread) { HANDLE thread = wasapi_thread; wasapi_thread = NULL; WaitForSingleObject(thread, -1); CloseHandle(thread); } if (pwfx) { CoTaskMemFree(pwfx); pwfx = NULL; } SAFE_RELEASE(render_client); SAFE_RELEASE(client); } // set buffer size void wasapi_set_buffer_time(double time) { if (time > 0) { buffer_time = time * 0.001; } } // get output samplerate uint wasapi_get_samplerate() { if (pwfx) { return pwfx->nSamplesPerSec; } return 44100; } // enum device void wasapi_enum_device(wasapi_enum_callback &callback) { HRESULT hr; IMMDeviceEnumerator *enumerator = NULL; IMMDeviceCollection *devices = NULL; IPropertyStore *props = NULL; // create enumerator if (FAILED(hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void * *)&enumerator))) goto error; if (FAILED(hr = enumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &devices))) goto error; uint device_count = 0; if (SUCCEEDED(devices->GetCount(&device_count))) { for (uint i = 0; i < device_count; i++) { IMMDevice *device = NULL; if (SUCCEEDED(devices->Item(i, &device))) { if (SUCCEEDED(device->OpenPropertyStore(STGM_READ, &props))) { PROPVARIANT varName; // Initialize container for property value. PropVariantInit(&varName); // Get the endpoint's friendly-name property. if (SUCCEEDED(props->GetValue(PKEY_Device_FriendlyName, &varName))) { char buff[256]; WideCharToMultiByte(_getmbcp(), 0, varName.pwszVal, -1, buff, sizeof(buff), NULL, NULL); callback(buff, (void *)device); } PropVariantClear(&varName); } } SAFE_RELEASE(device); } } error: SAFE_RELEASE(props); SAFE_RELEASE(devices); SAFE_RELEASE(enumerator); }
8,873
3,193
/* ========================================================================= Program: MPCDI Library Language: C++ Date: $Date: 2012-08-22 20:19:58 -0400 (Wed, 22 Aug 2012) $ Version: $Revision: 19513 $ Copyright (c) 2013 Scalable Display Technologies, Inc. All Rights Reserved. The MPCDI Library is distributed under the BSD license. Please see License.txt distributed with this package. ===================================================================auto== */ #include "mpcdiUtils.h" using namespace mpcdi; std::string Utils::ProfileVersionToString(const ProfileVersion& pv) { std::stringstream ss; ss << pv.MajorVersion << "." << pv.MinorVersion; return ss.str(); } MPCDI_Error Utils::StringToProfileVersion(const std::string &text, ProfileVersion& pv) { pv = ProfileVersion(); size_t pos = text.find_first_of("."); if (pos==std::string::npos) return MPCDI_FAILURE; pv.MajorVersion = StringToNumber<int>(text.substr(0,pos)); pv.MinorVersion = 0; if (text.size() >= pos+1) pv.MinorVersion = StringToNumber<int>(text.substr(pos+1,text.length())); return MPCDI_SUCCESS; }
1,142
408
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: graja <graja@student.42wolfsburg.de> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/02/12 14:02:52 by graja #+# #+# */ /* Updated: 2022/02/17 10:05:47 by graja ### ########.fr */ /* */ /* ************************************************************************** */ #include "DiamondTrap.hpp" int main(void) { DiamondTrap test; DiamondTrap lala("LaLa"); DiamondTrap kuemmel(test); //attack method overloaded by ScavTrap lala.attack("LOLO"); test.attack("TestTrapper"); //methods from ClapTrap lala.beRepaired(20); kuemmel.takeDamage(10); //method ScavTrap test.guardGate(); //method FragTrap test.highFivesGuys(); //method DiamondTrap test.whoAmI(); lala.whoAmI(); //operator overload for = test = lala; //check if it works test.whoAmI(); std::cout << "--------------------------------------------"; std::cout << std::endl << std::endl; return (0); }
1,508
488
namespace Veng { template<class KeyType, class ValueType, class Hasher> HashMap<KeyType, ValueType, Hasher>::HashNode::HashNode(const KeyType& key, const ValueType& value) : key(key) , value(value) , next(INVALID_INDEX) {} template<class KeyType, class ValueType, class Hasher> HashMap<KeyType, ValueType, Hasher>::HashNode::HashNode(const KeyType& key, const ValueType& value, int next) : key(key) , value(value) , next(next) {} template<class KeyType, class ValueType, class Hasher> HashMap<KeyType, ValueType, Hasher>::HashNode::HashNode(HashNode&& other) : key(other.key) , value(other.value) , next(other.next) { other.next = INVALID_INDEX; } template<class KeyType, class ValueType, class Hasher> typename HashMap<KeyType, ValueType, Hasher>::HashNode& HashMap<KeyType, ValueType, Hasher>::HashNode::operator=(typename HashMap<KeyType, ValueType, Hasher>::HashNode&& other) { KeyType k = key; ValueType v = value; key = other.key; value = other.value; next = other.next; other.key = k; other.value = v; other.next = INVALID_INDEX; return *this; } template<class KeyType, class ValueType, class Hasher> HashMap<KeyType, ValueType, Hasher>::HashMap(Allocator& allocator) : m_allocator(allocator) {} template<class KeyType, class ValueType, class Hasher> HashMap<KeyType, ValueType, Hasher>::HashMap(HashMap<KeyType, ValueType, Hasher>&& other) : m_allocator(other.m_allocator) , m_buckets(other.m_buckets) , m_bucketSize(other.m_bucketSize) , m_table(other.m_table) , m_size(other.m_size) { other.m_buckets = nullptr; other.m_bucketSize = 0; other.m_table = nullptr; other.m_size = 0; } template<class KeyType, class ValueType, class Hasher> HashMap<KeyType, ValueType, Hasher>& HashMap<KeyType, ValueType, Hasher>::operator=(HashMap<KeyType, ValueType, Hasher>&& other) { int* buckets = m_buckets; unsigned bucketSize = m_bucketSize; HashNode* table = m_table; unsigned size = m_size; m_allocator = other.m_allocator; m_buckets = other.m_buckets; m_bucketSize = other.m_bucketSize; m_table = other.m_table; m_size = other.m_size; other.m_buckets = buckets; other.m_bucketSize = bucketSize; other.m_table = table; other.m_size = size; return *this; } template<class KeyType, class ValueType, class Hasher> HashMap<KeyType, ValueType, Hasher>::~HashMap() { for (unsigned i = 0; i < m_size; ++i) { DELETE_PLACEMENT(m_table + i); } if (m_buckets != nullptr) m_allocator.Deallocate(m_buckets); } template<class KeyType, class ValueType, class Hasher> void HashMap<KeyType, ValueType, Hasher>::Clear() { for (unsigned i = 0; i < m_bucketSize; ++i) { m_buckets[i] = INVALID_INDEX; } for (unsigned i = 0; i < m_size; ++i) { DELETE_PLACEMENT(m_table + i); } m_size = 0; } template<class KeyType, class ValueType, class Hasher> typename HashMap<KeyType, ValueType, Hasher>::HashNode* HashMap<KeyType, ValueType, Hasher>::Begin() { return m_table; } template<class KeyType, class ValueType, class Hasher> typename HashMap<KeyType, ValueType, Hasher>::HashNode* HashMap<KeyType, ValueType, Hasher>::End() { return m_table + m_size; } template<class KeyType, class ValueType, class Hasher> typename const HashMap<KeyType, ValueType, Hasher>::HashNode* HashMap<KeyType, ValueType, Hasher>::Begin() const { return m_table; } template<class KeyType, class ValueType, class Hasher> typename const HashMap<KeyType, ValueType, Hasher>::HashNode* HashMap<KeyType, ValueType, Hasher>::End() const { return m_table + m_size; } template<class KeyType, class ValueType, class Hasher> bool HashMap<KeyType, ValueType, Hasher>::Find(const KeyType& key, ValueType*& value) const { if (m_size == 0) return false; unsigned bucketIdx = GetIndex(key); if (m_buckets[bucketIdx] == INVALID_INDEX) return false; HashNode* node = &m_table[m_buckets[bucketIdx]]; while (node->next != INVALID_INDEX && node->key != key) { node = &m_table[node->next]; } if (node->key == key) { value = &node->value; return true; } else { return false; } } template<class KeyType, class ValueType, class Hasher> ValueType* HashMap<KeyType, ValueType, Hasher>::Insert(const KeyType& key, const ValueType& value) { if (m_bucketSize == 0) Rehash(INITIAL_SIZE); if ((m_size / (float)m_bucketSize) * 100 > MAX_FACTOR) Rehash(m_bucketSize * ENLARGE_MULTIPLIER); unsigned bucketIdx = GetIndex(key); return Insert(bucketIdx, key, value); } template<class KeyType, class ValueType, class Hasher> bool HashMap<KeyType, ValueType, Hasher>::Erase(const KeyType& key) { unsigned bucketIdx = GetIndex(key); if (m_buckets[bucketIdx] == INVALID_INDEX) return false; int* pointingIdx = &m_buckets[bucketIdx]; HashNode* node = &m_table[*pointingIdx]; while (node->next != INVALID_INDEX && node->key != key) { pointingIdx = &node->next; node = &m_table[node->next]; } if (node->key != key) return false; int freeNodeIdx = *pointingIdx; *pointingIdx = node->next; DELETE_PLACEMENT(node); m_size--; if(m_size > 0 && freeNodeIdx != m_size) { //fill up hole in m_table HashNode& lastNode = m_table[m_size]; unsigned lastNodeBucketIdx = GetIndex(lastNode.key); pointingIdx = &m_buckets[lastNodeBucketIdx]; while(m_table[*pointingIdx].key != lastNode.key) { pointingIdx = &(m_table[*pointingIdx].next); } *pointingIdx = freeNodeIdx; NEW_PLACEMENT(node, HashNode)(Utils::Move(lastNode)); //DELETE_PLACEMENT(&lastNode); } return true; } template<class KeyType, class ValueType, class Hasher> void HashMap<KeyType, ValueType, Hasher>::Rehash(unsigned bucketSize) { ASSERT(bucketSize > m_bucketSize); int* oldBuckets = m_buckets; unsigned oldBucketSize = m_bucketSize; HashNode* oldTable = m_table; unsigned oldSize = m_size; m_bucketSize = bucketSize; m_size = 0; void* data = m_allocator.Allocate(bucketSize * (sizeof(int) + sizeof(HashNode)) + alignof(HashNode), alignof(int)); m_buckets = static_cast<int*>(data); m_table = static_cast<HashNode*>(AlignPointer(m_buckets + bucketSize, alignof(HashNode))); for (unsigned i = 0; i < m_bucketSize; ++i) { m_buckets[i] = INVALID_INDEX; } for (unsigned i = 0; i < oldSize; ++i) { HashNode& node = oldTable[i]; unsigned idx = GetIndex(node.key); Insert(idx, node.key, node.value); } if (oldBuckets != nullptr) m_allocator.Deallocate(oldBuckets); } template<class KeyType, class ValueType, class Hasher> size_t HashMap<KeyType, ValueType, Hasher>::GetBucketsSize() const { return m_bucketSize; } template<class KeyType, class ValueType, class Hasher> size_t HashMap<KeyType, ValueType, Hasher>::GetSize() const { return m_size; } template<class KeyType, class ValueType, class Hasher> ValueType* HashMap<KeyType, ValueType, Hasher>::Insert(unsigned bucketIdx, const KeyType& key, const ValueType& value) { ASSERT(m_size < m_bucketSize); if (m_buckets[bucketIdx] == INVALID_INDEX) { HashNode* newNode = NEW_PLACEMENT(m_table + m_size, HashNode)(key, value); m_buckets[bucketIdx] = m_size++; return &newNode->value; } HashNode* node = &m_table[m_buckets[bucketIdx]]; while (node->key != key && node->next != INVALID_INDEX) { node = &m_table[node->next]; } if (node->key == key) { return nullptr; } else { HashNode* newNode = NEW_PLACEMENT(m_table + m_size, HashNode)(key, value); node->next = m_size++; return &newNode->value; } } template<class KeyType, class ValueType, class Hasher> unsigned HashMap<KeyType, ValueType, Hasher>::GetIndex(const KeyType& key) const { auto hash = Hasher::get(key); return hash % m_bucketSize; } template<class KeyType, class ValueType, class Hasher> typename HashMap<KeyType, ValueType, Hasher>::HashNode* HashMap<KeyType, ValueType, Hasher>::GetNode(unsigned index) { ASSERT(index < m_bucketSize); return &m_table[index]; } template<class KeyType, class ValueType, class Hasher> inline typename HashMap<KeyType, ValueType, Hasher>::HashNode* begin(HashMap<KeyType, ValueType, Hasher>& a) { return a.Begin(); } template<class KeyType, class ValueType, class Hasher> inline typename HashMap<KeyType, ValueType, Hasher>::HashNode* end(HashMap<KeyType, ValueType, Hasher>& a) { return a.End(); } template<class KeyType, class ValueType, class Hasher> inline typename const HashMap<KeyType, ValueType, Hasher>::HashNode* begin(const HashMap<KeyType, ValueType, Hasher>& a) { return a.Begin(); } template<class KeyType, class ValueType, class Hasher> inline typename const HashMap<KeyType, ValueType, Hasher>::HashNode* end(const HashMap<KeyType, ValueType, Hasher>& a) { return a.End(); } }
8,562
3,203
#include<bits/stdc++.h> using namespace std; int decodings(string &str); int main(){ string str=""; cin>>str; cout<<decodings(str)<<endl; return 0; } int decodings(string &str){ int n=str.size(); /* Here just do the reverse process of memoization and get the ans in the bottom up manner. Compare it with the memoized version and you will get more clarity. */ vector<int> dp(n+1,0); //base case dp[0]=1; dp[1]=1; //Here we are going to fill the table bottomup both the conditions are same here also just the order is different and even if you look //closely then you will see that the order of filling the table is same in both the cases it's just difference in methodology for(int i=2;i<=n;i++){ if(str[i-1]>'0'){ dp[i]+=dp[i-1]; } if(str[i-2]=='1' || (str[i-2]=='2' && str[i-1]<'7')){ dp[i]+=dp[i-2]; } } return dp[n]; }
968
353
#include "TimeframeDataGenerator.h" RecommenderData* TimeframeDataGenerator::generate_recommender_data(RecDat*){ local_recommender_data_.clear(); double now = recommender_data_iterator_->get_actual()->time; double timeframe_begin=now-timeframe_length_; vector<RecDat>* train_data = local_recommender_data_.get_rec_data(); for(int counter = recommender_data_iterator_->get_counter();counter>=0;counter--){ RecDat* rec_dat = recommender_data_iterator_->get(counter); if(rec_dat->time<=timeframe_begin) break; train_data->push_back(*rec_dat); } if (!local_recommender_data_.initialize()) throw runtime_error("Initialization of local_recommender_data was unsuccesful."); return &local_recommender_data_; }
731
239
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/inspector2/model/Ec2InstanceAggregation.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Inspector2 { namespace Model { Ec2InstanceAggregation::Ec2InstanceAggregation() : m_amisHasBeenSet(false), m_instanceIdsHasBeenSet(false), m_instanceTagsHasBeenSet(false), m_operatingSystemsHasBeenSet(false), m_sortBy(Ec2InstanceSortBy::NOT_SET), m_sortByHasBeenSet(false), m_sortOrder(SortOrder::NOT_SET), m_sortOrderHasBeenSet(false) { } Ec2InstanceAggregation::Ec2InstanceAggregation(JsonView jsonValue) : m_amisHasBeenSet(false), m_instanceIdsHasBeenSet(false), m_instanceTagsHasBeenSet(false), m_operatingSystemsHasBeenSet(false), m_sortBy(Ec2InstanceSortBy::NOT_SET), m_sortByHasBeenSet(false), m_sortOrder(SortOrder::NOT_SET), m_sortOrderHasBeenSet(false) { *this = jsonValue; } Ec2InstanceAggregation& Ec2InstanceAggregation::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("amis")) { Array<JsonView> amisJsonList = jsonValue.GetArray("amis"); for(unsigned amisIndex = 0; amisIndex < amisJsonList.GetLength(); ++amisIndex) { m_amis.push_back(amisJsonList[amisIndex].AsObject()); } m_amisHasBeenSet = true; } if(jsonValue.ValueExists("instanceIds")) { Array<JsonView> instanceIdsJsonList = jsonValue.GetArray("instanceIds"); for(unsigned instanceIdsIndex = 0; instanceIdsIndex < instanceIdsJsonList.GetLength(); ++instanceIdsIndex) { m_instanceIds.push_back(instanceIdsJsonList[instanceIdsIndex].AsObject()); } m_instanceIdsHasBeenSet = true; } if(jsonValue.ValueExists("instanceTags")) { Array<JsonView> instanceTagsJsonList = jsonValue.GetArray("instanceTags"); for(unsigned instanceTagsIndex = 0; instanceTagsIndex < instanceTagsJsonList.GetLength(); ++instanceTagsIndex) { m_instanceTags.push_back(instanceTagsJsonList[instanceTagsIndex].AsObject()); } m_instanceTagsHasBeenSet = true; } if(jsonValue.ValueExists("operatingSystems")) { Array<JsonView> operatingSystemsJsonList = jsonValue.GetArray("operatingSystems"); for(unsigned operatingSystemsIndex = 0; operatingSystemsIndex < operatingSystemsJsonList.GetLength(); ++operatingSystemsIndex) { m_operatingSystems.push_back(operatingSystemsJsonList[operatingSystemsIndex].AsObject()); } m_operatingSystemsHasBeenSet = true; } if(jsonValue.ValueExists("sortBy")) { m_sortBy = Ec2InstanceSortByMapper::GetEc2InstanceSortByForName(jsonValue.GetString("sortBy")); m_sortByHasBeenSet = true; } if(jsonValue.ValueExists("sortOrder")) { m_sortOrder = SortOrderMapper::GetSortOrderForName(jsonValue.GetString("sortOrder")); m_sortOrderHasBeenSet = true; } return *this; } JsonValue Ec2InstanceAggregation::Jsonize() const { JsonValue payload; if(m_amisHasBeenSet) { Array<JsonValue> amisJsonList(m_amis.size()); for(unsigned amisIndex = 0; amisIndex < amisJsonList.GetLength(); ++amisIndex) { amisJsonList[amisIndex].AsObject(m_amis[amisIndex].Jsonize()); } payload.WithArray("amis", std::move(amisJsonList)); } if(m_instanceIdsHasBeenSet) { Array<JsonValue> instanceIdsJsonList(m_instanceIds.size()); for(unsigned instanceIdsIndex = 0; instanceIdsIndex < instanceIdsJsonList.GetLength(); ++instanceIdsIndex) { instanceIdsJsonList[instanceIdsIndex].AsObject(m_instanceIds[instanceIdsIndex].Jsonize()); } payload.WithArray("instanceIds", std::move(instanceIdsJsonList)); } if(m_instanceTagsHasBeenSet) { Array<JsonValue> instanceTagsJsonList(m_instanceTags.size()); for(unsigned instanceTagsIndex = 0; instanceTagsIndex < instanceTagsJsonList.GetLength(); ++instanceTagsIndex) { instanceTagsJsonList[instanceTagsIndex].AsObject(m_instanceTags[instanceTagsIndex].Jsonize()); } payload.WithArray("instanceTags", std::move(instanceTagsJsonList)); } if(m_operatingSystemsHasBeenSet) { Array<JsonValue> operatingSystemsJsonList(m_operatingSystems.size()); for(unsigned operatingSystemsIndex = 0; operatingSystemsIndex < operatingSystemsJsonList.GetLength(); ++operatingSystemsIndex) { operatingSystemsJsonList[operatingSystemsIndex].AsObject(m_operatingSystems[operatingSystemsIndex].Jsonize()); } payload.WithArray("operatingSystems", std::move(operatingSystemsJsonList)); } if(m_sortByHasBeenSet) { payload.WithString("sortBy", Ec2InstanceSortByMapper::GetNameForEc2InstanceSortBy(m_sortBy)); } if(m_sortOrderHasBeenSet) { payload.WithString("sortOrder", SortOrderMapper::GetNameForSortOrder(m_sortOrder)); } return payload; } } // namespace Model } // namespace Inspector2 } // namespace Aws
4,966
1,699
#pragma once #include <utility> #include <tuple> #include <type_traits> #include "nifty/meta/integral_constant.hpp" namespace nifty{ namespace meta{ // find the position of a type in a tuple template <class T, class Tuple> struct TupleTypeIndex; template <class T, class... Types> struct TupleTypeIndex<T, std::tuple<T, Types...>> : SizeT<0>{ }; template <class T, class U, class... Types> struct TupleTypeIndex<T, std::tuple<U, Types...>> : SizeT<1 + TupleTypeIndex<T, std::tuple<Types...>>::value>{ }; template<class TUPLE, template<typename ...> typename C> struct TransformTuple; template<class ... TUPLE_ARGS , template< typename ... ARGS> class C> struct TransformTuple<std::tuple<TUPLE_ARGS ...>, C >{ typedef std::tuple< C<TUPLE_ARGS> ...> type; }; ///\cond namespace detail{ template<class INDEX_SEQUENCE, template<std::size_t I> typename C> struct GenerateTupleImpl; template<std::size_t... Ints, template<std::size_t I> typename C> struct GenerateTupleImpl<std::index_sequence<Ints ... >, C>{ typedef std::tuple<C<Ints> ...> type; }; } ///\endcond template<std::size_t N, template<std::size_t I> typename C> struct GenerateTuple : detail::GenerateTupleImpl<std::make_index_sequence<N>, C>{ }; template<std::size_t N, class T> struct GenerateUniformTuple{ template<std::size_t I> using Helper = T; typedef typename GenerateTuple<N, Helper>::type type; }; } }
1,587
554
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <IGem.h> #include <AzCore/Module/DynamicModuleHandle.h> #include <Behaviors/LoggingGroupBehavior.h> #include <Processors/LoadingTrackingProcessor.h> #include <Processors/ExportTrackingProcessor.h> namespace SceneLoggingExample { // The SceneLoggingExampleModule is the entry point for gems. To extend the SceneAPI, the // logging, loading, and export components must be registered here. // // NOTE: The gem system currently does not support registering file extensions through the // AssetImportRequest EBus. class SceneLoggingExampleModule : public CryHooksModule { public: AZ_RTTI(SceneLoggingExampleModule, "{36AA9C0F-7976-40C7-AF54-C492AC5B16F6}", CryHooksModule); SceneLoggingExampleModule() : CryHooksModule() { // The SceneAPI libraries require specialized initialization. As early as possible, be // sure to repeat the following two lines for any SceneAPI you want to use. Omitting these // calls or making them too late can cause problems such as missing EBus events. m_sceneCoreModule = AZ::DynamicModuleHandle::Create("SceneCore"); m_sceneCoreModule->Load(true); m_descriptors.insert(m_descriptors.end(), { LoggingGroupBehavior::CreateDescriptor(), LoadingTrackingProcessor::CreateDescriptor(), ExportTrackingProcessor::CreateDescriptor() }); } // In this example, no system components are added. You can use system components // to set global settings for this gem from the Project Configurator. // For functionality that should always be available to the SceneAPI, we recommend // that you use a BehaviorComponent instead. AZ::ComponentTypeList GetRequiredSystemComponents() const override { return AZ::ComponentTypeList {}; } private: AZStd::unique_ptr<AZ::DynamicModuleHandle> m_sceneCoreModule; }; } // namespace SceneLoggingExample // DO NOT MODIFY THIS LINE UNLESS YOU RENAME THE GEM. // The first parameter should be GemName_GemIdLower. // The second should be the fully qualified name of the class above. AZ_DECLARE_MODULE_CLASS(Gem_SceneLoggingExample, SceneLoggingExample::SceneLoggingExampleModule)
2,579
710
// // engine // // Copyright © 2015–2016 D.E. Goodman-Wilson. All rights reserved. // #include <gtest/gtest.h> #include <slack/slack.h> #include <random> #include "environment.h" slack::channel_id id; TEST(channels, channels_list_basic) { auto result = env->slack.channels.list(); ASSERT_TRUE(result); ASSERT_LT(0, result.channels.size()); //in most cases it will be at least 2 (#general and #random) } TEST(channels, channels_create_basic) { std::string name = "tc"; auto result = env->slack.channels.create(name); ASSERT_TRUE(result); ASSERT_TRUE(static_cast<bool>(result.channel)); slack::channel chan{*result.channel}; //TODO store the ID so we can delete its id = chan.id; ASSERT_EQ(name, chan.name); } //TODO shouldn't depend upon id stored in last test! Should find it anew! TEST(channels, channels_rename_basic) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis{}; int rand = dis(gen); std::string new_name = "tc-"+std::to_string(rand); auto result = env->slack.channels.rename(id, new_name); ASSERT_TRUE(result); slack::channel chan{*result.channel}; ASSERT_EQ(new_name, chan.name); } TEST(channels, channels_archive_basic) { auto result = env->slack.channels.archive(id); ASSERT_TRUE(result); //really not much else we can check here. }
1,379
514
// counttests.cpp : count.{h,cpp} unit tests. /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "../db/ops/count.h" #include "../db/cursor.h" #include "../db/pdfile.h" #include "dbtests.h" namespace CountTests { class Base { Lock::DBWrite lk; Client::Context _context; public: Base() : lk(ns()), _context( ns() ) { addIndex( fromjson( "{\"a\":1}" ) ); } ~Base() { try { boost::shared_ptr<Cursor> c = theDataFileMgr.findAll( ns() ); vector< DiskLoc > toDelete; for(; c->ok(); c->advance() ) toDelete.push_back( c->currLoc() ); for( vector< DiskLoc >::iterator i = toDelete.begin(); i != toDelete.end(); ++i ) theDataFileMgr.deleteRecord( ns(), i->rec(), *i, false ); DBDirectClient cl; cl.dropIndexes( ns() ); } catch ( ... ) { FAIL( "Exception while cleaning up collection" ); } } protected: static const char *ns() { return "unittests.counttests"; } static void addIndex( const BSONObj &key ) { BSONObjBuilder b; b.append( "name", key.firstElementFieldName() ); b.append( "ns", ns() ); b.append( "key", key ); BSONObj o = b.done(); stringstream indexNs; indexNs << "unittests.system.indexes"; theDataFileMgr.insert( indexNs.str().c_str(), o.objdata(), o.objsize() ); } static void insert( const char *s ) { insert( fromjson( s ) ); } static void insert( const BSONObj &o ) { theDataFileMgr.insert( ns(), o.objdata(), o.objsize() ); } }; class CountBasic : public Base { public: void run() { insert( "{\"a\":\"b\"}" ); BSONObj cmd = fromjson( "{\"query\":{}}" ); string err; ASSERT_EQUALS( 1, runCount( ns(), cmd, err ) ); } }; class CountQuery : public Base { public: void run() { insert( "{\"a\":\"b\"}" ); insert( "{\"a\":\"b\",\"x\":\"y\"}" ); insert( "{\"a\":\"c\"}" ); BSONObj cmd = fromjson( "{\"query\":{\"a\":\"b\"}}" ); string err; ASSERT_EQUALS( 2, runCount( ns(), cmd, err ) ); } }; class CountFields : public Base { public: void run() { insert( "{\"a\":\"b\"}" ); insert( "{\"c\":\"d\"}" ); BSONObj cmd = fromjson( "{\"query\":{},\"fields\":{\"a\":1}}" ); string err; ASSERT_EQUALS( 2, runCount( ns(), cmd, err ) ); } }; class CountQueryFields : public Base { public: void run() { insert( "{\"a\":\"b\"}" ); insert( "{\"a\":\"c\"}" ); insert( "{\"d\":\"e\"}" ); BSONObj cmd = fromjson( "{\"query\":{\"a\":\"b\"},\"fields\":{\"a\":1}}" ); string err; ASSERT_EQUALS( 1, runCount( ns(), cmd, err ) ); } }; class CountIndexedRegex : public Base { public: void run() { insert( "{\"a\":\"b\"}" ); insert( "{\"a\":\"c\"}" ); BSONObj cmd = fromjson( "{\"query\":{\"a\":/^b/}}" ); string err; ASSERT_EQUALS( 1, runCount( ns(), cmd, err ) ); } }; class All : public Suite { public: All() : Suite( "count" ) { } void setupTests() { add< CountBasic >(); add< CountQuery >(); add< CountFields >(); add< CountQueryFields >(); add< CountIndexedRegex >(); } } myall; } // namespace CountTests
4,506
1,427
// // InsetOp.cc // Mandoline // // Created by GM on 11/24/10. // Copyright 2010 Belfry DevWorks. All rights reserved. // #include "InsetOp.h" #include "BGL/BGL.h" #include "SlicingContext.h" #include "CarvedSlice.h" InsetOp::~InsetOp() { } void InsetOp::main() { if ( isCancelled ) return; if ( NULL == context ) return; if ( NULL == slice ) return; double extWidth = context->standardExtrusionWidth(); int shells = context->perimeterShells; slice->perimeter.inset(shells*extWidth, slice->infillMask); for (int i = 0; i < shells; i++) { BGL::CompoundRegion compReg; slice->perimeter.inset((i+0.5)*extWidth, compReg); slice->shells.push_back(compReg); } slice->state = INSET; if ( isCancelled ) return; }
771
308
/* * Copyright (C) 2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "common.hpp" #include "test_config.hpp" #include <cassian/cli/cli.hpp> #include <cassian/runtime/runtime.hpp> #include <cassian/utility/utility.hpp> #include <catch2/catch.hpp> #include <cstdint> #include <numeric> #include <string> #include <vector> namespace ca = cassian; namespace { void test_aligned(ca::Runtime *runtime, const size_t global_work_size, const std::string &program_type) { const std::string source = ca::load_text_file( ca::get_asset("kernels/oclc_attribute_qualifiers/aligned.cl")); ca::Kernel kernel = runtime->create_kernel("test_kernel", source, "", program_type); runtime->run_kernel(kernel, global_work_size); runtime->release_kernel(kernel); } } // namespace TEST_CASE("aligned", "") { const TestConfig &config = get_test_config(); const auto size = config.work_size(); REQUIRE_NOTHROW(test_aligned(config.runtime(), size, config.program_type())); }
1,020
350
#include "EAC.hpp" #include <TlHelp32.h> HANDLE EAC::hEvent; typedef BOOL(NTAPI* p_DeviceIoControl)(HANDLE hDevice, DWORD dwIoControlCode, LPVOID lpInBuffer, DWORD nInBufferSize, LPVOID lpOutBuffer, DWORD nOutBufferSize, LPDWORD lpBytesReturned, LPOVERLAPPED lpOverlapped); static p_DeviceIoControl o_DeviceIoControl = nullptr; bool EAC::Init() { return Bypass_DeviceIoControl(true); } bool EAC::Uninit() { return Bypass_DeviceIoControl(false); } bool WINAPI DeviceIoControl_Hook (HANDLE hDevice, DWORD dwIoControlCode, LPVOID lpInBuffer, DWORD nInBufferSize, LPVOID lpOutBuffer, DWORD nOutBufferSize, LPDWORD lpBytesReturned, LPOVERLAPPED lpOverlapped) { VM_START DWORD_PTR dwStartAddress = 0; HMODULE hModule = 0; static HANDLE hThread = nullptr; if (NT_SUCCESS(NtQueryInformationThread(GetCurrentThread(), static_cast<THREADINFOCLASS>(9), &dwStartAddress, sizeof(DWORD_PTR), NULL)) && !GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast<char*>(dwStartAddress), &hModule)) { if (!EnumWindows([](HWND hWnd, LPARAM lParam) -> BOOL { DWORD procId = 0; if (GetWindowThreadProcessId(hWnd, &procId) && procId == GetCurrentProcessId()) SuspendThread(GetCurrentThread()); return TRUE; }, NULL)) { MessageBoxExA(0, "Failed to use EnumWindows!", "ERRROR!", 0, 0); return false; } } VM_END return o_DeviceIoControl(hDevice, dwIoControlCode, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, lpBytesReturned, lpOverlapped); }; bool EAC::Bypass_DeviceIoControl(bool detourStatus) { VM_START if(!o_DeviceIoControl) o_DeviceIoControl = reinterpret_cast<p_DeviceIoControl>(GetProcAddress(GetModuleHandleA("KERNELBASE"), "DeviceIoControl")); if (DetourTransactionBegin() != NO_ERROR || DetourUpdateThread(GetCurrentThread()) != NO_ERROR || DetourAttach(&(PVOID&)o_DeviceIoControl, DeviceIoControl_Hook) != NO_ERROR || DetourTransactionCommit() != NO_ERROR) { #if _DEBUG == 1 std::cout << "Could not hook functions" << std::endl; #endif MessageBoxExA(0, "Failed to hook functions!", "ERRROR!", 0, 0); return false; } VM_END return true; }
2,188
881
// $Id: HOPSPACK_GssPoint.hpp 149 2009-11-12 02:40:41Z tplante $ // $URL: https://software.sandia.gov/svn/hopspack/tags/dakota-6.3/src/src-citizens/citizen-gss/HOPSPACK_GssPoint.hpp $ //@HEADER // ************************************************************************ // // HOPSPACK: Hybrid Optimization Parallel Search Package // Copyright 2009 Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // This file is part of HOPSPACK. // // HOPSPACK is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 2.1 of the // License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library. If not, see http://www.gnu.org/licenses/. // // Questions? Contact Tammy Kolda (tgkolda@sandia.gov) // or Todd Plantenga (tplante@sandia.gov) // // ************************************************************************ //@HEADER /*! @file HOPSPACK_GssPoint.hpp @brief Class declaration for HOPSPACK::GssPoint, subclass of DataPoint. */ #ifndef HOPSPACK_GSSPOINT_HPP #define HOPSPACK_GSSPOINT_HPP #include "HOPSPACK_common.hpp" #include "HOPSPACK_DataPoint.hpp" #include "HOPSPACK_NonlConstrPenalty.hpp" #include "HOPSPACK_ProblemDef.hpp" #include "HOPSPACK_Vector.hpp" namespace HOPSPACK { //---------------------------------------------------------------------- //! Contains a trial location, evaluation results, and GSS parent information. /*! An instance contains the DataPoint base class members, plus GSS parent information and a method to compare evaluation results as a scalar. */ //---------------------------------------------------------------------- class GssPoint : public DataPoint { public: //! Tag value if a point has no GSS parent. static const int NO_PARENT_TAG = -1; //! Direction index value if a point has no parent direction. static const int NO_DIR_INDEX = -1; //! Constructor for a point with no parent. /*! * @param[in] nObjGoal Optimization goal: minimize, maximize, etc. * @param[in] cPenalty Penalty function for nonlinear constraints. * @param[in] cX Location of the trial point. * @param[in] dStep Step length used to generate this point. */ GssPoint (const ProblemDef::ObjectiveType nObjGoal, const NonlConstrPenalty & cPenalty, const Vector & cX, const double dStep); //! Constructor for a point generated from a parent point. /*! * @param[in] nObjGoal Optimization goal: minimize, maximize, etc. * @param[in] cPenalty Penalty function for nonlinear constraints. * @param[in] cX Location of the trial point. * @param[in] dStep Step length used to generate this point. * @param[in] nParentTag Tag of the parent of this point. * @param[in] dParentObj Objective of the parent of this point. * @param[in] dPenaltyTerm Nonlinear constraint penalty of the parent * at this point. * @param[in] dSuffImprvAmt Sufficient improvement amount (>= 0) that * the point must make over dParentObj. * @param[in] nDirIndex Direction index that generated this point. */ GssPoint (const ProblemDef::ObjectiveType nObjGoal, const NonlConstrPenalty & cPenalty, const Vector & cX, const double dStep, const int nParentTag, const double dParentObj, const double dPenaltyTerm, const double dSuffImprvAmt, const int nDirIndex); //! Constructor that makes an instance from a DataPoint not from GSS. /*! * The GSS citizen may use DataPoint instances generated from other * citizens or the framework. The new GssPoint has no parent, and is * typically assigned the GSS default initial step length for purposes * of computing more trial points. * * @param[in] cArg Existing point to be copied. * @param[in] cPenalty Penalty function for nonlinear constraints. * @param[in] dStep Step length to use. */ GssPoint (const DataPoint & cArg, const NonlConstrPenalty & cPenalty, const double dStep); //! Copy Constructor that makes a deep copy. GssPoint (const GssPoint & cArg); //! Destructor. ~GssPoint (void); //! Return the parent tag of the point. int getParentTag (void) const; //! Return the step length used to generate this point. double getStepLength (void) const; //! Return the index of the direction that generated this point. int getDirIndex (void) const; //! Return the evaluated objective function value plus penalty. /*! * This overrides the method in HOPSPACK_DataPoint to allow the citizen * to add nonlinear constraints as penalty terms. * * If getVecF() contains multiple objectives, then the "best" objective * is determined by calling HOPSPACK_DataPoint::getBestF(). * The NonlConstrPenalty associated with this point is used to compute * a penalty term for violated nonlinear constraints. The term causes * the objective to become worse if constraints are violated. * For instance, if optimization is trying to minimize the objective, * then a positive penalty term is added to the output of getBestF(). * If maximizing, then a positive penalty term is subtracted. */ double getBestF (void) const; //! Return true if this point's objective plus penalty is better. /*! * The method assumes both points are linearly feasible. * It calls DataPoint::getBestF() to combine multiple objectives and then * make a scalar inequality comparison. Special rules apply * if the point has not been evaluated, or the objective does not exist. * If nonlinear constraints are present, then the objective includes * a penalty term. */ bool isBetterObjThan (const GssPoint & other) const; //! Return true if the evaluated objective makes sufficient improvement. /*! * The objective of the point must improve over its parent's by an * amount that exceeds the "sufficient decrease" forcing function. * The forcing function is defined in GssIterator where it computes * the sufficient improvement amount for the GssPoint constructor. * The function is \f[ \rho (\Delta) = \alpha \Delta^2 \f] * where \f$ \Delta \f$ is step length, and \f$ \alpha \f$ is the * user parameter "Sufficient Improvement Factor". * If \f$ \alpha = 0 \f$, then the point need only make "simple decrease" * over the parent point. * If the point has no GSS parent, then the method returns true. */ bool hasSufficientImprovement (void) const; //! Print to the given stream. void print (ostream & stream, const bool bIncludeMsg = true) const; private: //! By design, there is no assignment operator. GssPoint & operator= (const GssPoint &); //! GSS parent point tag, or the value NO_PARENT_TAG if none. int _nParentTag; //! Index of the direction that generated this point. int _nDirIndex; //! Step length that was used to generate this point. double _dStep; //! Parent's objective value. double _dParentObjective; //! Sufficient improvement amount needed compared with parent's objective. double _dSufficientImprovementAmount; //! Penalty function for nonlinear constraints. const NonlConstrPenalty & _cPenalty; }; } //-- namespace HOPSPACK #endif //-- HOPSPACK_GSSPOINT_HPP
8,542
2,468
// // Created by Andgel on 25/01/2019. // #ifndef GRANDMATD_RESOURCES_HPP #define GRANDMATD_RESOURCES_HPP #include <vector> namespace gtd { struct Food { enum Type { Any, GlutenFree = 0, Vegan = 0, Carnivore = 0, NbOfTypes }; std::vector<double> stock; }; } #endif //GRANDMATD_RESOURCES_HPP
320
171
#include "WorkerThread.h" #include "Engine.h" namespace Wraith { WorkerThread::WorkerThread(const std::string& id) : Thread(id) { Clear(); } WorkerThread::~WorkerThread() { } void WorkerThread::Clear() { m_ProjectedTime = 0; m_QueuedJobs.clear(); } void WorkerThread::Queue(std::shared_ptr<PersistentJob> job) { if (ShouldRun()) { m_QueuedJobs.push_back(job); m_ProjectedTime += job->GetAverageTime(); } } void WorkerThread::Run() { SetActive(true); m_Channel.notify_all(); } const f32 WorkerThread::GetProjectedTime() const { return m_ProjectedTime; } void WorkerThread::Execute() { while (ShouldRun()) { std::unique_lock<std::mutex> wait_lock(m_Mutex); while (!IsRunning() && ShouldRun()) { m_Channel.wait(wait_lock); } wait_lock.unlock(); if (!ShouldRun()) return; f32 accumulated_time = 0.0f; for (auto& job : m_QueuedJobs) accumulated_time += job->Execute(); SetActive(false); } } } // namespace Wraith
1,264
402
/*************************************************************************** * Copyright 1998-2020 by authors (see AUTHORS.txt) * * * * This file is part of LuxCoreRender. * * * * 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 "slg/textures/triplanar.h" using namespace std; using namespace luxrays; using namespace slg; //------------------------------------------------------------------------------ // Triplanar mapping texture //------------------------------------------------------------------------------ float TriplanarTexture::GetFloatValue(const HitPoint &hitPoint) const { return GetSpectrumValue(hitPoint).Y(); } Spectrum TriplanarTexture::GetSpectrumValue(const HitPoint &hitPoint) const { Normal localShadeN; const Point localPoint = mapping->Map(hitPoint, &localShadeN); float weights[3] = { Sqr(Sqr(localShadeN.x)), Sqr(Sqr(localShadeN.y)), Sqr(Sqr(localShadeN.z)) }; const float sum = weights[0] + weights[1] + weights[2]; weights[0] = weights[0] / sum; weights[1] = weights[1] / sum; weights[2] = weights[2] / sum; HitPoint hitPointTmp = hitPoint; hitPointTmp.defaultUV.u = localPoint.y; hitPointTmp.defaultUV.v = localPoint.z; Spectrum result = texX->GetSpectrumValue(hitPointTmp) * weights[0]; hitPointTmp.defaultUV.u = localPoint.x; hitPointTmp.defaultUV.v = localPoint.z; result += texY->GetSpectrumValue(hitPointTmp) * weights[1]; hitPointTmp.defaultUV.u = localPoint.x; hitPointTmp.defaultUV.v = localPoint.y; result += texZ->GetSpectrumValue(hitPointTmp) * weights[2]; return result; } Normal TriplanarTexture::Bump(const HitPoint &hitPoint, const float sampleDistance) const { if (enableUVlessBumpMap) { // Calculate bump map value at intersection point const float base = GetFloatValue(hitPoint); // Compute offset positions and evaluate displacement texture const Point origP = hitPoint.p; HitPoint hitPointTmp = hitPoint; Normal dhdx; // Note: I should update not only hitPointTmp.p but also hitPointTmp.shadeN // however I can't because I don't know dndv/dndu so this is nearly an hack. hitPointTmp.p.x = origP.x + sampleDistance; hitPointTmp.p.y = origP.y; hitPointTmp.p.z = origP.z; const float offsetX = GetFloatValue(hitPointTmp); dhdx.x = (offsetX - base) / sampleDistance; hitPointTmp.p.x = origP.x; hitPointTmp.p.y = origP.y + sampleDistance; hitPointTmp.p.z = origP.z; const float offsetY = GetFloatValue(hitPointTmp); dhdx.y = (offsetY - base) / sampleDistance; hitPointTmp.p.x = origP.x; hitPointTmp.p.y = origP.y; hitPointTmp.p.z = origP.z + sampleDistance; const float offsetZ = GetFloatValue(hitPointTmp); dhdx.z = (offsetZ - base) / sampleDistance; Normal newShadeN = Normalize(hitPoint.shadeN - dhdx); newShadeN *= (Dot(hitPoint.shadeN, newShadeN) < 0.f) ? -1.f : 1.f; return newShadeN; } else return Texture::Bump(hitPoint, sampleDistance); } Properties TriplanarTexture::ToProperties(const ImageMapCache &imgMapCache, const bool useRealFileName) const { Properties props; const string name = GetName(); props.Set(Property("scene.textures." + name + ".type")("triplanar")); props.Set(Property("scene.textures." + name + ".texture1")(texX->GetSDLValue())); props.Set(Property("scene.textures." + name + ".texture2")(texY->GetSDLValue())); props.Set(Property("scene.textures." + name + ".texture3")(texZ->GetSDLValue())); props.Set(Property("scene.textures." + name + ".uvlessbumpmap.enable")(enableUVlessBumpMap)); props.Set(mapping->ToProperties("scene.textures." + name + ".mapping")); return props; }
4,684
1,509
// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions 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. /// \file /// Tests for the RawMultiAxisDevice class. #include <memory> #include <string> #include <boost/thread.hpp> #include <boost/chrono.hpp> #include <gtest/gtest.h> #include "SurgSim/Devices/MultiAxis/RawMultiAxisDevice.h" #include "SurgSim/DataStructures/DataGroup.h" #include "SurgSim/Math/RigidTransform.h" #include "SurgSim/Math/Matrix.h" #include "SurgSim/Testing/MockInputOutput.h" using SurgSim::Devices::RawMultiAxisDevice; using SurgSim::Devices::RawMultiAxisScaffold; using SurgSim::DataStructures::DataGroup; using SurgSim::Math::RigidTransform3d; using SurgSim::Math::Matrix44d; using SurgSim::Testing::MockInputOutput; TEST(RawMultiAxisDeviceTest, CreateUninitializedDevice) { std::shared_ptr<RawMultiAxisDevice> device = std::make_shared<RawMultiAxisDevice>("TestRawMultiAxis"); ASSERT_TRUE(device != nullptr) << "Device creation failed."; } TEST(RawMultiAxisDeviceTest, CreateAndInitializeDevice) { std::shared_ptr<RawMultiAxisDevice> device = std::make_shared<RawMultiAxisDevice>("TestRawMultiAxis"); ASSERT_TRUE(device != nullptr) << "Device creation failed."; EXPECT_FALSE(device->isInitialized()); ASSERT_TRUE(device->initialize()) << "Initialization failed. Is a RawMultiAxis device plugged in?"; EXPECT_TRUE(device->isInitialized()); } TEST(RawMultiAxisDeviceTest, Name) { std::shared_ptr<RawMultiAxisDevice> device = std::make_shared<RawMultiAxisDevice>("TestRawMultiAxis"); ASSERT_TRUE(device != nullptr) << "Device creation failed."; EXPECT_EQ("TestRawMultiAxis", device->getName()); EXPECT_TRUE(device->initialize()) << "Initialization failed. Is a RawMultiAxis device plugged in?"; EXPECT_EQ("TestRawMultiAxis", device->getName()); } TEST(RawMultiAxisDeviceTest, Factory) { std::shared_ptr<SurgSim::Input::DeviceInterface> device; ASSERT_NO_THROW(device = SurgSim::Input::DeviceInterface::getFactory().create( "SurgSim::Devices::RawMultiAxisDevice", "Device")); EXPECT_NE(nullptr, device); } static void testCreateDeviceSeveralTimes(bool doSleep) { for (int i = 0; i < 6; ++i) { std::shared_ptr<RawMultiAxisDevice> device = std::make_shared<RawMultiAxisDevice>("TestRawMultiAxis"); ASSERT_TRUE(device != nullptr) << "Device creation failed."; ASSERT_TRUE(device->initialize()) << "Initialization failed. Is a RawMultiAxis device plugged in?"; if (doSleep) { boost::this_thread::sleep_until(boost::chrono::steady_clock::now() + boost::chrono::milliseconds(100)); } // the device will be destroyed here } } TEST(RawMultiAxisDeviceTest, CreateDeviceSeveralTimes) { testCreateDeviceSeveralTimes(true); } TEST(RawMultiAxisDeviceTest, CreateSeveralDevices) { std::shared_ptr<RawMultiAxisDevice> device1 = std::make_shared<RawMultiAxisDevice>("RawMultiAxis1"); ASSERT_TRUE(device1 != nullptr) << "Device creation failed."; ASSERT_TRUE(device1->initialize()) << "Initialization failed. Is a RawMultiAxis device plugged in?"; // We can't check what happens with the scaffolds, since those are no longer a part of the device's API... std::shared_ptr<RawMultiAxisDevice> device2 = std::make_shared<RawMultiAxisDevice>("RawMultiAxis2"); ASSERT_TRUE(device2 != nullptr) << "Device creation failed."; if (! device2->initialize()) { std::cerr << "[Warning: second RawMultiAxis controller did not come up; is it plugged in?]" << std::endl; } } TEST(RawMultiAxisDeviceTest, CreateDevicesWithSameName) { std::shared_ptr<RawMultiAxisDevice> device1 = std::make_shared<RawMultiAxisDevice>("RawMultiAxis"); ASSERT_TRUE(device1 != nullptr) << "Device creation failed."; ASSERT_TRUE(device1->initialize()) << "Initialization failed. Is a RawMultiAxis device plugged in?"; std::shared_ptr<RawMultiAxisDevice> device2 = std::make_shared<RawMultiAxisDevice>("RawMultiAxis"); ASSERT_TRUE(device2 != nullptr) << "Device creation failed."; ASSERT_FALSE(device2->initialize()) << "Initialization succeeded despite duplicate name."; } // Create a string representation from an int. // C++11 adds std::to_string() to do this for various types, but VS2010 only half-supports that. template <typename T> inline std::string makeString(T value) { std::ostringstream out; out << value; return out.str(); } TEST(RawMultiAxisDeviceTest, CreateAllDevices) { std::vector<std::shared_ptr<RawMultiAxisDevice>> devices; for (int i = 1; ; ++i) { std::string name = "RawMultiAxis" + makeString(i); std::shared_ptr<RawMultiAxisDevice> device = std::make_shared<RawMultiAxisDevice>(name); ASSERT_TRUE(device != nullptr) << "Device creation failed."; if (! device->initialize()) { break; } devices.emplace_back(std::move(device)); } std::cout << devices.size() << " devices initialized." << std::endl; ASSERT_GT(devices.size(), 0U) << "Initialization failed. Is a RawMultiAxis device plugged in?"; } TEST(RawMultiAxisDeviceTest, InputConsumer) { std::shared_ptr<RawMultiAxisDevice> device = std::make_shared<RawMultiAxisDevice>("TestRawMultiAxis"); ASSERT_TRUE(device != nullptr) << "Device creation failed."; ASSERT_TRUE(device->initialize()) << "Initialization failed. Is a RawMultiAxis device plugged in?"; std::shared_ptr<MockInputOutput> consumer = std::make_shared<MockInputOutput>(); EXPECT_EQ(0, consumer->m_numTimesInitializedInput); EXPECT_EQ(0, consumer->m_numTimesReceivedInput); EXPECT_FALSE(device->removeInputConsumer(consumer)); EXPECT_EQ(0, consumer->m_numTimesInitializedInput); EXPECT_EQ(0, consumer->m_numTimesReceivedInput); EXPECT_TRUE(device->addInputConsumer(consumer)); // Adding the same input consumer again should fail. EXPECT_FALSE(device->addInputConsumer(consumer)); // Sleep for a second, to see how many times the consumer is invoked. // (A RawMultiAxis device updates internally at 60Hz, but our code currently runs at 100Hz to reduce latency.) boost::this_thread::sleep_until(boost::chrono::steady_clock::now() + boost::chrono::milliseconds(1000)); EXPECT_TRUE(device->removeInputConsumer(consumer)); // Removing the same input consumer again should fail. EXPECT_FALSE(device->removeInputConsumer(consumer)); // Check the number of invocations. EXPECT_EQ(1, consumer->m_numTimesInitializedInput); EXPECT_GE(consumer->m_numTimesReceivedInput, 90); EXPECT_LE(consumer->m_numTimesReceivedInput, 110); EXPECT_TRUE(consumer->m_lastReceivedInput.poses().hasData(SurgSim::DataStructures::Names::POSE)); EXPECT_TRUE(consumer->m_lastReceivedInput.booleans().hasData(SurgSim::DataStructures::Names::BUTTON_1)); EXPECT_TRUE(consumer->m_lastReceivedInput.booleans().hasData(SurgSim::DataStructures::Names::BUTTON_2)); EXPECT_TRUE(consumer->m_lastReceivedInput.booleans().hasData(SurgSim::DataStructures::Names::BUTTON_3)); EXPECT_TRUE(consumer->m_lastReceivedInput.booleans().hasData(SurgSim::DataStructures::Names::BUTTON_4)); } TEST(RawMultiAxisDeviceTest, OutputProducer) { std::shared_ptr<RawMultiAxisDevice> device = std::make_shared<RawMultiAxisDevice>("TestRawMultiAxis"); ASSERT_TRUE(device != nullptr) << "Device creation failed."; ASSERT_TRUE(device->initialize()) << "Initialization failed. Is a RawMultiAxis device plugged in?"; std::shared_ptr<MockInputOutput> producer = std::make_shared<MockInputOutput>(); EXPECT_EQ(0, producer->m_numTimesRequestedOutput); EXPECT_FALSE(device->removeOutputProducer(producer)); EXPECT_EQ(0, producer->m_numTimesRequestedOutput); EXPECT_TRUE(device->setOutputProducer(producer)); // Sleep for a second, to see how many times the producer is invoked. // (A RawMultiAxis device is does not request any output.) boost::this_thread::sleep_until(boost::chrono::steady_clock::now() + boost::chrono::milliseconds(1000)); EXPECT_TRUE(device->removeOutputProducer(producer)); // Removing the same input producer again should fail. EXPECT_FALSE(device->removeOutputProducer(producer)); // Check the number of invocations. EXPECT_GE(producer->m_numTimesRequestedOutput, 90); EXPECT_LE(producer->m_numTimesRequestedOutput, 110); }
8,606
2,886
#include "throws/throw_curves/throw_movement_position_only.h" namespace bitbots_throw{ ThrowMovementPositionOnly::ThrowMovementPositionOnly(std::shared_ptr<ThrowMaterial> material) : ThrowMovement(material){ } void ThrowMovementPositionOnly::add_movement_prepare_throw(){ throw_start_time_ = trajectory_time_; ThrowMovement::add_movement_prepare_throw(); } void ThrowMovementPositionOnly::add_movement_throw(){ // get Values auto current_throw_release_time = trajectory_time_; double duration_throw = sp_service_->get_movement_time_throw(); duration_throw -= sp_service_->get_movement_offset_move_arms_away_from_ball(); Struct3dRPY velocity = sp_service_->calculate_throw_velocity(duration_throw); auto left_arm_throw_release = sp_service_->get_left_arm_throw_release(); auto diff = left_arm_throw_release.x_ - sp_service_->get_left_arm_ball_behind_head().x_; trajectory_time_ = throw_start_time_ + (diff / velocity.x_); //// Movement ////==== Release ball add_to_left_hand( left_arm_throw_release); add_to_right_hand(sp_service_->get_right_arm_throw_release()); ////==== Move arms away from the ball trajectory_time_ += sp_service_->get_movement_offset_move_arms_away_from_ball(); add_to_left_hand(sp_service_->get_left_arm_move_away_from_ball(velocity.x_)); add_to_right_hand(sp_service_->get_right_arm_move_away_from_ball(velocity.x_)); if(current_throw_release_time > trajectory_time_){ trajectory_time_ = current_throw_release_time; } } } //bitbots_throw
1,676
553
#include<math.h> double cubeandmult(double u, double v) { return(pow(u,3)*v); }
82
37
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2017 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Andrey Abramov /// @author Vasiliy Nabatchikov //////////////////////////////////////////////////////////////////////////////// #include <algorithm> #include "tests_shared.hpp" #include "analysis/token_attributes.hpp" #include "formats/empty_term_reader.hpp" #include "search/scorers.hpp" #include "search/score.hpp" #include "utils/misc.hpp" NS_LOCAL struct empty_attribute_provider : irs::attribute_provider { virtual irs::attribute* get_mutable(irs::type_info::type_id) { return nullptr; } }; empty_attribute_provider EMPTY_ATTRIBUTE_PROVIDER; template<size_t Size, size_t Align> struct aligned_value { irs::memory::aligned_storage<Size, Align> data; // need these operators only to be sort API compliant bool operator<(const aligned_value&) const noexcept { return false; } const aligned_value& operator+=(const aligned_value&) const noexcept { return *this; } const aligned_value& operator+(const aligned_value&) const noexcept { return *this; } }; template<typename ScoreType, typename StatsType> struct aligned_scorer : public irs::sort { class prepared final : public irs::prepared_sort_basic<ScoreType, StatsType> { public: explicit prepared(const irs::flags& features, bool empty_scorer) noexcept : features_(features), empty_scorer_(empty_scorer) { } virtual field_collector::ptr prepare_field_collector() const override { return nullptr; } virtual term_collector::ptr prepare_term_collector() const override { return nullptr; } virtual void collect( irs::byte_type*, const irs::index_reader&, const field_collector*, const term_collector* ) const override { // NOOP } virtual irs::score_function prepare_scorer( const irs::sub_reader& /*segment*/, const irs::term_reader& /*field*/, const irs::byte_type* /*stats*/, irs::byte_type* score_buf, const irs::attribute_provider& /*doc_attrs*/, irs::boost_t /*boost*/) const override { if (empty_scorer_) { return { nullptr, nullptr }; } struct ctx : public irs::score_ctx { ctx(const irs::byte_type* score_buf) : score_buf(score_buf) { } const irs::byte_type* score_buf; }; return { std::make_unique<ctx>(score_buf), [](irs::score_ctx* ctx) noexcept { return reinterpret_cast<struct ctx*>(ctx)->score_buf; } }; } virtual const irs::flags& features() const override { return features_; } irs::flags features_; bool empty_scorer_; }; static constexpr irs::string_ref type_name() noexcept { return __FILE__ ":" STRINGIFY(__LINE__); } static ptr make(const irs::flags& features = irs::flags::empty_instance(), bool empty_scorer = true) { return std::make_unique<aligned_scorer>(features, empty_scorer); } explicit aligned_scorer( const irs::flags& features = irs::flags::empty_instance(), bool empty_scorer = true) : irs::sort(irs::type<aligned_scorer>::get()), features_(features), empty_scorer_(empty_scorer) { } virtual irs::sort::prepared::ptr prepare() const override { return irs::memory::make_unique<aligned_scorer<ScoreType, StatsType>::prepared>( features_, empty_scorer_); } irs::flags features_; bool empty_scorer_; }; struct dummy_scorer0: public irs::sort { static constexpr irs::string_ref type_name() noexcept { return __FILE__ ":" STRINGIFY(__LINE__); } static ptr make() { return std::make_unique<dummy_scorer0>(); } dummy_scorer0(): irs::sort(irs::type<dummy_scorer0>::get()) { } virtual prepared::ptr prepare() const override { return nullptr; } }; NS_END TEST(sort_tests, order_equal) { struct dummy_scorer1: public irs::sort { static constexpr irs::string_ref type_name() noexcept { return __FILE__ ":" STRINGIFY(__LINE__); } static ptr make() { return std::make_unique<dummy_scorer1>(); } dummy_scorer1(): irs::sort(irs::type<dummy_scorer1>::get()) { } virtual prepared::ptr prepare() const override { return nullptr; } }; // empty == empty { irs::order ord0; irs::order ord1; ASSERT_TRUE(ord0 == ord1); ASSERT_FALSE(ord0 != ord1); } // empty == !empty { irs::order ord0; irs::order ord1; ord1.add<dummy_scorer1>(false); ASSERT_FALSE(ord0 == ord1); ASSERT_TRUE(ord0 != ord1); } // different sort types { irs::order ord0; irs::order ord1; ord0.add<dummy_scorer0>(false); ord1.add<dummy_scorer1>(false); ASSERT_FALSE(ord0 == ord1); ASSERT_TRUE(ord0 != ord1); } // different order same sort type { irs::order ord0; irs::order ord1; ord0.add<dummy_scorer0>(false); ord0.add<dummy_scorer1>(false); ord1.add<dummy_scorer1>(false); ord1.add<dummy_scorer0>(false); ASSERT_FALSE(ord0 == ord1); ASSERT_TRUE(ord0 != ord1); } // different number same sorts { irs::order ord0; irs::order ord1; ord0.add<dummy_scorer0>(false); ord1.add<dummy_scorer0>(false); ord1.add<dummy_scorer0>(false); ASSERT_FALSE(ord0 == ord1); ASSERT_TRUE(ord0 != ord1); } // different number different sorts { irs::order ord0; irs::order ord1; ord0.add<dummy_scorer0>(false); ord1.add<dummy_scorer1>(false); ord1.add<dummy_scorer1>(false); ASSERT_FALSE(ord0 == ord1); ASSERT_TRUE(ord0 != ord1); } // same sorts same types { irs::order ord0; irs::order ord1; ord0.add<dummy_scorer0>(false); ord0.add<dummy_scorer1>(false); ord1.add<dummy_scorer0>(false); ord1.add<dummy_scorer1>(false); ASSERT_TRUE(ord0 == ord1); ASSERT_FALSE(ord0 != ord1); } } TEST(sort_tests, static_const) { ASSERT_TRUE(irs::order::unordered().empty()); ASSERT_TRUE(irs::order::prepared::unordered().empty()); } TEST(sort_tests, score_traits) { const size_t values[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; const size_t* ptrs[IRESEARCH_COUNTOF(values)]; std::iota(std::begin(ptrs), std::end(ptrs), values); irs::order_bucket bucket(aligned_scorer<size_t, size_t>().prepare(), 0, 0, true); for (size_t i = 0; i < IRESEARCH_COUNTOF(values); ++i) { size_t max_dst = 0; size_t aggregated_dst = 0; irs::score_traits<size_t>::bulk_aggregate( &bucket, reinterpret_cast<irs::byte_type*>(&aggregated_dst), reinterpret_cast<const irs::byte_type**>(ptrs), i); irs::score_traits<size_t>::bulk_max( &bucket, reinterpret_cast<irs::byte_type*>(&max_dst), reinterpret_cast<const irs::byte_type**>(ptrs), i); const auto begin = std::begin(values); const auto end = begin + i; ASSERT_EQ(std::accumulate(begin, end, 0), aggregated_dst); const auto it = std::max_element(begin, end); ASSERT_EQ(end == it ? 0 : *it, max_dst); } } TEST(sort_tests, merge_func) { aligned_scorer<size_t, size_t> scorer; auto prepared = scorer.prepare(); ASSERT_NE(nullptr, prepared); ASSERT_EQ(prepared->aggregate_func(), irs::sort::prepared::merge_func<irs::sort::MergeType::AGGREGATE>(*prepared)); ASSERT_EQ(&irs::score_traits<size_t>::aggregate, prepared->aggregate_func()); ASSERT_EQ(prepared->max_func(), irs::sort::prepared::merge_func<irs::sort::MergeType::MAX>(*prepared)); ASSERT_EQ(&irs::score_traits<size_t>::max, prepared->max_func()); // ensure order optimizes single scorer cases { irs::order ord; ord.add<aligned_scorer<size_t, size_t>>(true); auto prepared_order = ord.prepare(); ASSERT_FALSE(prepared_order.empty()); ASSERT_EQ(prepared_order.prepare_merger(irs::sort::MergeType::AGGREGATE), prepared->aggregate_func()); ASSERT_EQ(prepared_order.prepare_merger(irs::sort::MergeType::MAX), prepared->max_func()); } } TEST(sort_tests, prepare_order) { { irs::order ord; ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<1, 4>, aligned_value<1, 4>>>(true); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-0 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags::empty_instance(), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(1, prepared.size()); ASSERT_EQ(4, prepared.score_size()); ASSERT_EQ(4, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_TRUE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(0 == scorers.size()); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_TRUE(score.is_default()); } { irs::order ord; ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(true); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(true); ord.add<aligned_scorer<aligned_value<4, 4>, aligned_value<4, 4>>>(true); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-1 { 2, 2 }, // score: 2-3 { 4, 4 }, // score: 4-7 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags::empty_instance(), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(3, prepared.size()); ASSERT_EQ(8, prepared.score_size()); ASSERT_EQ(8, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_TRUE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(0 == scorers.size()); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_TRUE(score.is_default()); } { irs::order ord; ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(true, irs::flags::empty_instance(), false); // returns valid scorers ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(true); ord.add<aligned_scorer<aligned_value<4, 4>, aligned_value<4, 4>>>(true); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-1 { 2, 2 }, // score: 2-3 { 4, 4 }, // score: 4-7 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags::empty_instance(), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(3, prepared.size()); ASSERT_EQ(8, prepared.score_size()); ASSERT_EQ(8, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_TRUE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(1 == scorers.size()); auto& scorer = scorers.front(); ASSERT_NE(nullptr, scorer.func()); ASSERT_EQ(&prepared[0], scorer.bucket); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_FALSE(score.is_default()); ASSERT_EQ(score_buf.c_str(), score.evaluate()); // returns pointer to the beginning } { irs::order ord; ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(true); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(true, irs::flags::empty_instance(), false); // returns valid scorer ord.add<aligned_scorer<aligned_value<4, 4>, aligned_value<4, 4>>>(true); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-1 { 2, 2 }, // score: 2-3 { 4, 4 }, // score: 4-7 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags::empty_instance(), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(3, prepared.size()); ASSERT_EQ(8, prepared.score_size()); ASSERT_EQ(8, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_TRUE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(1 == scorers.size()); auto& scorer = scorers.front(); ASSERT_NE(nullptr, scorer.func()); ASSERT_EQ(&prepared[1], scorer.bucket); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_FALSE(score.is_default()); ASSERT_EQ(score_buf.c_str(), score.evaluate()); // returns pointer to the beginning of score_buf } { irs::order ord; ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(true); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(true); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(true); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-0 { 1, 1 }, // score: 1-1 { 2, 2 } // score: 2-2 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags::empty_instance(), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(3, prepared.size()); ASSERT_EQ(3, prepared.score_size()); ASSERT_EQ(3, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_TRUE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(0 == scorers.size()); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_TRUE(score.is_default()); } { irs::order ord; ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(true, irs::flags::empty_instance(), false); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(true, irs::flags::empty_instance(), false); ord.add<dummy_scorer0>(false); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-0, padding: 1-1 { 2, 2 } // score: 2-3 }; auto prepared = ord.prepare(); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(irs::flags::empty_instance(), prepared.features()); ASSERT_EQ(2, prepared.size()); ASSERT_EQ(4, prepared.score_size()); ASSERT_EQ(4, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_TRUE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(2 == scorers.size()); auto& front = scorers.front(); ASSERT_NE(nullptr, front.func()); ASSERT_EQ(&prepared[0], front.bucket); auto& back = scorers.back(); ASSERT_NE(nullptr, back.func()); ASSERT_EQ(&prepared[1], back.bucket); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_FALSE(score.is_default()); ASSERT_EQ(score_buf.c_str(), score.evaluate()); // returns pointer to the beginning of score_buf } { irs::order ord; ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(true, irs::flags::empty_instance(), false); ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(true, irs::flags::empty_instance(), false); ord.add<aligned_scorer<aligned_value<4, 4>, aligned_value<4, 4>>>(true, irs::flags::empty_instance(), false); auto prepared = ord.prepare(); ASSERT_EQ(irs::flags::empty_instance(), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(3, prepared.size()); ASSERT_EQ(8, prepared.score_size()); ASSERT_EQ(8, prepared.stats_size()); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-0, padding: 1-1 { 2, 2 }, // score: 2-3 { 4, 4 } // score: 4-7 }; auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_TRUE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(3 == scorers.size()); { auto& scorer = scorers[0]; ASSERT_NE(nullptr, scorer.func()); ASSERT_EQ(&prepared[0], scorer.bucket); } { auto& scorer = scorers[1]; ASSERT_NE(nullptr, scorer.func()); ASSERT_EQ(&prepared[1], scorer.bucket); } { auto& scorer = scorers[2]; ASSERT_NE(nullptr, scorer.func()); ASSERT_EQ(&prepared[2], scorer.bucket); } irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_FALSE(score.is_default()); ASSERT_EQ(score_buf.c_str(), score.evaluate()); // returns pointer to the beginning of score_buf } { irs::order ord; ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::document>::get()}, false); ord.add<aligned_scorer<aligned_value<5, 4>, aligned_value<5, 4>>>(false); ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(false, irs::flags{irs::type<irs::frequency>::get()}, false); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-0, padding: 1-3 { 4, 4 }, // score: 4-8, padding: 9-11 { 12, 12 } // score: 12-14 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags({ irs::type<irs::document>::get(), irs::type<irs::frequency>::get() }), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(3, prepared.size()); ASSERT_EQ(16, prepared.score_size()); ASSERT_EQ(16, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_FALSE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(2 == scorers.size()); { auto& scorer = scorers[0]; ASSERT_NE(nullptr, scorer.func()); ASSERT_EQ(&prepared[0], scorer.bucket); } { auto& scorer = scorers[1]; ASSERT_NE(nullptr, scorer.func()); ASSERT_EQ(&prepared[2], scorer.bucket); } irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_FALSE(score.is_default()); ASSERT_EQ(score_buf.c_str(), score.evaluate()); // returns pointer to the beginning of score_buf } { irs::order ord; ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<3, 1>, aligned_value<3, 1>>>(false, irs::flags{irs::type<irs::document>::get()}); ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<27, 8>, aligned_value<27, 8>>>(false); ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<7, 4>, aligned_value<7, 4>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<dummy_scorer0>(false); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-2, padding: 3-7 { 8, 8 }, // score: 8-34, padding: 35-39 { 40, 40 }, // score: 40-46, padding: 47-47 { 48, 48 }, // score: 48-48 { 49, 49 } // score: 49-49 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags({ irs::type<irs::document>::get(), irs::type<irs::frequency>::get() }), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(5, prepared.size()); ASSERT_EQ(56, prepared.score_size()); ASSERT_EQ(56, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_FALSE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(0 == scorers.size()); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_TRUE(score.is_default()); } { irs::order ord; ord.add<aligned_scorer<aligned_value<27, 8>, aligned_value<27, 8>>>(false); ord.add<aligned_scorer<aligned_value<3, 1>, aligned_value<3, 1>>>(false, irs::flags{irs::type<irs::document>::get()}); ord.add<aligned_scorer<aligned_value<7, 4>, aligned_value<7, 4>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-26, padding: 27-31 { 32, 32 }, // score: 32-34, padding: 34-35 { 36, 36 }, // score: 36-42, padding: 43-43 { 44, 44 }, // score: 44-44 { 45, 45 } // score: 45-45 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags({ irs::type<irs::document>::get(), irs::type<irs::frequency>::get() }), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(5, prepared.size()); ASSERT_EQ(48, prepared.score_size()); ASSERT_EQ(48, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_FALSE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(0 == scorers.size()); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_TRUE(score.is_default()); } { irs::order ord; ord.add<aligned_scorer<aligned_value<27, 8>, aligned_value<27, 8>>>(false); ord.add<aligned_scorer<aligned_value<7, 4>, aligned_value<7, 4>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<3, 1>, aligned_value<3, 1>>>(false, irs::flags{irs::type<irs::document>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-26, padding: 27-31 { 32, 32 }, // score: 32-38, padding: 39-39 { 40, 40 }, // score: 40-42 { 43, 43 }, // score: 43-43 { 44, 44 } // score: 44-44 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags({ irs::type<irs::document>::get(), irs::type<irs::frequency>::get() }), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(5, prepared.size()); ASSERT_EQ(48, prepared.score_size()); ASSERT_EQ(48, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_FALSE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(0 == scorers.size()); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_TRUE(score.is_default()); } { irs::order ord; ord.add<aligned_scorer<aligned_value<27, 8>, aligned_value<27, 8>>>(false); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(false, irs::flags{irs::type<irs::document>::get()}); ord.add<aligned_scorer<aligned_value<4, 4>, aligned_value<4, 4>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-26, padding: 27-31 { 32, 32 }, // score: 32-33, padding: 34-35 { 36, 36 }, // score: 36-39 { 40, 40 }, // score: 40-40 { 41, 41 } // score: 41-41 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags({ irs::type<irs::document>::get(), irs::type<irs::frequency>::get() }), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(5, prepared.size()); ASSERT_EQ(48, prepared.score_size()); ASSERT_EQ(48, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_FALSE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(0 == scorers.size()); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_TRUE(score.is_default()); } { irs::order ord; ord.add<aligned_scorer<aligned_value<27, 8>, aligned_value<27, 8>>>(false); ord.add<aligned_scorer<aligned_value<4, 4>, aligned_value<4, 4>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(false, irs::flags{irs::type<irs::document>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-26, padding: 27-31 { 32, 32 }, // score: 32-35 { 36, 36 }, // score: 36-37 { 38, 38 }, // score: 38-38 { 39, 39 } // score: 39-39 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags({ irs::type<irs::document>::get(), irs::type<irs::frequency>::get() }), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(5, prepared.size()); ASSERT_EQ(40, prepared.score_size()); ASSERT_EQ(40, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_FALSE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(0 == scorers.size()); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_TRUE(score.is_default()); } { irs::order ord; ord.add<aligned_scorer<aligned_value<27, 8>, aligned_value<27, 8>>>(false); ord.add<aligned_scorer<aligned_value<4, 4>, aligned_value<4, 4>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(false, irs::flags{irs::type<irs::document>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-26, padding: 27-31 { 32, 32 }, // score: 32-35 { 36, 36 }, // score: 36-37 { 38, 38 }, // score: 38-38 { 39, 39 } // score: 39-39 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags({ irs::type<irs::document>::get(), irs::type<irs::frequency>::get() }), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(5, prepared.size()); ASSERT_EQ(40, prepared.score_size()); ASSERT_EQ(40, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_FALSE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(0 == scorers.size()); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_TRUE(score.is_default()); } } TEST(score_function_test, construct) { struct ctx : irs::score_ctx { irs::byte_type buf[1]{}; }; { irs::score_function func; ASSERT_TRUE(func); ASSERT_NE(nullptr, func.func()); ASSERT_EQ(nullptr, func.ctx()); ASSERT_EQ(nullptr, func()); } { struct ctx ctx; auto score_func = [](irs::score_ctx* ctx) -> const irs::byte_type* { return static_cast<struct ctx*>(ctx)->buf; }; irs::score_function func(&ctx, score_func); ASSERT_TRUE(func); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_EQ(&ctx, func.ctx()); ASSERT_EQ(ctx.buf, func()); } { struct ctx ctx; auto score_func = [](irs::score_ctx* ctx) -> const irs::byte_type* { return static_cast<struct ctx*>(ctx)->buf; }; irs::score_function func( irs::memory::to_managed<irs::score_ctx, false>(&ctx), score_func); ASSERT_TRUE(func); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_EQ(&ctx, func.ctx()); ASSERT_EQ(ctx.buf, func()); } { auto score_func = [](irs::score_ctx* ctx) -> const irs::byte_type* { auto* buf = static_cast<struct ctx*>(ctx)->buf; buf[0] = 42; return buf; }; irs::score_function func(std::make_unique<struct ctx>(), score_func); ASSERT_TRUE(func); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_NE(nullptr, func.ctx()); auto* value = func(); ASSERT_NE(nullptr, value); ASSERT_EQ(42, *value); } { auto score_func = [](irs::score_ctx* ctx) -> const irs::byte_type* { auto* buf = static_cast<struct ctx*>(ctx)->buf; buf[0] = 42; return buf; }; irs::score_function func( irs::memory::to_managed<irs::score_ctx>(std::make_unique<struct ctx>()), score_func); ASSERT_TRUE(func); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_NE(nullptr, func.ctx()); auto* value = func(); ASSERT_NE(nullptr, value); ASSERT_EQ(42, *value); } } TEST(score_function_test, reset) { struct ctx : irs::score_ctx { irs::byte_type buf[1]{}; }; irs::score_function func; ASSERT_TRUE(func); ASSERT_NE(nullptr, func.func()); ASSERT_EQ(nullptr, func.ctx()); ASSERT_EQ(nullptr, func()); { struct ctx ctx; auto score_func = [](irs::score_ctx* ctx) -> const irs::byte_type* { return static_cast<struct ctx*>(ctx)->buf; }; func.reset(&ctx, score_func); ASSERT_TRUE(func); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_EQ(&ctx, func.ctx()); ASSERT_EQ(ctx.buf, func()); func.reset( irs::memory::to_managed<irs::score_ctx, false>(&ctx), score_func); ASSERT_TRUE(func); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_EQ(&ctx, func.ctx()); ASSERT_EQ(ctx.buf, func()); } { auto score_func = [](irs::score_ctx* ctx) -> const irs::byte_type* { auto* buf = static_cast<struct ctx*>(ctx)->buf; buf[0] = 42; return buf; }; func.reset(std::make_unique<struct ctx>(), score_func); ASSERT_TRUE(func); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_NE(nullptr, func.ctx()); auto* value = func(); ASSERT_NE(nullptr, value); ASSERT_EQ(42, *value); } { auto score_func = [](irs::score_ctx* ctx) -> const irs::byte_type* { auto* buf = static_cast<struct ctx*>(ctx)->buf; buf[0] = 43; return buf; }; func.reset( irs::memory::to_managed<irs::score_ctx>(std::make_unique<struct ctx>()), score_func); ASSERT_TRUE(func); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_NE(nullptr, func.ctx()); auto* value = func(); ASSERT_NE(nullptr, value); ASSERT_EQ(43, *value); } { struct ctx ctx; func.reset(&ctx, nullptr); ASSERT_FALSE(func); } } TEST(score_function_test, move) { struct ctx : irs::score_ctx { irs::byte_type buf[1]{}; }; // move construction { struct ctx ctx; auto score_func = [](irs::score_ctx* ctx) -> const irs::byte_type* { return static_cast<struct ctx*>(ctx)->buf; }; irs::score_function func(&ctx, score_func); ASSERT_TRUE(func); ASSERT_EQ(&ctx, func.ctx()); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_EQ(ctx.buf, func()); irs::score_function moved(std::move(func)); ASSERT_TRUE(moved); ASSERT_EQ(&ctx, moved.ctx()); ASSERT_EQ(static_cast<irs::score_f>(score_func), moved.func()); ASSERT_EQ(ctx.buf, moved()); ASSERT_TRUE(func); ASSERT_EQ(nullptr, func.ctx()); ASSERT_NE(static_cast<irs::score_f>(score_func), func.func()); ASSERT_EQ(nullptr, func()); } // move assignment { struct ctx ctx; auto score_func = [](irs::score_ctx* ctx) -> const irs::byte_type* { return static_cast<struct ctx*>(ctx)->buf; }; irs::score_function moved; ASSERT_TRUE(moved); ASSERT_EQ(nullptr, moved.ctx()); ASSERT_NE(static_cast<irs::score_f>(score_func), moved.func()); ASSERT_EQ(nullptr, moved()); irs::score_function func(&ctx, score_func); ASSERT_TRUE(func); ASSERT_EQ(&ctx, func.ctx()); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_EQ(ctx.buf, func()); moved = std::move(func); ASSERT_TRUE(moved); ASSERT_EQ(&ctx, moved.ctx()); ASSERT_EQ(static_cast<irs::score_f>(score_func), moved.func()); ASSERT_EQ(ctx.buf, moved()); ASSERT_TRUE(func); ASSERT_EQ(nullptr, func.ctx()); ASSERT_NE(static_cast<irs::score_f>(score_func), func.func()); ASSERT_EQ(nullptr, func()); } } TEST(score_function_test, equality) { struct ctx : irs::score_ctx { irs::byte_type buf[1]{}; } ctx0, ctx1; auto score_func0 = [](irs::score_ctx* ctx) -> const irs::byte_type* { return static_cast<struct ctx*>(ctx)->buf; }; auto score_func1 = [](irs::score_ctx* ctx) -> const irs::byte_type* { return static_cast<struct ctx*>(ctx)->buf; }; irs::score_function func0; irs::score_function func1(&ctx0, score_func0); irs::score_function func2(&ctx1, score_func1); irs::score_function func3(&ctx0, score_func1); irs::score_function func4(&ctx1, score_func0); ASSERT_EQ(func0, irs::score_function()); ASSERT_NE(func0, func1); ASSERT_NE(func2, func3); ASSERT_NE(func2, func4); ASSERT_EQ(func1, irs::score_function(&ctx0, score_func0)); ASSERT_EQ(func2, irs::score_function(&ctx1, score_func1)); }
43,626
16,527
// 1128_N_Queens_Puzzle.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include "pch.h" #include <iostream> #include <vector> #include <cmath> #include <map> using namespace std; int main() { int k, n; cin >> k; for (int i = 0; i < k; ++i) { cin >> n; vector<bool> row(n + 1, false); map<int, bool> diagsum; map<int, bool> diagdel; int p; bool flag = true; for (int j = 1; j <= n; ++j) { cin >> p; if (row[p] || diagsum[j + p] || diagdel[j - p]) flag = false; row[p] = diagsum[j + p] = diagdel[j - p] = true; } if (flag) { cout << "YES" << endl; } else { cout << "NO" << endl; } } }
627
343
/****************************************************************************** ** ** Copyright 2009-2020 Gunjou Inc. All rights reserved. ** Contact: Gunjou Inc. (information@gunjou.co.jp) ** ** This software is released under the MIT License. ** https://github.com/gunjouinc/Aoiduino/blob/master/LICENSE ** ******************************************************************************/ #ifdef ESP8266 /** Esp WiFi timeout */ #define ESP_WIFI_TIMEOUT 30000 #include "esp-esp8266.h" /* Flash */ #include <FS.h> FS *EspStorage = &SPIFFS; /* RTC */ #include <time.h> /* Servo */ #include <Servo.h> /* Ticker */ #include <Ticker.h> Ticker ticker; Ticker watchdog; uint32_t watchdogSecond = 0; uint32_t watchdogMills = 0; /* WiFi */ #include <ESP8266WiFi.h> #include <WiFiClient.h> #include <WiFiClientSecure.h> WiFiClient wifiClient; WiFiClientSecure wifiClientSecure; /** File mode - append */ #define _FILE_APPEND_ "a" /** File mode - read */ #define _FILE_READ_ "r" /** File mode - write */ #define _FILE_WRITE_ "w" /** Flash root path */ #define _FLASH_ "/mnt/spif" /** * @namespace AoiEsp * @brief Aoi esp classes. */ namespace AoiEsp { // Static variables. AoiBase::FunctionTable *Esp8266::m_functionTable = 0; Servo *Esp8266::m_servo = 0; int Esp8266::m_servoCount = 0; /** * @fn Esp8266::Esp8266( void ) * * Constructor. Member variables are initialized. */ Esp8266::Esp8266( void ) { if( m_functionTable ) return; // Sets function table, If there is no instance. AoiBase::FunctionTable ftl[] = { // ^ Please set your function to use. /* Arduino Core */ { "analogRead", &Arduino::analogRead }, { "analogWrite", &Arduino::analogWrite }, { "delay", &Arduino::delay }, { "delayMicroseconds", &Arduino::delayMicroseconds }, { "digitalRead", &Arduino::digitalRead }, { "digitalWrite", &Arduino::digitalWrite }, { "echo", &Arduino::echo }, { "micros", &Arduino::micros }, { "millis", &Arduino::millis }, { "noTone", &Arduino::noTone }, { "pinMode", &Arduino::pinMode }, { "tone", &Arduino::tone }, { "yield", &Arduino::yield }, /* File */ { ">", &Esp8266::create }, { ">>", &Esp8266::append }, { "cat", &Esp8266::read }, { "cd", &Esp8266::cd }, { "format", &Esp8266::format }, { "ll", &Esp8266::ll }, { "mkdir", &Esp8266::mkdir }, { "pwd", &Esp8266::pwd }, { "rm", &Esp8266::remove }, { "rmdir", &Esp8266::rmdir }, { "touch", &Esp8266::touch }, /* LowPower */ { "deepSleep", &Esp8266::deepSleep }, { "dmesg", &Esp8266::dmesg }, { "reboot", &Esp8266::restart }, /* HTTP */ { "httpBegin", &Esp8266::httpBegin }, { "httpGet", &AoiUtil::Http::httpGet }, { "httpPost", &Esp8266::httpPost }, /* RTC */ { "date", &Esp8266::date }, /* Servo */ { "servoAttach", &Esp8266::servoAttach }, { "servoBegin", &Esp8266::servoBegin }, { "servoEnd", &Esp8266::servoEnd }, { "servoWriteMicroseconds", &Esp8266::servoWriteMicroseconds }, /* Watchdog */ { "watchdogBegin", &Esp8266::watchdogBegin }, { "watchdogEnd", &Esp8266::watchdogEnd }, { "watchdogKick", &Esp8266::watchdogKick }, { "watchdogTimeleft", &Esp8266::watchdogTimeleft }, /* WiFi */ { "ifconfig", &Esp8266::ifConfig }, { "iwlist", &Esp8266::wifiScanNetworks }, { "wifiBegin", &Esp8266::wifiBegin }, { "wifiEnd", &Esp8266::wifiEnd }, { "wifiRtc", &Esp8266::wifiRtc }, // $ Please set your function to use. { "", 0 } }; // Creates function table to avoid kernel panic. uint8_t c = sizeof(ftl) / sizeof(AoiBase::FunctionTable); m_functionTable = Arduino::functionTable( ftl, c ); // Initalize library /* File */ SPIFFS.begin(); /* HTTP */ http = &wifiClient; } /** * @fn Esp8266::~Esp8266( void ) * * Destructor. Member variables are deleted. */ Esp8266::~Esp8266( void ) { } /** * @fn String Esp8266::className( void ) * * @see bool AbstractBase::className( void ) */ String Esp8266::className( void ) { return String( "Esp8266" ); } /** * @fn bool Esp8266::isExist( const String &function ) * * @see bool AbstractBase::isExist( const String &function ) */ bool Esp8266::isExist( const String &function ) { return Arduino::isExist( function, m_functionTable ); } /** * @fn String Esp8266::practice( StringList *args ) * * @see String AbstractBase::practice( StringList *args ) */ String Esp8266::practice( StringList *args ) { return Arduino::practice( args, m_functionTable ); } /** * @fn String Esp8266::usages( void ) * * @see String AbstractBase::usages( void ) */ String Esp8266::usages( void ) { return Arduino::usages( m_functionTable ); } /** * @fn StringList* Esp8266::rcScript( const String &index ) * * @see StringList* AbstractBase::rcScript( const String &index ) */ StringList* Esp8266::rcScript( const String &index ) { StringList *sl = 0; String s = appendRootPath( index ); if( !EspStorage->exists(s) ) return sl; File f = EspStorage->open( s, _FILE_READ_ ); if( f ) { String s = f.readString(); f.close(); sl = split( s, String(_lf) ); } return sl; } /** * @fn String Esp8266::append( StringList *args ) * * Append value on current device. * * @param[in] args Reference to arguments. * @return value string. */ String Esp8266::append( StringList *args ) { String s, t; int c = count( args ); if( c<2 ) s = usage( ">> file .+" ); else { t = appendRootPath( _a(0) ); // Create file if need if( !EspStorage->exists(t) ) { File w = EspStorage->open( t, _FILE_WRITE_ ); w.close(); } File f = EspStorage->open( t, _FILE_APPEND_ ); if( 0<f.size() ) f.print( _lf ); for( int i=1; i<c; i++ ) { if( 1<i ) f.print( STR_SPACE ); f.print( _a(i) ); } f.close(); // Re-open, Can't practice f.seek( 0 ) f = EspStorage->open( t, _FILE_READ_ ); s = prettyPrintTo( "value", f.readString() ); f.close(); } return s; } /** * @fn String Esp8266::cd( StringList *args ) * * Change device. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::cd( StringList *args ) { String s; String path; switch( count(args) ) { case 1: path = _a( 0 ); if( (path==_FLASH_) || (path=="/") ) EspStorage = &SPIFFS; else s = cd( 0 ); break; default: s = usage( "cd ("+String(_FLASH_)+")" ); break; } return s; } /** * @fn String Esp8266::create( StringList *args ) * * Create value on current device. * * @param[in] args Reference to arguments. * @return value string. */ String Esp8266::create( StringList *args ) { String s, t; int c = count( args ); if( c<2 ) s = usage( "> file .+" ); else { t = appendRootPath( _a(0) ); if( EspStorage->exists(t) ) EspStorage->remove( t ); s = append( args ); } return s; } /** * @fn String Esp8266::format( StringList *args ) * * Format file device. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::format( StringList *args ) { String s; String path; switch( count(args) ) { case 1: path = _a( 0 ); if( path==_FLASH_ ) SPIFFS.format(); else s = format( 0 ); break; default: s = usage( "format ("+String(_FLASH_)+")" ); break; } return s; } /** * @fn String Esp8266::ll( StringList *args ) * * Return file detail list in current device. * * @param[in] args Reference to arguments. * @return Current device. */ String Esp8266::ll( StringList *args ) { String s, p, root; DynamicJsonBuffer json; JsonArray &r = json.createArray(); Dir d; File f; switch( count(args) ) { case 1: root = _a( 0 ); case 0: // Root path root = appendRootPath( root ); d = EspStorage->openDir( root ); p = root; // File info to JSON while( d.next() ) { File f = d.openFile( "r" ); JsonObject &o = r.createNestedObject(); o[ "type" ] = f.isDirectory() ? "d" : "-"; o[ "name" ] = String(f.name()).substring( p.length() ); o[ "size" ] = f.size(); f.close(); } s = ""; r.prettyPrintTo( s ); break; default: s = usage( "ll (path)?" ); break; } return s; } /** * @fn String Esp8266::mkdir( StringList *args ) * * Make directory on current device. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::mkdir( StringList *args ) { String s, t; switch( count(args) ) { case 1: t = appendRootPath( _a(0) ); if( EspStorage->exists(t) ) s = mkdir( 0 ); else EspStorage->mkdir( t ); break; default: s = usage( "mkdir path" ); break; } return s; } /** * @fn String Esp8266::pwd( StringList *args ) * * Return current device. * * @param[in] args Reference to arguments. * @return Current device. */ String Esp8266::pwd( StringList *args ) { String s; switch( count(args) ) { case 0: s = prettyPrintTo( "value" , _FLASH_ ); break; default: s = usage( "pwd" ); break; } return s; } /** * @fn String Esp8266::read( StringList *args ) * * Return file content on current device. * * @param[in] args Reference to arguments. * @return File content. */ String Esp8266::read( StringList *args ) { String s, t; File f; switch( count(args) ) { case 1: t = appendRootPath( _a(0) ); if( !EspStorage->exists(t) ) s = read( 0 ); else { f = EspStorage->open( t, _FILE_READ_ ); if( f ) { s = prettyPrintTo( "value" , f.readString() ); f.close(); } } break; default: s = usage( "cat file" ); break; } return s; } /** * @fn String Esp8266::remove( StringList *args ) * * Remove file on current device. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::remove( StringList *args ) { String s, t; switch( count(args) ) { case 1: t = appendRootPath( _a(0) ); if( !EspStorage->exists(t) ) s = remove( 0 ); else EspStorage->remove( t ); break; default: s = usage( "rm file" ); break; } return s; } /** * @fn String Esp8266::rmdir( StringList *args ) * * Remove directory on current device. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::rmdir( StringList *args ) { String s, t; switch( count(args) ) { case 1: t = appendRootPath( _a(0) ); if( !EspStorage->exists(t) ) s = rmdir( 0 ); else EspStorage->rmdir( t ); break; default: s = usage( "rmdir path" ); break; } return s; } /** * @fn String Esp8266::httpBegin( StringList *args ) * * Initalize https certs. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::httpBegin( StringList *args ) { String s, t; File rc, cc, pk; switch( count(args) ) { case 0: http = &wifiClient; break; case 3: http = &wifiClientSecure; // RootCA rc = EspStorage->open( appendRootPath(_a(0)), _FILE_READ_ ); t = rc.readString(); wifiClientSecure.setCACert( (uint8_t*)t.c_str(), t.length() ); rc.close(); // Client certificate cc = EspStorage->open( appendRootPath(_a(1)), _FILE_READ_ ); t = cc.readString(); wifiClientSecure.setCertificate( (uint8_t*)t.c_str(), t.length() ); cc.close(); // Client private key pk = EspStorage->open( appendRootPath(_a(2)), _FILE_READ_ ); t = pk.readString(); wifiClientSecure.setPrivateKey( (uint8_t*)t.c_str(), t.length() ); pk.close(); break; default: s = usage( "httpBegin CACert Certificate PrivateKey" ); break; } return s; } /** * @fn String Esp8266::httpPost( StringList *args ) * * Send HTTP POST to server. * * @param[in] args Reference to arguments. * @return Recieved content. */ String Esp8266::httpPost( StringList *args ) { String s, t, header, footer; File f; int size = 0; String host; int port = 80; int timeout = 30 * 1000; uint8_t *buf = 0; switch( count(args) ) { case 5: timeout = _atoi( 4 ) * 1000; case 4: port = _atoi( 3 ); case 3: t = appendRootPath( _a(2) ); if( !EspStorage->exists(t) ) return AoiUtil::Http::httpPost( args ); // Request body header = requestBodyHeaderInPut( STR_BOUNDARY, STR_AOIDUINO, t, &size ); footer = requestBodyFooterInPut( STR_BOUNDARY ); size += header.length() + footer.length(); // POST host = _a( 0 ); if( !http->connect(host.c_str(),port) ) return httpPost( 0 ); http->println( "POST "+_a(1)+" HTTP/1.0" ); http->println( "Host: " + host ); http->println( "User-Agent: " + String(STR_USER_AGENT) ); http->print( "Content-Type: multipart/form-data; " ); http->println( "boundary=\""+String(STR_BOUNDARY)+"\"" ); http->println( "Content-Length: "+String(size) ); http->println( "Connection: close" ); http->println(); http->print( header ); // Upload file f = EspStorage->open( t, _FILE_READ_ ); buf = new uint8_t[ _AOIUTIL_HTTP_BUFFER_SIZE_ ]; while( f.available() ) { size = f.read( buf, _AOIUTIL_HTTP_BUFFER_SIZE_ ); http->write( buf, size ); } delete [] buf; f.close(); http->print( footer ); // Response s = response( timeout ); s = prettyPrintTo( "value", s ); break; default: s = usage( "httpPost host path (file|text) (port timeout)?" ); break; } return s; } /** * @fn String Esp8266::touch( StringList *args ) * * Create empty file on current device. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::touch( StringList *args ) { String s, t; File f; switch( count(args) ) { case 1: t = appendRootPath( _a(0) ); f = EspStorage->open( t, _FILE_WRITE_ ); if( f ) f.close(); break; default: s = usage( "touch file" ); break; } return s; } /** * @fn String Esp8266::deepSleep( StringList *args ) * * Enter the deep sleep state. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::deepSleep( StringList *args ) { String s; RFMode mode; switch( count(args) ) { case 0: ESP.deepSleep( 0 ); break; case 1: // Micro second. mode = WAKE_RF_DEFAULT; ESP.deepSleep( _atoi(0) * 1000 * 1000, mode ); break; default: s = usage( "deepSleep [0-9]*" ); break; } return s; } /** * @fn String Esp8266::dmesg( StringList *args ) * * Returns system information. * * @param[in] args Reference to arguments. * @return System information. */ String Esp8266::dmesg( StringList *args ) { String s; DynamicJsonBuffer json; JsonObject &r = json.createObject(); switch( count(args) ) { case 0: r[ "chipId" ] = String( ESP.getChipId(), HEX ); r[ "coreVersion" ] = ESP.getCoreVersion(); r[ "cpuFreqMHz" ] = ESP.getCpuFreqMHz(); r[ "flashChipId" ] = String( ESP.getFlashChipId(), HEX ); r[ "flashChipSize" ] = ESP.getFlashChipSize(); r[ "freeHeap" ] = ESP.getFreeHeap(); r[ "freeSketchSpace" ] = ESP.getFreeSketchSpace(); r[ "resetReason" ] = ESP.getResetReason(); r[ "sdkVersion" ] = ESP.getSdkVersion(); r[ "sketchSize" ] = ESP.getSketchSize(); r.prettyPrintTo( s ); break; default: s = usage( "dmesg" ); break; } return s; } /** * @fn String Esp8266::restart( StringList *args ) * * Reboot the system. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::restart( StringList *args ) { String s; switch( count(args) ) { case 0: ESP.restart(); break; case 1: ticker.once_ms( _atoi(0), reboot ); break; default: s = usage( "reboot ([0-9]+)" ); break; } return s; } /** * @fn String Esp8266::date( StringList *args ) * * Print date. * * @param[in] args Reference to arguments. * @return date string. */ String Esp8266::date( StringList *args ) { String s; uint8_t size = 20; char *buf = NULL; time_t t; struct tm *rtc; struct timeval tv; switch( count(args) ) { case 0: t = time( NULL ); rtc = localtime( &t ); buf = new char[ size ]; snprintf( buf, size, "%04d-%02d-%02dT%02d:%02d:%02d", rtc->tm_year+1900, rtc->tm_mon+1, rtc->tm_mday, rtc->tm_hour, rtc->tm_min, rtc->tm_sec ); s = prettyPrintTo( "value", buf ); delete [] buf; break; case 1: tv.tv_sec = _atoul( 0 ); settimeofday( &tv, NULL ); break; default: s = usage( "date (unixtime)?" ); break; } return s; } /** * @fn String Esp8266::servoAttach( StringList *args ) * * Attach the Servo variable to a pin. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::servoAttach( StringList *args ) { String s; switch( count(args) ) { case 1: ( m_servo+0 )->attach( _atoi(0) ); break; case 2: ( m_servo+_atoi(1) )->attach( _atoi(0) ); break; default: s = usage( "servoAttach pin ([0-(count-1)])" ); break; } return s; } /** * @fn String Esp8266::servoBegin( StringList *args ) * * Initialize the servo using count. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::servoBegin( StringList *args ) { String s; StringList sl; switch( count(args) ) { case 1: servoEnd( &sl ); m_servoCount = _atoi( 0 ); m_servo = new Servo[ m_servoCount ]; break; default: s = usage( "servoBegin count" ); break; } return s; } /** * @fn String Esp8266::servoEnd( StringList *args ) * * Detach the all Servo variable from its pin. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::servoEnd( StringList *args ) { String s; switch( count(args) ) { case 0: if( m_servo ) { for( int i=0; i<m_servoCount; i++ ) (m_servo+i)->detach(); delete [] m_servo; } m_servo = 0; m_servoCount = 0; break; default: s = usage( "servoEnd" ); break; } return s; } /** * @fn String Esp8266::servoWriteMicroseconds( StringList *args ) * * Set microseconds to servo using pin number. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::servoWriteMicroseconds( StringList *args ) { String s; switch( count(args) ) { case 1: ( m_servo+0 )->writeMicroseconds( _atoi(0) ); break; case 2: ( m_servo+_atoi(1) )->writeMicroseconds( _atoi(0) ); break; default: s = usage( "servoWriteMicroseconds micros ([0-(count-1)])" ); break; } return s; } /** * @fn String Esp8266::watchdogBegin( StringList *args ) * * Initialize the Watchdog and start to check timer(mesc). * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::watchdogBegin( StringList *args ) { String s; switch( count(args) ) { case 1: watchdog.once_ms( _atoi(0), reboot ); watchdogSecond = _atoi(0); watchdogMills = ::millis(); break; default: s = usage( "watchdogBegin [0-9]+" ); break; } return s; } /** * @fn String Esp8266::watchdogEnd( StringList *args ) * * Stop to check timer for avoid bite watchdog. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::watchdogEnd( StringList *args ) { String s; switch( count(args) ) { case 0: watchdog.detach(); watchdogSecond = 0; watchdogMills = 0; break; default: s = usage( "watchdogEnd" ); break; } return s; } /** * @fn String Ast::watchdogKick( StringList *args ) * * Kick to watchdog for notify keep alive. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::watchdogKick( StringList *args ) { String s; switch( count(args) ) { case 0: watchdog.detach(); watchdog.once_ms( watchdogSecond, reboot ); watchdogMills = ::millis(); break; default: s = usage( "watchdogKick" ); break; } return s; } /** * @fn String Esp8266::watchdogTimeleft( StringList *args ) * * Get a remain time for bite watchdog. * * @param[in] args Reference to arguments. * @return Remain time to expire timeout(mesc). */ String Esp8266::watchdogTimeleft( StringList *args ) { String s; uint32_t i = 0; switch( count(args) ) { case 0: i = watchdogSecond - (::millis()-watchdogMills); s = prettyPrintTo( "value" , i ); break; default: s = usage( "watchdogTimeleft" ); break; } return s; } /** * @fn String Esp8266::ifConfig( StringList *args ) * * Show network information. * * @param[in] args Reference to arguments. * @return Network information. */ String Esp8266::ifConfig( StringList *args ) { String s; DynamicJsonBuffer json; JsonObject &r = json.createObject(); switch( count(args) ) { case 0: r[ "ipAddress" ] = WiFi.localIP().toString(); r[ "subnetMask" ] = WiFi.subnetMask().toString(); r[ "gatewayIp" ] = WiFi.gatewayIP().toString(); r[ "macAddress" ] = WiFi.macAddress(); r[ "dnsIP1" ] = WiFi.dnsIP( 0 ).toString(); r[ "dnsIP2" ] = WiFi.dnsIP( 1 ).toString(); r[ "softAP" ] = WiFi.softAPIP().toString(); r.prettyPrintTo( s ); break; default: s = usage( "ifconfig" ); break; } return s; } /** * @fn String Esp8266::wifiScanNetworks( StringList *args ) * * Scan wifi networks. * * @param[in] args Reference to arguments. * @return Returns SSID, RSSI and Encryption type. */ String Esp8266::wifiScanNetworks( StringList *args ) { String s; int i = 0; DynamicJsonBuffer json; JsonArray &r = json.createArray(); switch( count(args) ) { case 0: i = WiFi.scanNetworks(); if( !i ) s = STR_NO_NETWORKS_FOUND; else { for( int j=0; j<i; j++ ) { JsonObject &o = r.createNestedObject(); o[ "ssid" ] = WiFi.SSID( j ); o[ "rssi" ] = WiFi.RSSI( j ); // Sets encription type. String t = ""; switch( WiFi.encryptionType(j) ) { case 2: t = "TKIP(WPA)"; break; case 5: t = "WEP"; break; case 4: t = "CCMP(WPA)"; break; case 7: t = "None"; break; case 8: t = "Auto"; break; default: t = "Other"; break; } o[ "type" ] = t; } r.prettyPrintTo( s ); } break; default: s = usage( "iwlist" ); break; } return s; } /** * @fn String Esp8266::wifiBegin( StringList *args ) * * Connect to wireless network. * * @param[in] args Reference to arguments. * @return Wireless ip address, Otherwise error string. */ String Esp8266::wifiBegin( StringList *args ) { String s; unsigned long i = 0; switch( count(args) ) { case 2: // Start WiFi.disconnect(); WiFi.mode( WIFI_STA ); WiFi.begin( _a(0).c_str(), _a(1).c_str() ); // Waiting i = ::millis(); while( WiFi.status()!=WL_CONNECTED && (::millis()-i)<ESP_WIFI_TIMEOUT ) ::delay( 500 ); // Result if( WiFi.status()!=WL_CONNECTED ) s = STR_CANT_CONNECT_TO_WIRELESS_NETWORK; else { StringList sl; s = ifConfig( &sl ); } break; default: s = usage( "wifiBegin ssid password" ); break; } return s; } /** * @fn String Esp8266::wifiEnd( StringList *args ) * * Detach from wireless network. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::wifiEnd( StringList *args ) { String s; switch( count(args) ) { case 0: if( WiFi.status()!=WL_CONNECTED ) s = wifiEnd( 0 ); else WiFi.disconnect(); break; default: s = usage( "wifiEnd" ); break; } return s; } /** * @fn String Esp8266::wifiRtc( StringList *args ) * * Get rtc from the WiFi network. * * @param[in] args Reference to arguments. * @return unixtime string. */ String Esp8266::wifiRtc( StringList *args ) { String s; time_t now; switch( count(args) ) { case 0: if( WiFi.status()!=WL_CONNECTED ) s = wifiRtc( 0 ); else { configTzTime( "JST-9", "ntp.nict.jp", "time.google.com", "ntp.jst.mfeed.ad.jp" ); time( &now ); s = String( now ); s = prettyPrintTo( "value", s ); } break; default: s = usage( "wifiRtc" ); break; } return s; } /** * @fn String Esp8266::appendRootPath( const String &path ) * * Append root path ("/") if need. * * @return Path include root. */ String Esp8266::appendRootPath( const String &path ) { String s = path; String r = "/"; if( s.indexOf(r) ) s = r + s; return s; } /** * @fn void Esp8266::reboot( void ) * * Reboot the system. */ void Esp8266::reboot( void ) { ESP.restart(); } /** * @fn String Esp8266::requestBodyHeaderInPut( const String &value ) * * Return request body header in HTTP PUT. * * @param[in] boundary Boundary string. * @param[in] name Content-Disposition: name attribute string. * @param[in] value Putted value. * @param[in/out] size Putted value size. If value is file, File size is used. * @return Request body header string in HTTP PUT. */ String Esp8266::requestBodyHeaderInPut( const String &boundary, const String &name, const String &value, int *size ) { String s; String t = appendRootPath( value ); // If file is exitst, use file size if( !EspStorage->exists(t) ) s = AoiUtil::Http::requestBodyHeaderInPut( boundary, name, value, size ); else { s += "--" + boundary + "\r\n"; s += "Content-Disposition: form-data; name=\"" + name + "\";"; s += " filename=\"" + value + "\"\r\n"; s += "Content-Type: application/octet-stream\r\n"; s += "Content-Transfer-Encoding: binary\r\n"; File f = EspStorage->open( t, _FILE_READ_ ); *size = f.size(); f.close(); s += "\r\n"; } return s; } } #endif
34,785
10,629
#include "sema/SemanticAnalyzer.hpp" /* std::unordered_map<std::string, SemanticAnalyzer::SymbolEntry *>::iterator SemanticAnalyzer::SymbolTable::addSymbol(const char *name, int kind, uint32_t level, const char *type, int attribute){ dumpList.push_back(name); return insert(name, new SymbolEntry(name, kind, level, type, attribute)); } std::unordered_map<std::string, SemanticAnalyzer::SymbolEntry *>::iterator SemanticAnalyzer::SymbolTable::addSymbol(const char *name, int kind, uint32_t level, const char *type, float attribute){ dumpList.push_back(name); return insert(name, new SymbolEntry(name, kind, level, type, attribute)); } std::unordered_map<std::string, SemanticAnalyzer::SymbolEntry *>::iterator SemanticAnalyzer::SymbolTable::addSymbol(const char *name, int kind, uint32_t level, const char *type, bool attribute){ dumpList.push_back(name); return insert(name, new SymbolEntry(name, kind, level, type, attribute)); }*/ std::unordered_map<std::string, SemanticAnalyzer::SymbolEntry *>::iterator SemanticAnalyzer::SymbolTable::addSymbol(const char *name, int kind, uint32_t level, const char *type, const char *attribute){ dumpList.push_back(name); return insert(name, new SymbolEntry(name, kind, level, type, attribute)); } std::unordered_map<std::string, SemanticAnalyzer::SymbolEntry *>::iterator SemanticAnalyzer::SymbolTable::insert(const char *name, SymbolEntry *symbol){ return entries.insert(std::pair<std::string, SymbolEntry *>(std::string(name), symbol)).first; } void SemanticAnalyzer::SymbolTable::SetLevel(uint32_t lv){ level = lv; } uint32_t SemanticAnalyzer::SymbolTable::GetLevel(){ return level; } std::list<const char *>::iterator SemanticAnalyzer::SymbolTable::GetDumpListBegin(){ return dumpList.begin(); } std::list<const char *>::iterator SemanticAnalyzer::SymbolTable::GetDumpListEnd(){ return dumpList.end(); } int SemanticAnalyzer::SymbolTable::GetDumpListSize(){ return (int)dumpList.size(); } SemanticAnalyzer::SymbolEntry *SemanticAnalyzer::SymbolTable::lookup(const char *name){ std::unordered_map<std::string, SymbolEntry *>::iterator got = entries.find(std::string(name)); if(got != entries.end()) return (got->second); else return NULL; } bool SemanticAnalyzer::SymbolTable::EraseSymbol(const char *name){ int result = entries.erase(std::string(name)); dumpList.remove(std::string(name).c_str()); if(result > 0) return true; else return false; }
2,487
785
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/disk_cache/block_files.h" #include "base/atomicops.h" #include "base/file_util.h" #include "base/metrics/histogram.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_checker.h" #include "base/time.h" #include "net/disk_cache/cache_util.h" #include "net/disk_cache/file_lock.h" #include "net/disk_cache/trace.h" using base::TimeTicks; namespace disk_cache { BlockFiles::BlockFiles(const base::FilePath& path) : init_(false), zero_buffer_(NULL), path_(path) { } BlockFiles::~BlockFiles() { if (zero_buffer_) delete[] zero_buffer_; CloseFiles(); } bool BlockFiles::Init(bool create_files) { DCHECK(!init_); if (init_) return false; thread_checker_.reset(new base::ThreadChecker); block_files_.resize(kFirstAdditionalBlockFile); for (int i = 0; i < kFirstAdditionalBlockFile; i++) { if (create_files) if (!CreateBlockFile(i, static_cast<FileType>(i + 1), true)) return false; if (!OpenBlockFile(i)) return false; // Walk this chain of files removing empty ones. if (!RemoveEmptyFile(static_cast<FileType>(i + 1))) return false; } init_ = true; return true; } bool BlockFiles::CreateBlock(FileType block_type, int block_count, Addr* block_address) { DCHECK(thread_checker_->CalledOnValidThread()); if (block_type < RANKINGS || block_type > BLOCK_4K || block_count < 1 || block_count > 4) return false; if (!init_) return false; MappedFile* file = FileForNewBlock(block_type, block_count); if (!file) return false; ScopedFlush flush(file); BlockFileHeader* header = reinterpret_cast<BlockFileHeader*>(file->buffer()); int target_size = 0; for (int i = block_count; i <= 4; i++) { if (header->empty[i - 1]) { target_size = i; break; } } DCHECK(target_size); int index; if (!CreateMapBlock(target_size, block_count, header, &index)) return false; Addr address(block_type, block_count, header->this_file, index); block_address->set_value(address.value()); Trace("CreateBlock 0x%x", address.value()); return true; } void BlockFiles::DeleteBlock(Addr address, bool deep) { DCHECK(thread_checker_->CalledOnValidThread()); if (!address.is_initialized() || address.is_separate_file()) return; if (!zero_buffer_) { zero_buffer_ = new char[Addr::BlockSizeForFileType(BLOCK_4K) * 4]; memset(zero_buffer_, 0, Addr::BlockSizeForFileType(BLOCK_4K) * 4); } MappedFile* file = GetFile(address); if (!file) return; Trace("DeleteBlock 0x%x", address.value()); size_t size = address.BlockSize() * address.num_blocks(); size_t offset = address.start_block() * address.BlockSize() + kBlockHeaderSize; if (deep) file->Write(zero_buffer_, size, offset); BlockFileHeader* header = reinterpret_cast<BlockFileHeader*>(file->buffer()); DeleteMapBlock(address.start_block(), address.num_blocks(), header); file->Flush(); if (!header->num_entries) { // This file is now empty. Let's try to delete it. FileType type = Addr::RequiredFileType(header->entry_size); if (Addr::BlockSizeForFileType(RANKINGS) == header->entry_size) type = RANKINGS; RemoveEmptyFile(type); // Ignore failures. } } void BlockFiles::CloseFiles() { if (init_) { DCHECK(thread_checker_->CalledOnValidThread()); } init_ = false; for (unsigned int i = 0; i < block_files_.size(); i++) { if (block_files_[i]) { block_files_[i]->Release(); block_files_[i] = NULL; } } block_files_.clear(); } void BlockFiles::ReportStats() { DCHECK(thread_checker_->CalledOnValidThread()); int used_blocks[kFirstAdditionalBlockFile]; int load[kFirstAdditionalBlockFile]; for (int i = 0; i < kFirstAdditionalBlockFile; i++) { GetFileStats(i, &used_blocks[i], &load[i]); } UMA_HISTOGRAM_COUNTS("DiskCache.Blocks_0", used_blocks[0]); UMA_HISTOGRAM_COUNTS("DiskCache.Blocks_1", used_blocks[1]); UMA_HISTOGRAM_COUNTS("DiskCache.Blocks_2", used_blocks[2]); UMA_HISTOGRAM_COUNTS("DiskCache.Blocks_3", used_blocks[3]); UMA_HISTOGRAM_ENUMERATION("DiskCache.BlockLoad_0", load[0], 101); UMA_HISTOGRAM_ENUMERATION("DiskCache.BlockLoad_1", load[1], 101); UMA_HISTOGRAM_ENUMERATION("DiskCache.BlockLoad_2", load[2], 101); UMA_HISTOGRAM_ENUMERATION("DiskCache.BlockLoad_3", load[3], 101); } bool BlockFiles::IsValid(Addr address) { #ifdef NDEBUG return true; #else if (!address.is_initialized() || address.is_separate_file()) return false; MappedFile* file = GetFile(address); if (!file) return false; BlockFileHeader* header = reinterpret_cast<BlockFileHeader*>(file->buffer()); bool rv = UsedMapBlock(address.start_block(), address.num_blocks(), header); DCHECK(rv); static bool read_contents = false; if (read_contents) { scoped_ptr<char[]> buffer; buffer.reset(new char[Addr::BlockSizeForFileType(BLOCK_4K) * 4]); size_t size = address.BlockSize() * address.num_blocks(); size_t offset = address.start_block() * address.BlockSize() + kBlockHeaderSize; bool ok = file->Read(buffer.get(), size, offset); DCHECK(ok); } return rv; #endif } MappedFile* BlockFiles::GetFile(Addr address) { DCHECK(thread_checker_->CalledOnValidThread()); DCHECK(block_files_.size() >= 4); DCHECK(address.is_block_file() || !address.is_initialized()); if (!address.is_initialized()) return NULL; int file_index = address.FileNumber(); if (static_cast<unsigned int>(file_index) >= block_files_.size() || !block_files_[file_index]) { // We need to open the file if (!OpenBlockFile(file_index)) return NULL; } DCHECK(block_files_.size() >= static_cast<unsigned int>(file_index)); return block_files_[file_index]; } bool BlockFiles::GrowBlockFile(MappedFile* file, BlockFileHeader* header) { if (kMaxBlocks == header->max_entries) return false; ScopedFlush flush(file); DCHECK(!header->empty[3]); int new_size = header->max_entries + 1024; if (new_size > kMaxBlocks) new_size = kMaxBlocks; int new_size_bytes = new_size * header->entry_size + sizeof(*header); if (!file->SetLength(new_size_bytes)) { // Most likely we are trying to truncate the file, so the header is wrong. if (header->updating < 10 && !FixBlockFileHeader(file)) { // If we can't fix the file increase the lock guard so we'll pick it on // the next start and replace it. header->updating = 100; return false; } return (header->max_entries >= new_size); } FileLock lock(header); header->empty[3] = (new_size - header->max_entries) / 4; // 4 blocks entries header->max_entries = new_size; return true; } MappedFile* BlockFiles::FileForNewBlock(FileType block_type, int block_count) { COMPILE_ASSERT(RANKINGS == 1, invalid_file_type); MappedFile* file = block_files_[block_type - 1]; BlockFileHeader* header = reinterpret_cast<BlockFileHeader*>(file->buffer()); TimeTicks start = TimeTicks::Now(); while (NeedToGrowBlockFile(header, block_count)) { if (kMaxBlocks == header->max_entries) { file = NextFile(file); if (!file) return NULL; header = reinterpret_cast<BlockFileHeader*>(file->buffer()); continue; } if (!GrowBlockFile(file, header)) return NULL; break; } HISTOGRAM_TIMES("DiskCache.GetFileForNewBlock", TimeTicks::Now() - start); return file; } // Note that we expect to be called outside of a FileLock... however, we cannot // DCHECK on header->updating because we may be fixing a crash. bool BlockFiles::FixBlockFileHeader(MappedFile* file) { ScopedFlush flush(file); BlockFileHeader* header = reinterpret_cast<BlockFileHeader*>(file->buffer()); int file_size = static_cast<int>(file->GetLength()); if (file_size < static_cast<int>(sizeof(*header))) return false; // file_size > 2GB is also an error. const int kMinBlockSize = 36; const int kMaxBlockSize = 4096; if (header->entry_size < kMinBlockSize || header->entry_size > kMaxBlockSize || header->num_entries < 0) return false; // Make sure that we survive crashes. header->updating = 1; int expected = header->entry_size * header->max_entries + sizeof(*header); if (file_size != expected) { int max_expected = header->entry_size * kMaxBlocks + sizeof(*header); if (file_size < expected || header->empty[3] || file_size > max_expected) { NOTREACHED(); LOG(ERROR) << "Unexpected file size"; return false; } // We were in the middle of growing the file. int num_entries = (file_size - sizeof(*header)) / header->entry_size; header->max_entries = num_entries; } FixAllocationCounters(header); int empty_blocks = EmptyBlocks(header); if (empty_blocks + header->num_entries > header->max_entries) header->num_entries = header->max_entries - empty_blocks; if (!ValidateCounters(header)) return false; header->updating = 0; return true; } // We are interested in the total number of blocks used by this file type, and // the max number of blocks that we can store (reported as the percentage of // used blocks). In order to find out the number of used blocks, we have to // substract the empty blocks from the total blocks for each file in the chain. void BlockFiles::GetFileStats(int index, int* used_count, int* load) { int max_blocks = 0; *used_count = 0; *load = 0; for (;;) { if (!block_files_[index] && !OpenBlockFile(index)) return; BlockFileHeader* header = reinterpret_cast<BlockFileHeader*>(block_files_[index]->buffer()); max_blocks += header->max_entries; int used = header->max_entries; for (int i = 0; i < 4; i++) { used -= header->empty[i] * (i + 1); DCHECK_GE(used, 0); } *used_count += used; if (!header->next_file) break; index = header->next_file; } if (max_blocks) *load = *used_count * 100 / max_blocks; } } // namespace disk_cache
10,234
3,614
#include"lud.h" #include <iostream> //Elment with the block BSIZE, diagonal #define AA(i,j) result[(offset + i) * matrix_dim + j + offset] //Elment with global index #define BB(i,j) result[i * matrix_dim + j] using namespace std; extern "C"{ void diagonal_load(float* result, float* buffer, int offset){ int i, j; for(i = 0; i < BSIZE; i++){ for (j = 0; j < BSIZE; j++){ buffer[i * BSIZE + j] = AA(i, j); } } } void diagonal_store(float* result, float* buffer, int offset){ int i, j; for(i = 0; i < BSIZE; i++){ for (j = 0; j < BSIZE; j++){ AA(i, j) = buffer[i * BSIZE + j]; } } } void lud_diagonal(float* result, int offset) { int i, j, k; float buffer[BSIZE * BSIZE]; diagonal_load(result, buffer, offset); for (i = 0; i < BSIZE; i++){ top:for (j = i; j < BSIZE; j++){ for (k = 0; k < i; k++){ buffer[i * BSIZE + j] = buffer[i * BSIZE + j] - buffer[i * BSIZE + k]* buffer[k * BSIZE + j]; } } float temp = 1.f / buffer[i * BSIZE + i]; left:for (j = i + 1; j < BSIZE; j++){ for (k = 0; k < i; k++){ buffer[j * BSIZE + i]= buffer[j * BSIZE + i]- buffer[j * BSIZE + k] * buffer[k * BSIZE + i]; } buffer[j * BSIZE + i] = buffer[j * BSIZE + i] * temp; } } diagonal_store(result, buffer, offset); } void perimeter_load(float* result, float* top, float* left, int offset, int chunk_idx){ int i, j; int i_top = offset; int j_top = offset + BSIZE * (chunk_idx + 1); int i_left = offset + BSIZE * (chunk_idx + 1); int j_left = offset; for(i = 0; i < BSIZE; i++){ for(j = 0; j < BSIZE; j++){ top[i * BSIZE + j] = BB((i_top + i), (j_top + j)); } } for(i = 0; i < BSIZE; i++){ for(j = 0; j < BSIZE; j++){ left[i * BSIZE + j] = BB((i_left + i), (j_left + j)); } } } void perimeter_store(float* result, float* top, float* left, int offset, int chunk_idx){ int i, j; int i_top = offset; int j_top = offset + BSIZE * (chunk_idx + 1); int i_left = offset + BSIZE * (chunk_idx + 1); int j_left = offset; for(i = 0; i < BSIZE; i++){ for(j = 0; j < BSIZE; j++){ BB((i_top + i), (j_top + j)) = top[i * BSIZE + j]; } } for(i = 0; i < BSIZE; i++){ for(j = 0; j < BSIZE; j++){ BB((i_left + i), (j_left + j)) = left[i * BSIZE + j]; } } } //99327 void lud_perimeter(float* result, int offset) { float diagonal_buffer[BSIZE * BSIZE]; float top_buffer[BSIZE * BSIZE]; float left_buffer[BSIZE * BSIZE]; int i, j, k; diagonal:for (i = 0; i < BSIZE; i++){ for (j = 0; j < BSIZE; j++){ diagonal_buffer[i * BSIZE + j] = AA(i, j); } } int chunk_idx, chunk_num; chunk_num = ((matrix_dim - offset) / BSIZE) - 1; for (chunk_idx = 0; chunk_idx < chunk_num; chunk_idx++){ perimeter_load(result, top_buffer, left_buffer, offset, chunk_idx); float sum; // processing top perimeter for (j = 0; j < BSIZE; j++){ for (i = 0; i < BSIZE; i++){ sum = 0.0f; for (k = 0; k < i; k++){ sum += diagonal_buffer[BSIZE * i + k] * top_buffer[k * BSIZE + j]; } top_buffer[i * BSIZE + j] = top_buffer[i * BSIZE + j] - sum; } } // processing left perimeter for (i = 0; i < BSIZE; i++){ for (j = 0; j < BSIZE; j++){ sum = 0.0f; for (k = 0; k < j; k++){ sum += left_buffer[i * BSIZE + k] * diagonal_buffer[BSIZE * k + j]; } left_buffer[i * BSIZE + j] = (left_buffer[i * BSIZE + j] - sum) / diagonal_buffer[j * BSIZE + j]; } } perimeter_store(result, top_buffer, left_buffer, offset, chunk_idx); } cout << "success here perimeter" << endl; } void internal_load(float* result, float* top, float* left, float* inner, int offset, int chunk_idx, int chunk_num){ int i, j; int i_global, j_global; i_global = offset + BSIZE * (1 + chunk_idx / chunk_num); j_global = offset + BSIZE * (1 + chunk_idx % chunk_num); for(i = 0; i < BSIZE; i++){ for(j = 0; j < BSIZE; j++){ top[i * BSIZE + j] = result[matrix_dim * (i + offset) + j + j_global]; } } for(i = 0; i < BSIZE; i++){ for(j = 0; j < BSIZE; j++){ left[i * BSIZE + j] = result[matrix_dim * (i + i_global) + offset + j]; } } for(i = 0; i < BSIZE; i++){ for(j = 0; j < BSIZE; j++){ inner[i * BSIZE + j] = result[matrix_dim * (i + i_global) + j + j_global]; } } } void internal_store(float* result, float* inner, int offset, int chunk_idx, int chunk_num){ int i, j; int i_global, j_global; i_global = offset + BSIZE * (1 + chunk_idx / chunk_num); j_global = offset + BSIZE * (1 + chunk_idx % chunk_num); for(i = 0; i < BSIZE; i++){ for(j = 0; j < BSIZE; j++){ result[matrix_dim * (i + i_global) + j + j_global] = inner[i * BSIZE + j]; } } } void lud_internal( float* result, int offset) { int chunk_idx, chunk_num; chunk_num = ((matrix_dim - offset) / BSIZE) - 1; float top_buffer[BSIZE * BSIZE]; float left_buffer[BSIZE * BSIZE]; float inner_buffer[BSIZE * BSIZE]; int i, j, k, i_global, j_global; for (chunk_idx = 0; chunk_idx < chunk_num * chunk_num; chunk_idx++){ internal_load(result, top_buffer, left_buffer, inner_buffer, offset, chunk_idx, chunk_num); for (i = 0; i < BSIZE; i++){ for (j = 0; j < BSIZE; j++){ float sum = 0.0f; //#pragma HLS unsafemath for (k = 0; k < BSIZE; k++){ sum += left_buffer[BSIZE * i + k] * top_buffer[BSIZE * k + j]; } inner_buffer[i * BSIZE + j] -= sum; } } internal_store(result, inner_buffer, offset, chunk_idx, chunk_num); } cout << "success internal" << endl; } void workload(float result[GRID_ROWS * GRID_COLS]){ #pragma HLS INTERFACE m_axi port=result offset=slave bundle=gmem #pragma HLS INTERFACE s_axilite port=result bundle=control #pragma HLS INTERFACE s_axilite port=return bundle=control for(int i = 0; i < matrix_dim - BSIZE; i += BSIZE){ lud_diagonal(result, i); lud_perimeter(result, i); lud_internal(result, i); } int i = matrix_dim - BSIZE; lud_diagonal(result, i); return; } }
7,249
2,572
#ifndef MENOH_ARRAY_HPP #define MENOH_ARRAY_HPP #include <algorithm> #include <memory> #include <vector> #include <menoh/dims.hpp> #include <menoh/dtype.hpp> #include <menoh/exception.hpp> namespace menoh_impl { class array { public: array() = default; array(dtype_t d, std::vector<int> const& dims, void* data_handle); array(dtype_t d, std::vector<int> const& dims, std::shared_ptr<void> data); array(dtype_t d, std::vector<int> const& dims); dtype_t dtype() const { return dtype_; } auto const& dims() const { return dims_; } auto* data() const { return data_handle_; } bool has_ownership() const { return static_cast<bool>(data_); } private: dtype_t dtype_ = dtype_t::undefined; std::vector<int> dims_; std::shared_ptr<void> data_; void* data_handle_ = nullptr; }; std::size_t total_size(array const& a); float* fbegin(array const& a); float* fend(array const& a); float& fat(array const& a, std::size_t i); template <typename T> auto uniforms(dtype_t d, std::vector<int> const& dims, T val) { static_assert(std::is_arithmetic<T>::value, ""); auto arr = array(d, dims); if(d == dtype_t::float_) { std::fill_n(static_cast<float*>(arr.data()), calc_total_size(dims), static_cast<float>(val)); return arr; } throw invalid_dtype(std::to_string(static_cast<int>(d))); } array zeros(dtype_t d, std::vector<int> const& dims); } // namespace menoh_impl #endif // MENOH_ARRAY_HPP
1,636
570
#include "GeneralUtilities/inc/VMInfo.hh" #include <array> #include <fstream> #include <map> #include <sstream> #include <stdexcept> #include <unistd.h> namespace { // Helper function to check the units and return the value. long parseLine ( std::string const& line, std::string const& unitExpected ){ std::istringstream is(line); std::string key, unit; long val; is >> key >> val >> unit; if ( unit!=unitExpected ){ throw std::runtime_error( "ProcStatus: cannot parse: " + line ); } return val; } } // end anonymous namespace // The c'tor does all of the work. mu2e::VMInfo::VMInfo(){ // The information we want. std::array<std::string,4> wanted{ "VmPeak", "VmSize", "VmHWM", "VmRSS"}; // Parse the information to get what we need. std::ifstream proc("/proc/self/status"); std::map<std::string,long> values; while ( proc ){ std::string line; getline( proc, line); if ( !proc ) break; for ( auto const& name: wanted ){ if ( line.find(name) != std::string::npos ){ long val = parseLine( line, "kB"); values[name] = val; break; } } } vmPeak = values["VmPeak"]; vmSize = values["VmSize"]; vmHWM = values["VmHWM"]; vmRSS = values["VmRSS"]; }
1,287
454
/* libember -- C++ 03 implementation of the Ember+ Protocol Copyright (C) 2012-2016 Lawo GmbH (http://www.lawo.com). Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef __LIBEMBER_GLOW_GLOWPARAMETER_IPP #define __LIBEMBER_GLOW_GLOWPARAMETER_IPP #include "../../util/Inline.hpp" #include "../util/ValueConverter.hpp" #include "../GlowStringIntegerPair.hpp" #include "../GlowTags.hpp" #include "../GlowNodeBase.hpp" namespace libember { namespace glow { LIBEMBER_INLINE GlowParameter::GlowParameter(int number) : GlowParameterBase(GlowType::Parameter, GlowTags::ElementDefault(), GlowTags::Parameter::Contents(), GlowTags::Parameter::Children()) , m_cachedNumber(-1) { insert(begin(), new dom::VariantLeaf(GlowTags::Parameter::Number(), number)); } LIBEMBER_INLINE GlowParameter::GlowParameter(GlowNodeBase* parent, int number) : GlowParameterBase(GlowType::Parameter, GlowTags::ElementDefault(), GlowTags::Parameter::Contents(), GlowTags::Parameter::Children()) , m_cachedNumber(-1) { insert(begin(), new dom::VariantLeaf(GlowTags::Parameter::Number(), number)); if (parent) { GlowElementCollection* children = parent->children(); GlowElementCollection::iterator const where = children->end(); children->insert(where, this); } } LIBEMBER_INLINE GlowParameter::GlowParameter(int number, ber::Tag const& tag) : GlowParameterBase(GlowType::Parameter, tag, GlowTags::Parameter::Contents(), GlowTags::Parameter::Children()) , m_cachedNumber(-1) { insert(begin(), new dom::VariantLeaf(GlowTags::Parameter::Number(), number)); } LIBEMBER_INLINE GlowParameter::GlowParameter(ber::Tag const& tag) : GlowParameterBase(GlowType::Parameter, tag, GlowTags::Parameter::Contents(), GlowTags::Parameter::Children()) , m_cachedNumber(-1) {} LIBEMBER_INLINE int GlowParameter::number() const { if (m_cachedNumber == -1) { ber::Tag const tag = GlowTags::Parameter::Number(); const_iterator const first = begin(); const_iterator const last = end(); const_iterator const result = util::find_tag(first, last, tag); if (result != last) { m_cachedNumber = util::ValueConverter::valueOf(&*result, -1); } else { m_cachedNumber = -1; } } return m_cachedNumber; } LIBEMBER_INLINE GlowParameter::iterator GlowParameter::insertImpl(iterator const& where, Node* child) { m_cachedNumber = -1; return GlowContainer::insertImpl(where, child); } LIBEMBER_INLINE void GlowParameter::eraseImpl(iterator const& first, iterator const& last) { m_cachedNumber = -1; GlowContainer::eraseImpl(first, last); } } } #endif // __LIBEMBER_GLOW_GLOWPARAMETER_IPP
3,125
987
/**************************************************************************************** * @author: kzvd4729 created: Nov/29/2019 12:50 * solution_verdict: Accepted language: GNU C++14 * run_time: 31 ms memory_used: 0 KB * problem: https://codeforces.com/gym/102001/problem/A ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6,inf=1e9; int main() { ios_base::sync_with_stdio(0);cin.tie(0); string s;cin>>s;int one=0,zero=0; for(auto x:s)x=='1'?one++:zero++; char c='0';if(zero>=one)c='1'; string p; for(int i=1;i<=s.size();i++)p.push_back(c); if(one!=zero)cout<<p<<endl,exit(0); if(s[0]=='0') { cout<<'1'; for(int i=2;i<=s.size();i++)cout<<'0'; } else { cout<<'0'; for(int i=2;i<=s.size();i++)cout<<'1'; } return 0; }
1,095
384
#include "Bitmap.h" #include "OpenFileDialog.h" #include <iostream> #include <fstream> #include <windows.h> using namespace std; int main() { // Open File Dialog OpenFileDialog* openFileDialog1 = new OpenFileDialog(); openFileDialog1->ShowDialog(); // String Representation of Filename string filename(openFileDialog1->FileName); // Open BMP File ifstream ifs(filename, fstream::in | fstream::binary); // Ensure File is still Accessible if (!ifs.is_open()) { cout << filename << " can't be opened\n"; } // Ensure File is of type .bmp else if (!(filename.substr(filename.find_last_of(".") + 1) == "bmp")) { cout << filename << " is not a .bmp file\n"; } else { BMPHeader header; // Pass File to be read header.Fill(&ifs); // Display Various Information cout << header.toString(); // Inverse Pixels header.inversePixel(); // Write BMP File header.writeBMP(filename); } return 1; }
986
373
// Created on: 1994-08-03 // Created by: Christophe MARION // Copyright (c) 1994-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _HLRTopoBRep_OutLiner_HeaderFile #define _HLRTopoBRep_OutLiner_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TopoDS_Shape.hxx> #include <HLRTopoBRep_Data.hxx> #include <Standard_Transient.hxx> #include <BRepTopAdaptor_MapOfShapeTool.hxx> #include <Standard_Integer.hxx> class HLRAlgo_Projector; class TopoDS_Face; class HLRTopoBRep_OutLiner; DEFINE_STANDARD_HANDLE(HLRTopoBRep_OutLiner, Standard_Transient) class HLRTopoBRep_OutLiner : public Standard_Transient { public: Standard_EXPORT HLRTopoBRep_OutLiner(); Standard_EXPORT HLRTopoBRep_OutLiner(const TopoDS_Shape& OriSh); Standard_EXPORT HLRTopoBRep_OutLiner(const TopoDS_Shape& OriS, const TopoDS_Shape& OutS); void OriginalShape (const TopoDS_Shape& OriS); TopoDS_Shape& OriginalShape(); void OutLinedShape (const TopoDS_Shape& OutS); TopoDS_Shape& OutLinedShape(); HLRTopoBRep_Data& DataStructure(); Standard_EXPORT void Fill (const HLRAlgo_Projector& P, BRepTopAdaptor_MapOfShapeTool& MST, const Standard_Integer nbIso); DEFINE_STANDARD_RTTIEXT(HLRTopoBRep_OutLiner,Standard_Transient) protected: private: //! Builds faces from F and add them to S. Standard_EXPORT void ProcessFace (const TopoDS_Face& F, TopoDS_Shape& S, BRepTopAdaptor_MapOfShapeTool& M); Standard_EXPORT void BuildShape (BRepTopAdaptor_MapOfShapeTool& M); TopoDS_Shape myOriginalShape; TopoDS_Shape myOutLinedShape; HLRTopoBRep_Data myDS; }; #include <HLRTopoBRep_OutLiner.lxx> #endif // _HLRTopoBRep_OutLiner_HeaderFile
2,333
890
#include <gtest/gtest.h> #include <random> #include <string> #include "eddl/tensor/tensor.h" #include "eddl/tensor/nn/tensor_nn.h" #include "eddl/descriptors/descriptors.h" using namespace std; // Demo dataset static auto *ptr_iris = new float[150*4]{ 5.10, 3.50, 1.40, 0.20, 4.90, 3.00, 1.40, 0.20, 4.70, 3.20, 1.30, 0.20, 4.60, 3.10, 1.50, 0.20, 5.00, 3.60, 1.40, 0.20, 5.40, 3.90, 1.70, 0.40, 4.60, 3.40, 1.40, 0.30, 5.00, 3.40, 1.50, 0.20, 4.40, 2.90, 1.40, 0.20, 4.90, 3.10, 1.50, 0.10, 5.40, 3.70, 1.50, 0.20, 4.80, 3.40, 1.60, 0.20, 4.80, 3.00, 1.40, 0.10, 4.30, 3.00, 1.10, 0.10, 5.80, 4.00, 1.20, 0.20, 5.70, 4.40, 1.50, 0.40, 5.40, 3.90, 1.30, 0.40, 5.10, 3.50, 1.40, 0.30, 5.70, 3.80, 1.70, 0.30, 5.10, 3.80, 1.50, 0.30, 5.40, 3.40, 1.70, 0.20, 5.10, 3.70, 1.50, 0.40, 4.60, 3.60, 1.00, 0.20, 5.10, 3.30, 1.70, 0.50, 4.80, 3.40, 1.90, 0.20, 5.00, 3.00, 1.60, 0.20, 5.00, 3.40, 1.60, 0.40, 5.20, 3.50, 1.50, 0.20, 5.20, 3.40, 1.40, 0.20, 4.70, 3.20, 1.60, 0.20, 4.80, 3.10, 1.60, 0.20, 5.40, 3.40, 1.50, 0.40, 5.20, 4.10, 1.50, 0.10, 5.50, 4.20, 1.40, 0.20, 4.90, 3.10, 1.50, 0.20, 5.00, 3.20, 1.20, 0.20, 5.50, 3.50, 1.30, 0.20, 4.90, 3.60, 1.40, 0.10, 4.40, 3.00, 1.30, 0.20, 5.10, 3.40, 1.50, 0.20, 5.00, 3.50, 1.30, 0.30, 4.50, 2.30, 1.30, 0.30, 4.40, 3.20, 1.30, 0.20, 5.00, 3.50, 1.60, 0.60, 5.10, 3.80, 1.90, 0.40, 4.80, 3.00, 1.40, 0.30, 5.10, 3.80, 1.60, 0.20, 4.60, 3.20, 1.40, 0.20, 5.30, 3.70, 1.50, 0.20, 5.00, 3.30, 1.40, 0.20, 7.00, 3.20, 4.70, 1.40, 6.40, 3.20, 4.50, 1.50, 6.90, 3.10, 4.90, 1.50, 5.50, 2.30, 4.00, 1.30, 6.50, 2.80, 4.60, 1.50, 5.70, 2.80, 4.50, 1.30, 6.30, 3.30, 4.70, 1.60, 4.90, 2.40, 3.30, 1.00, 6.60, 2.90, 4.60, 1.30, 5.20, 2.70, 3.90, 1.40, 5.00, 2.00, 3.50, 1.00, 5.90, 3.00, 4.20, 1.50, 6.00, 2.20, 4.00, 1.00, 6.10, 2.90, 4.70, 1.40, 5.60, 2.90, 3.60, 1.30, 6.70, 3.10, 4.40, 1.40, 5.60, 3.00, 4.50, 1.50, 5.80, 2.70, 4.10, 1.00, 6.20, 2.20, 4.50, 1.50, 5.60, 2.50, 3.90, 1.10, 5.90, 3.20, 4.80, 1.80, 6.10, 2.80, 4.00, 1.30, 6.30, 2.50, 4.90, 1.50, 6.10, 2.80, 4.70, 1.20, 6.40, 2.90, 4.30, 1.30, 6.60, 3.00, 4.40, 1.40, 6.80, 2.80, 4.80, 1.40, 6.70, 3.00, 5.00, 1.70, 6.00, 2.90, 4.50, 1.50, 5.70, 2.60, 3.50, 1.00, 5.50, 2.40, 3.80, 1.10, 5.50, 2.40, 3.70, 1.00, 5.80, 2.70, 3.90, 1.20, 6.00, 2.70, 5.10, 1.60, 5.40, 3.00, 4.50, 1.50, 6.00, 3.40, 4.50, 1.60, 6.70, 3.10, 4.70, 1.50, 6.30, 2.30, 4.40, 1.30, 5.60, 3.00, 4.10, 1.30, 5.50, 2.50, 4.00, 1.30, 5.50, 2.60, 4.40, 1.20, 6.10, 3.00, 4.60, 1.40, 5.80, 2.60, 4.00, 1.20, 5.00, 2.30, 3.30, 1.00, 5.60, 2.70, 4.20, 1.30, 5.70, 3.00, 4.20, 1.20, 5.70, 2.90, 4.20, 1.30, 6.20, 2.90, 4.30, 1.30, 5.10, 2.50, 3.00, 1.10, 5.70, 2.80, 4.10, 1.30, 6.30, 3.30, 6.00, 2.50, 5.80, 2.70, 5.10, 1.90, 7.10, 3.00, 5.90, 2.10, 6.30, 2.90, 5.60, 1.80, 6.50, 3.00, 5.80, 2.20, 7.60, 3.00, 6.60, 2.10, 4.90, 2.50, 4.50, 1.70, 7.30, 2.90, 6.30, 1.80, 6.70, 2.50, 5.80, 1.80, 7.20, 3.60, 6.10, 2.50, 6.50, 3.20, 5.10, 2.00, 6.40, 2.70, 5.30, 1.90, 6.80, 3.00, 5.50, 2.10, 5.70, 2.50, 5.00, 2.00, 5.80, 2.80, 5.10, 2.40, 6.40, 3.20, 5.30, 2.30, 6.50, 3.00, 5.50, 1.80, 7.70, 3.80, 6.70, 2.20, 7.70, 2.60, 6.90, 2.30, 6.00, 2.20, 5.00, 1.50, 6.90, 3.20, 5.70, 2.30, 5.60, 2.80, 4.90, 2.00, 7.70, 2.80, 6.70, 2.00, 6.30, 2.70, 4.90, 1.80, 6.70, 3.30, 5.70, 2.10, 7.20, 3.20, 6.00, 1.80, 6.20, 2.80, 4.80, 1.80, 6.10, 3.00, 4.90, 1.80, 6.40, 2.80, 5.60, 2.10, 7.20, 3.00, 5.80, 1.60, 7.40, 2.80, 6.10, 1.90, 7.90, 3.80, 6.40, 2.00, 6.40, 2.80, 5.60, 2.20, 6.30, 2.80, 5.10, 1.50, 6.10, 2.60, 5.60, 1.40, 7.70, 3.00, 6.10, 2.30, 6.30, 3.40, 5.60, 2.40, 6.40, 3.10, 5.50, 1.80, 6.00, 3.00, 4.80, 1.80, 6.90, 3.10, 5.40, 2.10, 6.70, 3.10, 5.60, 2.40, 6.90, 3.10, 5.10, 2.30, 5.80, 2.70, 5.10, 1.90, 6.80, 3.20, 5.90, 2.30, 6.70, 3.30, 5.70, 2.50, 6.70, 3.00, 5.20, 2.30, 6.30, 2.50, 5.00, 1.90, 6.50, 3.00, 5.20, 2.00, 6.20, 3.40, 5.40, 2.30, 5.90, 3.00, 5.10, 1.80, }; static auto* t_iris = new Tensor({150, 4}, ptr_iris, DEV_CPU); // Demo image static auto* t_image = Tensor::arange(0, 100); // Random generators const int MIN_RANDOM = 0; const int MAX_RANDOM = 999999; static std::random_device rd; static std::mt19937 mt(rd()); static std::uniform_int_distribution<std::mt19937::result_type> dist6(MIN_RANDOM, MAX_RANDOM); TEST(TensorTestSuite, tensor_io_jpg) { // Generate random name int rdn_name = dist6(mt); string fname = "image_" + to_string(rdn_name) + ".jpg"; // Save file Tensor *t_ref = Tensor::concat({t_image, t_image, t_image}); // This jpeg needs 3 channels t_ref->reshape_({3, 10, 10}); // This jpeg needs 3 channels t_ref->save(fname); // All values are cast to integers // Load saved file Tensor* t_load = Tensor::load(fname); // Delete file int hasFailed = std::remove(fname.c_str()); if(hasFailed) { cout << "Error deleting file: " << fname << endl; } ASSERT_TRUE(Tensor::equivalent(t_ref, t_load, 1e-3f, 0.0f, true, true)); delete t_ref; delete t_load; } TEST(TensorTestSuite, tensor_io_png) { // Generate random name int rdn_name = dist6(mt); string fname = "image_" + to_string(rdn_name) + ".png"; // Save file Tensor *t_ref = Tensor::concat({t_image, t_image, t_image}); // This jpeg needs 3 channels t_ref->reshape_({3, 10, 10}); // This jpeg needs 3 channels t_ref->save(fname); // All values are cast to integers // Load saved file Tensor* t_load = Tensor::load(fname); // Delete file int hasFailed = std::remove(fname.c_str()); if(hasFailed) { cout << "Error deleting file: " << fname << endl; } ASSERT_TRUE(Tensor::equivalent(t_ref, t_load, 1e-3f, 0.0f, true, true)); delete t_ref; delete t_load; } TEST(TensorTestSuite, tensor_io_bmp) { // Generate random name int rdn_name = dist6(mt); string fname = "image_" + to_string(rdn_name) + ".bmp"; // Save file Tensor *t_ref = Tensor::concat({t_image, t_image, t_image}); // This jpeg needs 3 channels t_ref->reshape_({3, 10, 10}); // This jpeg needs 3 channels t_ref->save(fname); // All values are cast to integers // Load saved file Tensor* t_load = Tensor::load(fname); // Delete file int hasFailed = std::remove(fname.c_str()); if(hasFailed) { cout << "Error deleting file: " << fname << endl; } ASSERT_TRUE(Tensor::equivalent(t_ref, t_load, 1e-3f, 0.0f, true, true)); delete t_ref; delete t_load; } //TEST(TensorTestSuite, tensor_io_numpy) //{ // // Generate random name // int rdn_name = dist6(mt); // string fname = "iris_" + to_string(rdn_name) + ".npy"; // // // Save file // t_iris->save(fname); // // // Load saved file // Tensor* t_load = Tensor::load<float>(fname); // // // Delete file // int hasFailed = std::remove(fname.c_str()); // if(hasFailed) { cout << "Error deleting file: " << fname << endl; } // // ASSERT_TRUE(Tensor::equivalent(t_iris, t_load, 1e-3f, 0.0f, true, true)); //} //TEST(TensorTestSuite, tensor_io_csv) //{ // // Generate random name // int rdn_name = dist6(mt); // string fname = "iris_" + to_string(rdn_name) + ".csv"; // // // Save file // t_iris->save(fname); // // // Load saved file // Tensor* t_load = Tensor::load(fname); // // // Delete file // int hasFailed = std::remove(fname.c_str()); // if(hasFailed) { cout << "Error deleting file: " << fname << endl; } // // ASSERT_TRUE(Tensor::equivalent(t_iris, t_load, 1e-3f, 0.0f, true, true)); //} //TEST(TensorTestSuite, tensor_io_tsv) //{ // // Generate random name // int rdn_name = dist6(mt); // string fname = "iris_" + to_string(rdn_name) + ".tsv"; // // // Save file // t_iris->save(fname); // // // Load saved file // Tensor* t_load = Tensor::load(fname); // // // Delete file // int hasFailed = std::remove(fname.c_str()); // if(hasFailed) { cout << "Error deleting file: " << fname << endl; } // // ASSERT_TRUE(Tensor::equivalent(t_iris, t_load, 1e-3f, 0.0f, true, true)); //} //TEST(TensorTestSuite, tensor_io_txt) //{ // // Generate random name // int rdn_name = dist6(mt); // string fname = "iris_" + to_string(rdn_name) + ".txt"; // // // Save file // t_iris->save2txt(fname, ' ', {"sepal.length" , "sepal.width", "petal.length", "petal.width"}); // // // Load saved file // Tensor* t_load = Tensor::load_from_txt(fname, ' ', 1); // // // Delete file // int hasFailed = std::remove(fname.c_str()); // if(hasFailed) { cout << "Error deleting file: " << fname << endl; } // // ASSERT_TRUE(Tensor::equivalent(t_iris, t_load, 1e-3f, 0.0f, true, true)); //} TEST(TensorTestSuite, tensor_io_bin) { // Generate random name int rdn_name = dist6(mt); string fname = "iris_" + to_string(rdn_name) + ".bin"; // Save file t_iris->save(fname); // Load saved file Tensor* t_load = Tensor::load(fname); // Delete file int hasFailed = std::remove(fname.c_str()); if(hasFailed) { cout << "Error deleting file: " << fname << endl; } ASSERT_TRUE(Tensor::equivalent(t_iris, t_load, 1e-3f, 0.0f, true, true)); delete t_iris; delete t_load; }
10,301
5,949
// Tags: DP // Difficulty: 4.5 // Priority: 1 // Date: 23-07-2021 #include <bits/stdc++.h> #define all(A) begin(A), end(A) #define rall(A) rbegin(A), rend(A) #define sz(A) int(A.size()) #define pb push_back #define mp make_pair using namespace std; typedef long long ll; typedef pair <int, int> pii; typedef pair <ll, ll> pll; typedef vector <int> vi; typedef vector <ll> vll; typedef vector <pii> vpii; typedef vector <pll> vpll; int main () { ios::sync_with_stdio(false); cin.tie(0); int tt; cin >> tt; while (tt--) { int n, k; cin >> n >> k; vi a(n + 1); for (int i = 1; i <= n; i++) cin >> a[i]; vi dp(n + 1, -1); // dp(i) = maximum number of fixed points with an array of size i dp[0] = 0; for (int i = 1; i <= n; i++) { for (int j = n; j > 0; j--) { if (dp[j - 1] == -1) continue; dp[j] = max(dp[j], dp[j - 1] + (a[i] == j)); } } int ans = -1; for (int i = n; i >= 1; i--) { if (dp[i] >= k) { ans = n - i; break; } } cout << ans << '\n'; } return (0); }
1,096
506
#ifndef EXAMPLE_POSTGRESQL_MOLECULESERVICE_HPP #define EXAMPLE_POSTGRESQL_MOLECULESERVICE_HPP #include "db/MoleculeDb.hpp" #include "dto/StatusDto.hpp" #include "dto/MoleculeDto.hpp" #include "dto/MoleculesListDto.hpp" #include "oatpp/web/protocol/http/Http.hpp" #include "oatpp/core/macro/component.hpp" class MoleculeService { private: typedef oatpp::web::protocol::http::Status Status; private: OATPP_COMPONENT(std::shared_ptr<MoleculeDb>, m_database); // Inject database component public: oatpp::Object<MoleculeDto> getMoleculeById(const oatpp::Int64& id); oatpp::Object<MoleculeDetailedDto> getExactMolecule(const oatpp::String& structure); oatpp::Object<ListDto<oatpp::Object<MoleculeDto>>> getSubstructureMatches(const oatpp::String& structure, const oatpp::Int64& limit); oatpp::Object<SimListDto<oatpp::Object<MoleculeDto>>> getSimilarityMatches(const oatpp::String& structure, const oatpp::Int64& limit, const oatpp::Float64& threshold); }; #endif //EXAMPLE_POSTGRESQL_MOLECULESERVICE_HPP
1,017
420
/* ** Copyright (C) 2020 SoftBank Robotics Europe ** See COPYING for the license */ #pragma once #ifndef QIPYTHON_GUARD_HPP #define QIPYTHON_GUARD_HPP #include <qipython/common.hpp> #include <ka/typetraits.hpp> #include <type_traits> namespace qi { namespace py { /// DefaultConstructible Guard /// Procedure<_ (Args)> F template<typename Guard, typename F, typename... Args> ka::ResultOf<F(Args&&...)> invokeGuarded(F&& f, Args&&... args) { Guard g; return std::forward<F>(f)(std::forward<Args>(args)...); } namespace detail { // Guards the copy, construction and destruction of an object, and only when // in case of copy construction the source object evaluates to true, and in case // of destruction, the object itself evaluates to true. // // Explanation: // pybind11::object only requires the GIL to be locked on copy and if the // source is not null. Default construction does not require the GIL either. template<typename Guard, typename Object> class Guarded { using Storage = typename std::aligned_storage<sizeof(Object), alignof(Object)>::type; Storage _object; Object& object() { return reinterpret_cast<Object&>(_object); } const Object& object() const { return reinterpret_cast<const Object&>(_object); } public: template<typename Arg0, typename... Args, ka::EnableIf<std::is_constructible<Object, Arg0&&, Args&&...>::value, int> = 0> explicit Guarded(Arg0&& arg0, Args&&... args) { Guard g; new(&_object) Object(std::forward<Arg0>(arg0), std::forward<Args>(args)...); } Guarded() { // Default construction, no GIL needed. new(&_object) Object(); } Guarded(Guarded& o) { boost::optional<Guard> optGuard; if (o.object()) optGuard.emplace(); new(&_object) Object(o.object()); } Guarded(const Guarded& o) { boost::optional<Guard> optGuard; if (o.object()) optGuard.emplace(); new(&_object) Object(o.object()); } Guarded(Guarded&& o) { new(&_object) Object(std::move(o.object())); } ~Guarded() { boost::optional<Guard> optGuard; if (object()) optGuard.emplace(); object().~Object(); } Guarded& operator=(const Guarded& o) { if (this == &o) return *this; { boost::optional<Guard> optGuard; if (o.object()) optGuard.emplace(); object() = o.object(); } return *this; } Guarded& operator=(Guarded&& o) { if (this == &o) return *this; object() = std::move(o.object()); return *this; } Object& operator*() { return object(); } const Object& operator*() const { return object(); } Object* operator->() { return &object(); } const Object* operator->() const { return &object(); } explicit operator Object&() { return object(); } explicit operator const Object&() const { return object(); } }; } // namespace detail /// Wraps a pybind11::object value and locks the GIL on copy and destruction. /// /// This is useful for instance to put pybind11 objects in lambda functions so /// that they can be copied around safely. using GILGuardedObject = detail::Guarded<pybind11::gil_scoped_acquire, pybind11::object>; } // namespace py } // namespace qi #endif // QIPYTHON_GUARD_HPP
3,234
1,102
/* * djnn v2 * * The copyright holders for the contents of this file are: * Ecole Nationale de l'Aviation Civile, France (2018) * See file "license.terms" for the rights and conditions * defined by copyright holders. * * * Contributors: * Mathieu Magnaudet <mathieu.magnaudet@enac.fr> * */ #include "../backend.h" #include "../transformation/transformations.h" #include "qt_context.h" #include "qt_backend.h" #include "qt_window.h" #include <QtWidgets/QWidget> #include <QtGui/QPainter> #include <QtCore/QtMath> #include <QtCore/QFileInfo> #include <iostream> #include <cmath> namespace djnn { QtBackend *QtBackend::_instance; std::once_flag QtBackend::onceFlag; QtBackend* QtBackend::instance () { std::call_once (QtBackend::onceFlag, [] () { _instance = new QtBackend(); }); return _instance; } QtBackend::QtBackend () : _painter (nullptr), _picking_view (nullptr) { _context_manager = new QtContextManager (); } QtBackend::~QtBackend () { if (_context_manager) { delete _context_manager; _context_manager = nullptr;} } void QtBackend::save_context () { if (_painter != nullptr) _painter->save (); } void QtBackend::restore_context () { if (_painter != nullptr) _painter->restore (); } void QtBackend::set_painter (QPainter* p) { _painter = p; } void QtBackend::set_picking_view (QtPickingView* p) { _picking_view = p; } /* Qt context management is imported from djnn v1 */ void QtBackend::load_drawing_context (AbstractGShape *s, double tx, double ty, double width, double height) { QtContext *cur_context = _context_manager->get_current (); QMatrix4x4 matrix = cur_context->matrix; QTransform transform = matrix.toTransform (); if (s->matrix () != nullptr) { Homography *h = dynamic_cast<Homography*> (s->matrix ()); Homography *hi = dynamic_cast<Homography*> (s->inverted_matrix ()); QMatrix4x4 loc_matrix = QMatrix4x4 (matrix); h->_m11->set_value (loc_matrix (0, 0), false); h->_m12->set_value (loc_matrix (0, 1), false); h->_m13->set_value (loc_matrix (0, 2), false); h->_m14->set_value (loc_matrix (0, 3), false); h->_m21->set_value (loc_matrix (1, 0), false); h->_m22->set_value (loc_matrix (1, 1), false); h->_m23->set_value (loc_matrix (1, 2), false); h->_m24->set_value (loc_matrix (1, 3), false); h->_m31->set_value (loc_matrix (2, 0), false); h->_m32->set_value (loc_matrix (2, 1), false); h->_m33->set_value (loc_matrix (2, 2), false); h->_m34->set_value (loc_matrix (2, 3), false); h->_m41->set_value (loc_matrix (3, 0), false); h->_m42->set_value (loc_matrix (3, 1), false); h->_m43->set_value (loc_matrix (3, 2), false); h->_m44->set_value (loc_matrix (3, 3), false); loc_matrix = loc_matrix.inverted (); hi->_m11->set_value (loc_matrix (0, 0), false); hi->_m12->set_value (loc_matrix (0, 1), false); hi->_m13->set_value (loc_matrix (0, 2), false); hi->_m14->set_value (loc_matrix (0, 3), false); hi->_m21->set_value (loc_matrix (1, 0), false); hi->_m22->set_value (loc_matrix (1, 1), false); hi->_m23->set_value (loc_matrix (1, 2), false); hi->_m24->set_value (loc_matrix (1, 3), false); hi->_m31->set_value (loc_matrix (2, 0), false); hi->_m32->set_value (loc_matrix (2, 1), false); hi->_m33->set_value (loc_matrix (2, 2), false); hi->_m34->set_value (loc_matrix (2, 3), false); hi->_m41->set_value (loc_matrix (3, 0), false); hi->_m42->set_value (loc_matrix (3, 1), false); hi->_m43->set_value (loc_matrix (3, 2), false); hi->_m44->set_value (loc_matrix (3, 3), false); } /* setup the painting environment of the drawing view */ QPen tmpPen (cur_context->pen); /* * with Qt, dash pattern and dash offset are specified * in stroke-width unit so we need to update the values accordingly */ if (cur_context->pen.style () == Qt::CustomDashLine) { qreal w = cur_context->pen.widthF () || 1; QVector<qreal> dashPattern = cur_context->pen.dashPattern (); QVector<qreal> tmp (dashPattern.size ()); for (int i = 0; i < dashPattern.size (); i++) tmp[i] = dashPattern.value (i) / w; tmpPen.setDashPattern (tmp); tmpPen.setDashOffset (cur_context->pen.dashOffset () / w); } _painter->setRenderHint (QPainter::Antialiasing, true); _painter->setPen (tmpPen); _painter->setTransform (transform); /* If the brush style is gradient and the coordinate mode is ObjectBoundingMode * then translate the rotation axis of the gradient transform and transpose * the translation values in the global coordinate system*/ if (cur_context->brush.style () == Qt::LinearGradientPattern || cur_context->brush.style () == Qt::RadialGradientPattern) { if (cur_context->brush.gradient ()->coordinateMode () == QGradient::ObjectBoundingMode) { QTransform origin = cur_context->gradientTransform; QTransform newT = QTransform (); newT.translate (tx, ty); QTransform result = origin * newT; result.translate (-tx, -ty); double m11 = result.m11 (); double m12 = result.m12 (); double m13 = result.m13 (); double m21 = result.m21 (); double m22 = result.m22 (); double m23 = result.m23 (); double m31 = result.m31 () * width; double m32 = result.m32 () * height; double m33 = result.m33 (); result.setMatrix (m11, m12, m13, m21, m22, m23, m31, m32, m33); cur_context->gradientTransform = result; } } cur_context->brush.setTransform (cur_context->gradientTransform); _painter->setBrush (cur_context->brush); } void QtBackend::load_pick_context (AbstractGShape *s) { QtContext *cur_context = _context_manager->get_current (); QPen pickPen; QBrush pickBrush (_picking_view->pick_color ()); pickPen.setStyle (Qt::SolidLine); pickPen.setColor (_picking_view->pick_color ()); pickPen.setWidth (cur_context->pen.width()); _picking_view->painter ()->setPen (pickPen); _picking_view->painter ()->setBrush (pickBrush); _picking_view->painter ()->setTransform (cur_context->matrix.toTransform ()); _picking_view->add_gobj (s); } WinImpl* QtBackend::create_window (Window *win, const std::string& title, double x, double y, double w, double h) { return new QtWindow (win, title, x, y, w, h); } bool QtBackend::is_in_picking_view (AbstractGShape *s) { return is_pickable (s); /*return s->press ()->has_coupling () || s->x ()->has_coupling () || s->y ()->has_coupling () || s->move ()->has_coupling () || s->release ()->has_coupling () || s->enter ()->has_coupling () || s->leave ()->has_coupling ();*/ } static QFont::Style fontStyleArray[3] = { QFont::StyleNormal, QFont::StyleItalic, QFont::StyleOblique }; void QtBackend::update_text_geometry (Text* text, FontFamily* ff, FontSize* fsz, FontStyle* fs, FontWeight *fw) { QFont qfont; if (ff) { QString val (ff->family()->get_value ().c_str ()); qfont.setFamily (val); } if (fsz) { qfont.setPixelSize (fsz->size ()->get_value ()); } if (fs) { int i = fs->style ()->get_value (); if (i >= 0 && i <= 3) qfont.setStyle (fontStyleArray [i]); } if (fw) { qfont.setWeight (fw->weight ()->get_value ()); } QString str (text->text ()->get_value().c_str ()); QFontMetrics fm (qfont); int width = fm.width (str); int height = fm.height (); text->set_width (width); text->set_height (height); } } /* namespace djnn */
7,820
2,884
//************************************ bs::framework - Copyright 2018 Marko Pintera **************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// #include "Managers/BsMeshManager.h" #include "BsCoreApplication.h" #include "Math/BsVector3.h" #include "Mesh/BsMesh.h" #include "RenderAPI/BsVertexDataDesc.h" namespace bs { MeshManager::MeshManager() { } MeshManager::~MeshManager() { } void MeshManager::onStartUp() { SPtr<VertexDataDesc> vertexDesc = bs_shared_ptr_new<VertexDataDesc>(); vertexDesc->addVertElem(VET_FLOAT3, VES_POSITION); mDummyMeshData = bs_shared_ptr_new<MeshData>(1, 3, vertexDesc); auto vecIter = mDummyMeshData->getVec3DataIter(VES_POSITION); vecIter.setValue(Vector3(0, 0, 0)); auto indices = mDummyMeshData->getIndices32(); indices[0] = 0; indices[1] = 0; indices[2] = 0; mDummyMesh = Mesh::create(mDummyMeshData); } }
979
393
#include <cstdio> #include "rss_expl.h" #include "../ExprLib/exprman.h" #include "../ExprLib/mod_vars.h" // For ordering states #include "../include/heap.h" #include "../Modules/expl_states.h" // ****************************************************************** // * * // * expl_reachset methods * // * * // ****************************************************************** expl_reachset::expl_reachset(StateLib::state_db* ss) { state_dictionary = ss; state_dictionary->ConvertToStatic(true); state_handle = 0; state_collection = 0; DCASSERT(state_dictionary); natorder = new natural_db_iter(*state_dictionary); needs_discorder = false; discorder = 0; lexorder = 0; } expl_reachset::~expl_reachset() { delete state_dictionary; delete[] state_handle; delete state_collection; delete natorder; delete discorder; delete lexorder; } StateLib::state_db* expl_reachset::getStateDatabase() const { return state_dictionary; } void expl_reachset::getNumStates(long &ns) const { if (state_dictionary) { ns = state_dictionary->Size(); } else { DCASSERT(state_collection); ns = state_collection->Size(); } } void expl_reachset::showInternal(OutputStream &os) const { long ns; getNumStates(ns); for (long i=0; i<ns; i++) { long bytes = 0; const unsigned char* ptr = 0; os << "State " << i << " internal:"; if (state_dictionary) { ptr = state_dictionary->GetRawState(i, bytes); } else { DCASSERT(state_collection); DCASSERT(state_handle); ptr = state_collection->GetRawState(state_handle[i], bytes); } for (long b=0; b<bytes; b++) { os.Put(' '); os.PutHex(ptr[b]); } os.Put('\n'); os.flush(); } } void expl_reachset::showState(OutputStream &os, const shared_state* st) const { st->Print(os, 0); } state_lldsm::reachset::iterator& expl_reachset ::iteratorForOrder(state_lldsm::display_order ord) { DCASSERT(state_dictionary || (state_collection && state_handle)); switch (ord) { case state_lldsm::DISCOVERY: if (needs_discorder) { if (0==discorder) { discorder = new discovery_coll_iter(*state_collection, state_handle); } return *discorder; } DCASSERT(natorder); return *natorder; case state_lldsm::LEXICAL: if (0==lexorder) { if (state_dictionary) { lexorder = new lexical_db_iter(getGrandParent(), *state_dictionary); } else { lexorder = new lexical_coll_iter(getGrandParent(), *state_collection, state_handle); } } return *lexorder; case state_lldsm::NATURAL: default: DCASSERT(natorder); return *natorder; }; } state_lldsm::reachset::iterator& expl_reachset::easiestIterator() const { DCASSERT(natorder); return *natorder; } void expl_reachset::Finish() { // Compact states state_collection = state_dictionary->TakeStateCollection(); delete state_dictionary; state_dictionary = 0; state_handle = state_collection->RemoveIndexHandles(); // Update iterators DCASSERT(state_collection); DCASSERT(state_handle); delete natorder; natorder = new natural_coll_iter(*state_collection, state_handle); delete lexorder; lexorder = 0; delete discorder; discorder = 0; } void expl_reachset::Renumber(const GraphLib::node_renumberer* Ren) { if (0==Ren) return; if (!Ren->changes_something()) return; DCASSERT(state_collection); DCASSERT(state_handle); // Renumber state_handle array long* aux = new long[state_collection->Size()]; for (long i=state_collection->Size()-1; i>=0; i--) { aux[i] = state_handle[i]; } for (long i=state_collection->Size()-1; i>=0; i--) { CHECK_RANGE(0, Ren->new_number(i), state_collection->Size()); state_handle[Ren->new_number(i)] = aux[i]; } delete[] aux; needs_discorder = true; } // ****************************************************************** // * * // * expl_reachset::db_iterator methods * // * * // ****************************************************************** expl_reachset::db_iterator::db_iterator(const StateLib::state_db &s) : indexed_iterator(s.Size()), states(s) { } expl_reachset::db_iterator::~db_iterator() { } void expl_reachset::db_iterator::copyState(shared_state* st, long o) const { states.GetStateKnown(ord2index(o), st->writeState(), st->getStateSize()); } // ****************************************************************** // * * // * expl_reachset::coll_iterator methods * // * * // ****************************************************************** expl_reachset::coll_iterator::coll_iterator(const StateLib::state_coll &SC, const long* SH) : indexed_iterator(SC.Size()), states(SC), state_handle(SH) { DCASSERT(state_handle); } expl_reachset::coll_iterator::~coll_iterator() { } void expl_reachset::coll_iterator::copyState(shared_state* st, long o) const { states.GetStateKnown(state_handle[ord2index(o)], st->writeState(), st->getStateSize()); } // ****************************************************************** // * * // * expl_reachset::natural_db_iter methods * // * * // ****************************************************************** expl_reachset::natural_db_iter::natural_db_iter(const StateLib::state_db &s) : db_iterator(s) { // nothing! } // ****************************************************************** // * * // * expl_reachset::natural_coll_iter methods * // * * // ****************************************************************** expl_reachset::natural_coll_iter::natural_coll_iter(const StateLib::state_coll &SC, const long* SH) : coll_iterator(SC, SH) { // nothing! } // ****************************************************************** // * * // * expl_reachset::discovery_coll_iter methods * // * * // ****************************************************************** expl_reachset::discovery_coll_iter::discovery_coll_iter(const StateLib::state_coll &SC, const long* SH) : coll_iterator(SC, SH) { long* M = new long[SC.Size()]; DCASSERT(SH); HeapSort(SH, M, SC.Size()); setMap(M); } // ****************************************************************** // * * // * expl_reachset::lexical_db_iter methods * // * * // ****************************************************************** expl_reachset::lexical_db_iter::lexical_db_iter(const hldsm* hm, const StateLib::state_db &s) : db_iterator(s) { long* M = new long[s.Size()]; const StateLib::state_coll* coll = s.GetStateCollection(); LexicalSort(hm, coll, M); setMap(M); } // ****************************************************************** // * * // * expl_reachset::lexical_coll_iter methods * // * * // ****************************************************************** expl_reachset::lexical_coll_iter::lexical_coll_iter(const hldsm* hm, const StateLib::state_coll &SC, const long* SH) : coll_iterator(SC, SH) { long* M = new long[SC.Size()]; DCASSERT(SH); LexicalSort(hm, &SC, SH, M); setMap(M); }
8,210
2,426
// RUN: %clangxx_msan -O0 -g %s -o %t && %run %t // ftime() is deprecated on FreeBSD and NetBSD. // UNSUPPORTED: freebsd, netbsd #include <assert.h> #include <sys/timeb.h> #include <sanitizer/msan_interface.h> int main(void) { struct timeb tb; int res = ftime(&tb); assert(!res); assert(__msan_test_shadow(&tb, sizeof(tb)) == -1); return 0; }
357
157
#include <system.hh> #include <urbite.hh> #include <process.hh> #include <strutils.hh> using namespace makemore; extern "C" void mainmore(Process *); void mainmore( Process *process ) { unsigned int itabn = process->itab.size(); if (itabn < 2) return; strvec argext; if (!process->read(&argext, itabn - 1)) return; process->itab[itabn - 1]->unlink_reader(process); process->itab.resize(itabn - 1); Command shellmore = find_command("sh"); process->cmd = "sh"; process->func = shellmore; strvec bak_args = process->args; catstrvec(process->args, argext); shellmore(process); process->cmd = "args"; process->func = mainmore; process->args = bak_args; }
698
269
// $Id$ #include "ACEXML/common/Element_Def_Builder.h" ACEXML_Element_Def_Builder::~ACEXML_Element_Def_Builder () { }
122
54
/***************************************************************** | | Platinum - Synchronous Media Browser | | Copyright (c) 2004-2010, Plutinosoft, LLC. | All rights reserved. | http://www.plutinosoft.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. | | OEMs, ISVs, VARs and other distributors that combine and | distribute commercially licensed software with Platinum software | and do not wish to distribute the source code for the commercially | licensed software under version 2, or (at your option) any later | version, of the GNU General Public License (the "GPL") must enter | into a commercial license agreement with Plutinosoft, LLC. | licensing@plutinosoft.com | | This program is distributed in the hope that it will be useful, | but WITHOUT ANY WARRANTY; without even the implied warranty of | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | GNU General Public License for more details. | | You should have received a copy of the GNU General Public License | along with this program; see the file LICENSE.txt. If not, write to | the Free Software Foundation, Inc., | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. | http://www.gnu.org/licenses/gpl-2.0.html | ****************************************************************/ /*---------------------------------------------------------------------- | includes +---------------------------------------------------------------------*/ #include "PltSyncMediaBrowser.h" NPT_SET_LOCAL_LOGGER("platinum.media.server.syncbrowser") /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::PLT_SyncMediaBrowser +---------------------------------------------------------------------*/ PLT_SyncMediaBrowser::PLT_SyncMediaBrowser(PLT_CtrlPointReference& ctrlPoint, bool use_cache /* = false */, PLT_MediaContainerChangesListener* listener /* = NULL */) : PLT_MediaBrowser(ctrlPoint), m_ContainerListener(listener), m_UseCache(use_cache) { SetDelegate(this); } /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::~PLT_SyncMediaBrowser +---------------------------------------------------------------------*/ PLT_SyncMediaBrowser::~PLT_SyncMediaBrowser() { } /* Blocks forever waiting for a response from a request * It is expected the request to succeed or to timeout and return an error eventually */ /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::WaitForResponse +---------------------------------------------------------------------*/ NPT_Result PLT_SyncMediaBrowser::WaitForResponse(NPT_SharedVariable& shared_var) { return shared_var.WaitUntilEquals(1, 30000); } /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::OnDeviceAdded +---------------------------------------------------------------------*/ NPT_Result PLT_SyncMediaBrowser::OnDeviceAdded(PLT_DeviceDataReference& device) { NPT_String uuid = device->GetUUID(); // test if it's a media server PLT_Service* service; if (NPT_SUCCEEDED(device->FindServiceByType("urn:schemas-upnp-org:service:ContentDirectory:*", service))) { NPT_AutoLock lock(m_MediaServers); m_MediaServers.Put(uuid, device); } return PLT_MediaBrowser::OnDeviceAdded(device); } /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::OnDeviceRemoved +---------------------------------------------------------------------*/ NPT_Result PLT_SyncMediaBrowser::OnDeviceRemoved(PLT_DeviceDataReference& device) { NPT_String uuid = device->GetUUID(); // Remove from our list of servers first if found { NPT_AutoLock lock(m_MediaServers); m_MediaServers.Erase(uuid); } // clear cache for that device if (m_UseCache) m_Cache.Clear(device.AsPointer()->GetUUID()); return PLT_MediaBrowser::OnDeviceRemoved(device); } /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::Find +---------------------------------------------------------------------*/ NPT_Result PLT_SyncMediaBrowser::Find(const char* ip, PLT_DeviceDataReference& device) { NPT_AutoLock lock(m_MediaServers); const NPT_List<PLT_DeviceMapEntry*>::Iterator it = m_MediaServers.GetEntries().Find(PLT_DeviceMapFinderByIp(ip)); if (it) { device = (*it)->GetValue(); return NPT_SUCCESS; } return NPT_FAILURE; } /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::OnBrowseResult +---------------------------------------------------------------------*/ void PLT_SyncMediaBrowser::OnBrowseResult(NPT_Result res, PLT_DeviceDataReference& device, PLT_BrowseInfo* info, void* userdata) { NPT_COMPILER_UNUSED(device); if (!userdata) return; PLT_BrowseDataReference* data = (PLT_BrowseDataReference*) userdata; (*data)->res = res; if (NPT_SUCCEEDED(res) && info) { (*data)->info = *info; } (*data)->shared_var.SetValue(1); delete data; } /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::OnMSStateVariablesChanged +---------------------------------------------------------------------*/ void PLT_SyncMediaBrowser::OnMSStateVariablesChanged(PLT_Service* service, NPT_List<PLT_StateVariable*>* vars) { NPT_AutoLock lock(m_MediaServers); PLT_DeviceDataReference device; const NPT_List<PLT_DeviceMapEntry*>::Iterator it = m_MediaServers.GetEntries().Find(PLT_DeviceMapFinderByUUID(service->GetDevice()->GetUUID())); if (!it) return; // device with this service has gone away device = (*it)->GetValue(); PLT_StateVariable* var = PLT_StateVariable::Find(*vars, "ContainerUpdateIDs"); if (var) { // variable found, parse value NPT_String value = var->GetValue(); NPT_String item_id, update_id; int index; while (value.GetLength()) { // look for container id index = value.Find(','); if (index < 0) break; item_id = value.Left(index); value = value.SubString(index+1); // look for update id if (value.GetLength()) { index = value.Find(','); update_id = (index<0)?value:value.Left(index); value = (index<0)?"":value.SubString(index+1); // clear cache for that device if (m_UseCache) m_Cache.Clear(device->GetUUID(), item_id); // notify listener if (m_ContainerListener) m_ContainerListener->OnContainerChanged(device, item_id, update_id); } } } } /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::BrowseSync +---------------------------------------------------------------------*/ NPT_Result PLT_SyncMediaBrowser::BrowseSync(PLT_BrowseDataReference& browse_data, PLT_DeviceDataReference& device, const char* object_id, NPT_Int32 index, NPT_Int32 count, bool browse_metadata, const char* filter, const char* sort) { NPT_Result res; browse_data->shared_var.SetValue(0); browse_data->info.si = index; // send off the browse packet. Note that this will // not block. There is a call to WaitForResponse in order // to block until the response comes back. res = PLT_MediaBrowser::Browse(device, (const char*)object_id, index, count, browse_metadata, filter, sort, new PLT_BrowseDataReference(browse_data)); NPT_CHECK_SEVERE(res); return WaitForResponse(browse_data->shared_var); } /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::BrowseSync +---------------------------------------------------------------------*/ NPT_Result PLT_SyncMediaBrowser::BrowseSync(PLT_DeviceDataReference& device, const char* object_id, PLT_MediaObjectListReference& list, bool metadata, /* = false */ NPT_Int32 start, /* = 0 */ NPT_Cardinal max_results /* = 0 */) { NPT_Result res = NPT_FAILURE; NPT_Int32 index = start; // only cache metadata or if starting from 0 and asking for maximum bool cache = m_UseCache && (metadata || (start == 0 && max_results == 0)); // reset output params list = NULL; // look into cache first if (cache && NPT_SUCCEEDED(m_Cache.Get(device->GetUUID(), object_id, list))) return NPT_SUCCESS; do { PLT_BrowseDataReference browse_data(new PLT_BrowseData(), true); // send off the browse packet. Note that this will // not block. There is a call to WaitForResponse in order // to block until the response comes back. res = BrowseSync( browse_data, device, (const char*)object_id, index, metadata?1:30, // DLNA recommendations for browsing children is no more than 30 at a time metadata); NPT_CHECK_LABEL_WARNING(res, done); if (NPT_FAILED(browse_data->res)) { res = browse_data->res; NPT_CHECK_LABEL_WARNING(res, done); } // server returned no more, bail now if (browse_data->info.items->GetItemCount() == 0) break; if (list.IsNull()) { list = browse_data->info.items; } else { list->Add(*browse_data->info.items); // clear the list items so that the data inside is not // cleaned up by PLT_MediaItemList dtor since we copied // each pointer into the new list. browse_data->info.items->Clear(); } // stop now if our list contains exactly what the server said it had. // Note that the server could return 0 if it didn't know how many items were // available. In this case we have to continue browsing until // nothing is returned back by the server. // Unless we were told to stop after reaching a certain amount to avoid // length delays // (some servers may return a total matches out of whack at some point too) if ((browse_data->info.tm && browse_data->info.tm <= list->GetItemCount()) || (max_results && list->GetItemCount() >= max_results)) break; // ask for the next chunk of entries index = list->GetItemCount(); } while(1); done: // cache the result if (cache && NPT_SUCCEEDED(res) && !list.IsNull() && list->GetItemCount()) { m_Cache.Put(device->GetUUID(), object_id, list); } // clear entire cache data for device if failed, the device could be gone if (NPT_FAILED(res) && cache) m_Cache.Clear(device->GetUUID()); return res; } /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::IsCached +---------------------------------------------------------------------*/ bool PLT_SyncMediaBrowser::IsCached(const char* uuid, const char* object_id) { NPT_AutoLock lock(m_MediaServers); const NPT_List<PLT_DeviceMapEntry*>::Iterator it = m_MediaServers.GetEntries().Find(PLT_DeviceMapFinderByUUID(uuid)); if (!it) { m_Cache.Clear(uuid); return false; // device with this service has gone away } PLT_MediaObjectListReference list; return NPT_SUCCEEDED(m_Cache.Get(uuid, object_id, list))?true:false; }
12,695
3,461
/************************************************************************ Copyright 2020 Advanced Micro Devices, 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 "lavaApiFramebuffer.h" #include "aovDescriptor.h" #include "pxr/imaging/rprUsd/helpers.h" PXR_NAMESPACE_OPEN_SCOPE HdRprApiFramebuffer::HdRprApiFramebuffer(rpr::Context* context, uint32_t width, uint32_t height) : m_context(context) , m_rprFb(nullptr) , m_width(0) , m_height(0) , m_aov(kAovNone) { if (!m_context) { LAVA_THROW_ERROR_MSG("Failed to create framebuffer: missing rpr context"); } Create(width, height); } HdRprApiFramebuffer::HdRprApiFramebuffer(HdRprApiFramebuffer&& fb) noexcept { *this = std::move(fb); } HdRprApiFramebuffer::~HdRprApiFramebuffer() { Delete(); } HdRprApiFramebuffer& HdRprApiFramebuffer::operator=(HdRprApiFramebuffer&& fb) noexcept { m_context = fb.m_context; m_width = fb.m_width; m_height = fb.m_height; m_aov = fb.m_aov; m_rprFb = fb.m_rprFb; fb.m_width = 0u; fb.m_height = 0u; fb.m_aov = kAovNone; fb.m_rprFb = nullptr; return *this; } void HdRprApiFramebuffer::AttachAs(lava::Aov aov) { if (m_aov != kAovNone || aov == kAovNone) { //LAVA_ERROR_CHECK(m_context->SetAOV(m_aov, nullptr), "Failed to detach aov framebuffer"); } if (aov != kAovNone) { //LAVA_ERROR_CHECK_THROW(m_context->SetAOV(aov, m_rprFb), "Failed to attach aov framebuffer"); } m_aov = aov; } void HdRprApiFramebuffer::Clear(float r, float g, float b, float a) { if (m_width == 0 || m_height == 0) { return; } LAVA_ERROR_CHECK(m_rprFb->Clear(), "Failed to clear framebuffer"); // XXX (FIR-1681): We can not rely on clear values because every AOV in LAVA is multisampled, i.e. // value of singlesampled AOV (any ID AOV, worldCoordinate, etc) is always equals to `clearValue + renderedValue` /*if (r == 0.0f && g == 0.0f && b == 0.0f && a == 0.0f) { LAVA_ERROR_CHECK(m_rprFb->Clear(), "Failed to clear framebuffer"); } else { LAVA_ERROR_CHECK(m_rprFb->FillWithColor(r, g, b, a), "Failed to clear framebuffer"); }*/ } void HdRprApiFramebuffer::Resolve(HdRprApiFramebuffer* dstFrameBuffer) { if (!m_rprFb || !dstFrameBuffer || !dstFrameBuffer->m_rprFb) { return; } LAVA_ERROR_CHECK_THROW(m_context->ResolveFrameBuffer(m_rprFb, dstFrameBuffer->m_rprFb, true), "Failed to resolve framebuffer"); } bool HdRprApiFramebuffer::Resize(uint32_t width, uint32_t height) { if (m_width == width && m_height == height) { return false; } lava::Aov aov = m_aov; Delete(); Create(width, height); if (aov != kAovNone) { AttachAs(aov); } return true; } bool HdRprApiFramebuffer::GetData(void* dstBuffer, size_t dstBufferSize) { if (m_width == 0 || m_height == 0 || !m_rprFb) { return false; } auto size = GetSize(); if (size > dstBufferSize) { return false; } return !LAVA_ERROR_CHECK(m_rprFb->GetInfo(LAVA_FRAMEBUFFER_DATA, size, dstBuffer, nullptr), "Failed to get framebuffer data"); } size_t HdRprApiFramebuffer::GetSize() const { return m_width * m_height * kNumChannels * sizeof(float); } rpr::FramebufferDesc HdRprApiFramebuffer::GetDesc() const { rpr::FramebufferDesc desc = {}; desc.fb_width = m_width; desc.fb_height = m_height; return desc; } void HdRprApiFramebuffer::Create(uint32_t width, uint32_t height) { if (width == 0 || height == 0) { return; } rpr::FramebufferFormat format = {}; format.num_components = kNumChannels; format.type = LAVA_COMPONENT_TYPE_FLOAT32; rpr::FramebufferDesc desc = {}; desc.fb_width = width; desc.fb_height = height; rpr::Status status; m_rprFb = m_context->CreateFrameBuffer(format, desc, &status); if (!m_rprFb) { LAVA_ERROR_CHECK_THROW(status, "Failed to create framebuffer"); } m_width = width; m_height = height; } void HdRprApiFramebuffer::Delete() { if (m_aov != kAovNone) { AttachAs(kAovNone); } if (m_rprFb) { delete m_rprFb; m_rprFb = nullptr; } } PXR_NAMESPACE_CLOSE_SCOPE
4,795
1,830
#include "_core.h" namespace autowig { typedef ::statiskit::ContinuousUnivariateConditionalDistribution class_type; class Trampoline : public class_type { public: using ::statiskit::ContinuousUnivariateConditionalDistribution::ContinuousUnivariateConditionalDistribution; typedef class ::std::unique_ptr< struct ::statiskit::UnivariateConditionalDistribution, struct ::std::default_delete< struct ::statiskit::UnivariateConditionalDistribution > > return_type_2d42bbbaff065a9cb38813f62e9dafda; virtual return_type_2d42bbbaff065a9cb38813f62e9dafda copy() const override { PYBIND11_OVERLOAD_PURE_UNIQUE_PTR(return_type_2d42bbbaff065a9cb38813f62e9dafda, class_type, copy, ); }; typedef unsigned int return_type_a19605344e725c65ab302819d1663dbe; virtual return_type_a19605344e725c65ab302819d1663dbe get_nb_parameters() const override { PYBIND11_OVERLOAD_PURE(return_type_a19605344e725c65ab302819d1663dbe, class_type, get_nb_parameters, ); }; typedef struct ::statiskit::MultivariateSampleSpace const * return_type_152a627d69cd5b35837e015943fc1e75; virtual return_type_152a627d69cd5b35837e015943fc1e75 get_explanatory_space() const override { PYBIND11_OVERLOAD_PURE(return_type_152a627d69cd5b35837e015943fc1e75, class_type, get_explanatory_space, ); }; typedef struct ::statiskit::UnivariateDistribution const * return_type_53f978a20dca5ccd9144b1aeb74559b6; typedef struct ::statiskit::MultivariateEvent const & param_53f978a20dca5ccd9144b1aeb74559b6_0_type; virtual return_type_53f978a20dca5ccd9144b1aeb74559b6 operator()(param_53f978a20dca5ccd9144b1aeb74559b6_0_type param_0) const override { PYBIND11_OVERLOAD_PURE(return_type_53f978a20dca5ccd9144b1aeb74559b6, class_type, operator(), param_0); }; }; } namespace autowig { } void wrapper_206185953d7651e78a6714d1fe602758(pybind11::module& module) { pybind11::class_<struct ::statiskit::ContinuousUnivariateConditionalDistribution, autowig::Trampoline, autowig::HolderType< struct ::statiskit::ContinuousUnivariateConditionalDistribution >::Type, struct ::statiskit::UnivariateConditionalDistribution > class_206185953d7651e78a6714d1fe602758(module, "ContinuousUnivariateConditionalDistribution", ""); }
2,308
1,010
/* * AES using AES-NI instructions * (C) 2009,2012 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <stdint.h> #include <cstring> #ifdef __x86_64 #include <wmmintrin.h> inline void load_le(uint32_t* output, const uint8_t* input, size_t count) { //Not dealing with endianness right now //std::memcpy(output, reinterpret_cast<const uint32_t*>(input), count); std::memcpy(output, input, count * sizeof(uint32_t)); } __m128i aes_128_key_expansion(__m128i key, __m128i key_with_rcon) { key_with_rcon = _mm_shuffle_epi32(key_with_rcon, _MM_SHUFFLE(3,3,3,3)); key = _mm_xor_si128(key, _mm_slli_si128(key, 4)); key = _mm_xor_si128(key, _mm_slli_si128(key, 4)); key = _mm_xor_si128(key, _mm_slli_si128(key, 4)); return _mm_xor_si128(key, key_with_rcon); } void aes_192_key_expansion(__m128i* K1, __m128i* K2, __m128i key2_with_rcon, uint32_t out[], bool last) { __m128i key1 = *K1; __m128i key2 = *K2; key2_with_rcon = _mm_shuffle_epi32(key2_with_rcon, _MM_SHUFFLE(1,1,1,1)); key1 = _mm_xor_si128(key1, _mm_slli_si128(key1, 4)); key1 = _mm_xor_si128(key1, _mm_slli_si128(key1, 4)); key1 = _mm_xor_si128(key1, _mm_slli_si128(key1, 4)); key1 = _mm_xor_si128(key1, key2_with_rcon); *K1 = key1; _mm_storeu_si128(reinterpret_cast<__m128i*>(out), key1); if(last) return; key2 = _mm_xor_si128(key2, _mm_slli_si128(key2, 4)); key2 = _mm_xor_si128(key2, _mm_shuffle_epi32(key1, _MM_SHUFFLE(3,3,3,3))); *K2 = key2; out[4] = _mm_cvtsi128_si32(key2); out[5] = _mm_cvtsi128_si32(_mm_srli_si128(key2, 4)); } /* * The second half of the AES-256 key expansion (other half same as AES-128) */ __m128i aes_256_key_expansion(__m128i key, __m128i key2) { __m128i key_with_rcon = _mm_aeskeygenassist_si128(key2, 0x00); key_with_rcon = _mm_shuffle_epi32(key_with_rcon, _MM_SHUFFLE(2,2,2,2)); key = _mm_xor_si128(key, _mm_slli_si128(key, 4)); key = _mm_xor_si128(key, _mm_slli_si128(key, 4)); key = _mm_xor_si128(key, _mm_slli_si128(key, 4)); return _mm_xor_si128(key, key_with_rcon); } #define AES_ENC_4_ROUNDS(K) \ do \ { \ B0 = _mm_aesenc_si128(B0, K); \ B1 = _mm_aesenc_si128(B1, K); \ B2 = _mm_aesenc_si128(B2, K); \ B3 = _mm_aesenc_si128(B3, K); \ } while(0) #define AES_ENC_4_LAST_ROUNDS(K) \ do \ { \ B0 = _mm_aesenclast_si128(B0, K); \ B1 = _mm_aesenclast_si128(B1, K); \ B2 = _mm_aesenclast_si128(B2, K); \ B3 = _mm_aesenclast_si128(B3, K); \ } while(0) #define AES_DEC_4_ROUNDS(K) \ do \ { \ B0 = _mm_aesdec_si128(B0, K); \ B1 = _mm_aesdec_si128(B1, K); \ B2 = _mm_aesdec_si128(B2, K); \ B3 = _mm_aesdec_si128(B3, K); \ } while(0) #define AES_DEC_4_LAST_ROUNDS(K) \ do \ { \ B0 = _mm_aesdeclast_si128(B0, K); \ B1 = _mm_aesdeclast_si128(B1, K); \ B2 = _mm_aesdeclast_si128(B2, K); \ B3 = _mm_aesdeclast_si128(B3, K); \ } while(0) /* * AES-128 Encryption */ void aesni_128_encrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t encryption_keys[44]) { const __m128i* in_mm = reinterpret_cast<const __m128i*>(in); __m128i* out_mm = reinterpret_cast<__m128i*>(out); const __m128i* key_mm = reinterpret_cast<const __m128i*>(encryption_keys); const __m128i K0 = _mm_loadu_si128(key_mm); const __m128i K1 = _mm_loadu_si128(key_mm + 1); const __m128i K2 = _mm_loadu_si128(key_mm + 2); const __m128i K3 = _mm_loadu_si128(key_mm + 3); const __m128i K4 = _mm_loadu_si128(key_mm + 4); const __m128i K5 = _mm_loadu_si128(key_mm + 5); const __m128i K6 = _mm_loadu_si128(key_mm + 6); const __m128i K7 = _mm_loadu_si128(key_mm + 7); const __m128i K8 = _mm_loadu_si128(key_mm + 8); const __m128i K9 = _mm_loadu_si128(key_mm + 9); const __m128i K10 = _mm_loadu_si128(key_mm + 10); while(blocks >= 4){ __m128i B0 = _mm_loadu_si128(in_mm + 0); __m128i B1 = _mm_loadu_si128(in_mm + 1); __m128i B2 = _mm_loadu_si128(in_mm + 2); __m128i B3 = _mm_loadu_si128(in_mm + 3); B0 = _mm_xor_si128(B0, K0); B1 = _mm_xor_si128(B1, K0); B2 = _mm_xor_si128(B2, K0); B3 = _mm_xor_si128(B3, K0); AES_ENC_4_ROUNDS(K1); AES_ENC_4_ROUNDS(K2); AES_ENC_4_ROUNDS(K3); AES_ENC_4_ROUNDS(K4); AES_ENC_4_ROUNDS(K5); AES_ENC_4_ROUNDS(K6); AES_ENC_4_ROUNDS(K7); AES_ENC_4_ROUNDS(K8); AES_ENC_4_ROUNDS(K9); AES_ENC_4_LAST_ROUNDS(K10); _mm_storeu_si128(out_mm + 0, B0); _mm_storeu_si128(out_mm + 1, B1); _mm_storeu_si128(out_mm + 2, B2); _mm_storeu_si128(out_mm + 3, B3); blocks -= 4; in_mm += 4; out_mm += 4; } for(size_t i = 0; i != blocks; ++i) { __m128i B = _mm_loadu_si128(in_mm + i); B = _mm_xor_si128(B, K0); B = _mm_aesenc_si128(B, K1); B = _mm_aesenc_si128(B, K2); B = _mm_aesenc_si128(B, K3); B = _mm_aesenc_si128(B, K4); B = _mm_aesenc_si128(B, K5); B = _mm_aesenc_si128(B, K6); B = _mm_aesenc_si128(B, K7); B = _mm_aesenc_si128(B, K8); B = _mm_aesenc_si128(B, K9); B = _mm_aesenclast_si128(B, K10); _mm_storeu_si128(out_mm + i, B); } } /* * AES-128 Decryption */ void aesni_128_decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t decryption_keys[44]) { const __m128i* in_mm = reinterpret_cast<const __m128i*>(in); __m128i* out_mm = reinterpret_cast<__m128i*>(out); const __m128i* key_mm = reinterpret_cast<const __m128i*>(decryption_keys); const __m128i K0 = _mm_loadu_si128(key_mm); const __m128i K1 = _mm_loadu_si128(key_mm + 1); const __m128i K2 = _mm_loadu_si128(key_mm + 2); const __m128i K3 = _mm_loadu_si128(key_mm + 3); const __m128i K4 = _mm_loadu_si128(key_mm + 4); const __m128i K5 = _mm_loadu_si128(key_mm + 5); const __m128i K6 = _mm_loadu_si128(key_mm + 6); const __m128i K7 = _mm_loadu_si128(key_mm + 7); const __m128i K8 = _mm_loadu_si128(key_mm + 8); const __m128i K9 = _mm_loadu_si128(key_mm + 9); const __m128i K10 = _mm_loadu_si128(key_mm + 10); while(blocks >= 4){ __m128i B0 = _mm_loadu_si128(in_mm + 0); __m128i B1 = _mm_loadu_si128(in_mm + 1); __m128i B2 = _mm_loadu_si128(in_mm + 2); __m128i B3 = _mm_loadu_si128(in_mm + 3); B0 = _mm_xor_si128(B0, K0); B1 = _mm_xor_si128(B1, K0); B2 = _mm_xor_si128(B2, K0); B3 = _mm_xor_si128(B3, K0); AES_DEC_4_ROUNDS(K1); AES_DEC_4_ROUNDS(K2); AES_DEC_4_ROUNDS(K3); AES_DEC_4_ROUNDS(K4); AES_DEC_4_ROUNDS(K5); AES_DEC_4_ROUNDS(K6); AES_DEC_4_ROUNDS(K7); AES_DEC_4_ROUNDS(K8); AES_DEC_4_ROUNDS(K9); AES_DEC_4_LAST_ROUNDS(K10); _mm_storeu_si128(out_mm + 0, B0); _mm_storeu_si128(out_mm + 1, B1); _mm_storeu_si128(out_mm + 2, B2); _mm_storeu_si128(out_mm + 3, B3); blocks -= 4; in_mm += 4; out_mm += 4; } for(size_t i = 0; i != blocks; ++i){ __m128i B = _mm_loadu_si128(in_mm + i); B = _mm_xor_si128(B, K0); B = _mm_aesdec_si128(B, K1); B = _mm_aesdec_si128(B, K2); B = _mm_aesdec_si128(B, K3); B = _mm_aesdec_si128(B, K4); B = _mm_aesdec_si128(B, K5); B = _mm_aesdec_si128(B, K6); B = _mm_aesdec_si128(B, K7); B = _mm_aesdec_si128(B, K8); B = _mm_aesdec_si128(B, K9); B = _mm_aesdeclast_si128(B, K10); _mm_storeu_si128(out_mm + i, B); } } /* * AES-128 Key Schedule */ void aesni_128_key_schedule(const uint8_t key[], uint32_t encryption_keys[44], uint32_t decryption_keys[44]) { #define AES_128_key_exp(K, RCON) \ aes_128_key_expansion(K, _mm_aeskeygenassist_si128(K, RCON)) const __m128i K0 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(key)); const __m128i K1 = AES_128_key_exp(K0, 0x01); const __m128i K2 = AES_128_key_exp(K1, 0x02); const __m128i K3 = AES_128_key_exp(K2, 0x04); const __m128i K4 = AES_128_key_exp(K3, 0x08); const __m128i K5 = AES_128_key_exp(K4, 0x10); const __m128i K6 = AES_128_key_exp(K5, 0x20); const __m128i K7 = AES_128_key_exp(K6, 0x40); const __m128i K8 = AES_128_key_exp(K7, 0x80); const __m128i K9 = AES_128_key_exp(K8, 0x1B); const __m128i K10 = AES_128_key_exp(K9, 0x36); __m128i* EK_mm = reinterpret_cast<__m128i*>(encryption_keys); _mm_storeu_si128(EK_mm , K0); _mm_storeu_si128(EK_mm + 1, K1); _mm_storeu_si128(EK_mm + 2, K2); _mm_storeu_si128(EK_mm + 3, K3); _mm_storeu_si128(EK_mm + 4, K4); _mm_storeu_si128(EK_mm + 5, K5); _mm_storeu_si128(EK_mm + 6, K6); _mm_storeu_si128(EK_mm + 7, K7); _mm_storeu_si128(EK_mm + 8, K8); _mm_storeu_si128(EK_mm + 9, K9); _mm_storeu_si128(EK_mm + 10, K10); // Now generate decryption keys __m128i* DK_mm = reinterpret_cast<__m128i*>(decryption_keys); _mm_storeu_si128(DK_mm , K10); _mm_storeu_si128(DK_mm + 1, _mm_aesimc_si128(K9)); _mm_storeu_si128(DK_mm + 2, _mm_aesimc_si128(K8)); _mm_storeu_si128(DK_mm + 3, _mm_aesimc_si128(K7)); _mm_storeu_si128(DK_mm + 4, _mm_aesimc_si128(K6)); _mm_storeu_si128(DK_mm + 5, _mm_aesimc_si128(K5)); _mm_storeu_si128(DK_mm + 6, _mm_aesimc_si128(K4)); _mm_storeu_si128(DK_mm + 7, _mm_aesimc_si128(K3)); _mm_storeu_si128(DK_mm + 8, _mm_aesimc_si128(K2)); _mm_storeu_si128(DK_mm + 9, _mm_aesimc_si128(K1)); _mm_storeu_si128(DK_mm + 10, K0); } void aesni_128_key_schedule_only_encryption(const uint8_t key[], uint32_t encryption_keys[44]) { #define AES_128_key_exp(K, RCON) \ aes_128_key_expansion(K, _mm_aeskeygenassist_si128(K, RCON)) const __m128i K0 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(key)); const __m128i K1 = AES_128_key_exp(K0, 0x01); const __m128i K2 = AES_128_key_exp(K1, 0x02); const __m128i K3 = AES_128_key_exp(K2, 0x04); const __m128i K4 = AES_128_key_exp(K3, 0x08); const __m128i K5 = AES_128_key_exp(K4, 0x10); const __m128i K6 = AES_128_key_exp(K5, 0x20); const __m128i K7 = AES_128_key_exp(K6, 0x40); const __m128i K8 = AES_128_key_exp(K7, 0x80); const __m128i K9 = AES_128_key_exp(K8, 0x1B); const __m128i K10 = AES_128_key_exp(K9, 0x36); __m128i* EK_mm = reinterpret_cast<__m128i*>(encryption_keys); _mm_storeu_si128(EK_mm , K0); _mm_storeu_si128(EK_mm + 1, K1); _mm_storeu_si128(EK_mm + 2, K2); _mm_storeu_si128(EK_mm + 3, K3); _mm_storeu_si128(EK_mm + 4, K4); _mm_storeu_si128(EK_mm + 5, K5); _mm_storeu_si128(EK_mm + 6, K6); _mm_storeu_si128(EK_mm + 7, K7); _mm_storeu_si128(EK_mm + 8, K8); _mm_storeu_si128(EK_mm + 9, K9); _mm_storeu_si128(EK_mm + 10, K10); } /* * AES-192 Encryption */ void aesni_192_encrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t encryption_keys[52]) { const __m128i* in_mm = reinterpret_cast<const __m128i*>(in); __m128i* out_mm = reinterpret_cast<__m128i*>(out); const __m128i* key_mm = reinterpret_cast<const __m128i*>(encryption_keys); const __m128i K0 = _mm_loadu_si128(key_mm); const __m128i K1 = _mm_loadu_si128(key_mm + 1); const __m128i K2 = _mm_loadu_si128(key_mm + 2); const __m128i K3 = _mm_loadu_si128(key_mm + 3); const __m128i K4 = _mm_loadu_si128(key_mm + 4); const __m128i K5 = _mm_loadu_si128(key_mm + 5); const __m128i K6 = _mm_loadu_si128(key_mm + 6); const __m128i K7 = _mm_loadu_si128(key_mm + 7); const __m128i K8 = _mm_loadu_si128(key_mm + 8); const __m128i K9 = _mm_loadu_si128(key_mm + 9); const __m128i K10 = _mm_loadu_si128(key_mm + 10); const __m128i K11 = _mm_loadu_si128(key_mm + 11); const __m128i K12 = _mm_loadu_si128(key_mm + 12); while(blocks >= 4) { __m128i B0 = _mm_loadu_si128(in_mm + 0); __m128i B1 = _mm_loadu_si128(in_mm + 1); __m128i B2 = _mm_loadu_si128(in_mm + 2); __m128i B3 = _mm_loadu_si128(in_mm + 3); B0 = _mm_xor_si128(B0, K0); B1 = _mm_xor_si128(B1, K0); B2 = _mm_xor_si128(B2, K0); B3 = _mm_xor_si128(B3, K0); AES_ENC_4_ROUNDS(K1); AES_ENC_4_ROUNDS(K2); AES_ENC_4_ROUNDS(K3); AES_ENC_4_ROUNDS(K4); AES_ENC_4_ROUNDS(K5); AES_ENC_4_ROUNDS(K6); AES_ENC_4_ROUNDS(K7); AES_ENC_4_ROUNDS(K8); AES_ENC_4_ROUNDS(K9); AES_ENC_4_ROUNDS(K10); AES_ENC_4_ROUNDS(K11); AES_ENC_4_LAST_ROUNDS(K12); _mm_storeu_si128(out_mm + 0, B0); _mm_storeu_si128(out_mm + 1, B1); _mm_storeu_si128(out_mm + 2, B2); _mm_storeu_si128(out_mm + 3, B3); blocks -= 4; in_mm += 4; out_mm += 4; } for(size_t i = 0; i != blocks; ++i) { __m128i B = _mm_loadu_si128(in_mm + i); B = _mm_xor_si128(B, K0); B = _mm_aesenc_si128(B, K1); B = _mm_aesenc_si128(B, K2); B = _mm_aesenc_si128(B, K3); B = _mm_aesenc_si128(B, K4); B = _mm_aesenc_si128(B, K5); B = _mm_aesenc_si128(B, K6); B = _mm_aesenc_si128(B, K7); B = _mm_aesenc_si128(B, K8); B = _mm_aesenc_si128(B, K9); B = _mm_aesenc_si128(B, K10); B = _mm_aesenc_si128(B, K11); B = _mm_aesenclast_si128(B, K12); _mm_storeu_si128(out_mm + i, B); } } /* * AES-192 Decryption */ void aesni_192_decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t decryption_keys[52]) { const __m128i* in_mm = reinterpret_cast<const __m128i*>(in); __m128i* out_mm = reinterpret_cast<__m128i*>(out); const __m128i* key_mm = reinterpret_cast<const __m128i*>(decryption_keys); const __m128i K0 = _mm_loadu_si128(key_mm); const __m128i K1 = _mm_loadu_si128(key_mm + 1); const __m128i K2 = _mm_loadu_si128(key_mm + 2); const __m128i K3 = _mm_loadu_si128(key_mm + 3); const __m128i K4 = _mm_loadu_si128(key_mm + 4); const __m128i K5 = _mm_loadu_si128(key_mm + 5); const __m128i K6 = _mm_loadu_si128(key_mm + 6); const __m128i K7 = _mm_loadu_si128(key_mm + 7); const __m128i K8 = _mm_loadu_si128(key_mm + 8); const __m128i K9 = _mm_loadu_si128(key_mm + 9); const __m128i K10 = _mm_loadu_si128(key_mm + 10); const __m128i K11 = _mm_loadu_si128(key_mm + 11); const __m128i K12 = _mm_loadu_si128(key_mm + 12); while(blocks >= 4) { __m128i B0 = _mm_loadu_si128(in_mm + 0); __m128i B1 = _mm_loadu_si128(in_mm + 1); __m128i B2 = _mm_loadu_si128(in_mm + 2); __m128i B3 = _mm_loadu_si128(in_mm + 3); B0 = _mm_xor_si128(B0, K0); B1 = _mm_xor_si128(B1, K0); B2 = _mm_xor_si128(B2, K0); B3 = _mm_xor_si128(B3, K0); AES_DEC_4_ROUNDS(K1); AES_DEC_4_ROUNDS(K2); AES_DEC_4_ROUNDS(K3); AES_DEC_4_ROUNDS(K4); AES_DEC_4_ROUNDS(K5); AES_DEC_4_ROUNDS(K6); AES_DEC_4_ROUNDS(K7); AES_DEC_4_ROUNDS(K8); AES_DEC_4_ROUNDS(K9); AES_DEC_4_ROUNDS(K10); AES_DEC_4_ROUNDS(K11); AES_DEC_4_LAST_ROUNDS(K12); _mm_storeu_si128(out_mm + 0, B0); _mm_storeu_si128(out_mm + 1, B1); _mm_storeu_si128(out_mm + 2, B2); _mm_storeu_si128(out_mm + 3, B3); blocks -= 4; in_mm += 4; out_mm += 4; } for(size_t i = 0; i != blocks; ++i) { __m128i B = _mm_loadu_si128(in_mm + i); B = _mm_xor_si128(B, K0); B = _mm_aesdec_si128(B, K1); B = _mm_aesdec_si128(B, K2); B = _mm_aesdec_si128(B, K3); B = _mm_aesdec_si128(B, K4); B = _mm_aesdec_si128(B, K5); B = _mm_aesdec_si128(B, K6); B = _mm_aesdec_si128(B, K7); B = _mm_aesdec_si128(B, K8); B = _mm_aesdec_si128(B, K9); B = _mm_aesdec_si128(B, K10); B = _mm_aesdec_si128(B, K11); B = _mm_aesdeclast_si128(B, K12); _mm_storeu_si128(out_mm + i, B); } } /* * AES-192 Key Schedule */ void aesni_192_key_schedule(const uint8_t input_key[], uint32_t encryption_keys[52], uint32_t decryption_keys[52]) { __m128i K0 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(input_key)); __m128i K1 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(input_key + 8)); K1 = _mm_srli_si128(K1, 8); load_le(encryption_keys, input_key, 6); #define AES_192_key_exp(RCON, EK_OFF) \ aes_192_key_expansion(&K0, &K1, \ _mm_aeskeygenassist_si128(K1, RCON), \ (uint32_t*)(&encryption_keys[EK_OFF]), EK_OFF == 48) AES_192_key_exp(0x01, 6); AES_192_key_exp(0x02, 12); AES_192_key_exp(0x04, 18); AES_192_key_exp(0x08, 24); AES_192_key_exp(0x10, 30); AES_192_key_exp(0x20, 36); AES_192_key_exp(0x40, 42); AES_192_key_exp(0x80, 48); #undef AES_192_key_exp // Now generate decryption keys const __m128i* EK_mm = reinterpret_cast<const __m128i*>(encryption_keys); __m128i* DK_mm = reinterpret_cast<__m128i*>(decryption_keys); _mm_storeu_si128(DK_mm , _mm_loadu_si128(EK_mm + 12)); _mm_storeu_si128(DK_mm + 1, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 11))); _mm_storeu_si128(DK_mm + 2, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 10))); _mm_storeu_si128(DK_mm + 3, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 9))); _mm_storeu_si128(DK_mm + 4, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 8))); _mm_storeu_si128(DK_mm + 5, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 7))); _mm_storeu_si128(DK_mm + 6, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 6))); _mm_storeu_si128(DK_mm + 7, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 5))); _mm_storeu_si128(DK_mm + 8, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 4))); _mm_storeu_si128(DK_mm + 9, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 3))); _mm_storeu_si128(DK_mm + 10, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 2))); _mm_storeu_si128(DK_mm + 11, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 1))); _mm_storeu_si128(DK_mm + 12, _mm_loadu_si128(EK_mm + 0)); } void aesni_192_key_schedule_only_encryption(const uint8_t input_key[], uint32_t encryption_keys[52]) { __m128i K0 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(input_key)); __m128i K1 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(input_key + 8)); K1 = _mm_srli_si128(K1, 8); load_le(encryption_keys, input_key, 6); #define AES_192_key_exp(RCON, EK_OFF) \ aes_192_key_expansion(&K0, &K1, \ _mm_aeskeygenassist_si128(K1, RCON), \ (uint32_t*)(&encryption_keys[EK_OFF]), EK_OFF == 48) AES_192_key_exp(0x01, 6); AES_192_key_exp(0x02, 12); AES_192_key_exp(0x04, 18); AES_192_key_exp(0x08, 24); AES_192_key_exp(0x10, 30); AES_192_key_exp(0x20, 36); AES_192_key_exp(0x40, 42); AES_192_key_exp(0x80, 48); #undef AES_192_key_exp } /* * AES-256 Encryption */ void aesni_256_encrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t encryption_keys[60]) { const __m128i* in_mm = reinterpret_cast<const __m128i*>(in); __m128i* out_mm = reinterpret_cast<__m128i*>(out); const __m128i* key_mm = reinterpret_cast<const __m128i*>(encryption_keys); const __m128i K0 = _mm_loadu_si128(key_mm); const __m128i K1 = _mm_loadu_si128(key_mm + 1); const __m128i K2 = _mm_loadu_si128(key_mm + 2); const __m128i K3 = _mm_loadu_si128(key_mm + 3); const __m128i K4 = _mm_loadu_si128(key_mm + 4); const __m128i K5 = _mm_loadu_si128(key_mm + 5); const __m128i K6 = _mm_loadu_si128(key_mm + 6); const __m128i K7 = _mm_loadu_si128(key_mm + 7); const __m128i K8 = _mm_loadu_si128(key_mm + 8); const __m128i K9 = _mm_loadu_si128(key_mm + 9); const __m128i K10 = _mm_loadu_si128(key_mm + 10); const __m128i K11 = _mm_loadu_si128(key_mm + 11); const __m128i K12 = _mm_loadu_si128(key_mm + 12); const __m128i K13 = _mm_loadu_si128(key_mm + 13); const __m128i K14 = _mm_loadu_si128(key_mm + 14); while(blocks >= 4) { __m128i B0 = _mm_loadu_si128(in_mm + 0); __m128i B1 = _mm_loadu_si128(in_mm + 1); __m128i B2 = _mm_loadu_si128(in_mm + 2); __m128i B3 = _mm_loadu_si128(in_mm + 3); B0 = _mm_xor_si128(B0, K0); B1 = _mm_xor_si128(B1, K0); B2 = _mm_xor_si128(B2, K0); B3 = _mm_xor_si128(B3, K0); AES_ENC_4_ROUNDS(K1); AES_ENC_4_ROUNDS(K2); AES_ENC_4_ROUNDS(K3); AES_ENC_4_ROUNDS(K4); AES_ENC_4_ROUNDS(K5); AES_ENC_4_ROUNDS(K6); AES_ENC_4_ROUNDS(K7); AES_ENC_4_ROUNDS(K8); AES_ENC_4_ROUNDS(K9); AES_ENC_4_ROUNDS(K10); AES_ENC_4_ROUNDS(K11); AES_ENC_4_ROUNDS(K12); AES_ENC_4_ROUNDS(K13); AES_ENC_4_LAST_ROUNDS(K14); _mm_storeu_si128(out_mm + 0, B0); _mm_storeu_si128(out_mm + 1, B1); _mm_storeu_si128(out_mm + 2, B2); _mm_storeu_si128(out_mm + 3, B3); blocks -= 4; in_mm += 4; out_mm += 4; } for(size_t i = 0; i != blocks; ++i) { __m128i B = _mm_loadu_si128(in_mm + i); B = _mm_xor_si128(B, K0); B = _mm_aesenc_si128(B, K1); B = _mm_aesenc_si128(B, K2); B = _mm_aesenc_si128(B, K3); B = _mm_aesenc_si128(B, K4); B = _mm_aesenc_si128(B, K5); B = _mm_aesenc_si128(B, K6); B = _mm_aesenc_si128(B, K7); B = _mm_aesenc_si128(B, K8); B = _mm_aesenc_si128(B, K9); B = _mm_aesenc_si128(B, K10); B = _mm_aesenc_si128(B, K11); B = _mm_aesenc_si128(B, K12); B = _mm_aesenc_si128(B, K13); B = _mm_aesenclast_si128(B, K14); _mm_storeu_si128(out_mm + i, B); } } /* * AES-256 Decryption */ void aesni_256_decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t decryption_keys[60]) { const __m128i* in_mm = reinterpret_cast<const __m128i*>(in); __m128i* out_mm = reinterpret_cast<__m128i*>(out); const __m128i* key_mm = reinterpret_cast<const __m128i*>(decryption_keys); const __m128i K0 = _mm_loadu_si128(key_mm); const __m128i K1 = _mm_loadu_si128(key_mm + 1); const __m128i K2 = _mm_loadu_si128(key_mm + 2); const __m128i K3 = _mm_loadu_si128(key_mm + 3); const __m128i K4 = _mm_loadu_si128(key_mm + 4); const __m128i K5 = _mm_loadu_si128(key_mm + 5); const __m128i K6 = _mm_loadu_si128(key_mm + 6); const __m128i K7 = _mm_loadu_si128(key_mm + 7); const __m128i K8 = _mm_loadu_si128(key_mm + 8); const __m128i K9 = _mm_loadu_si128(key_mm + 9); const __m128i K10 = _mm_loadu_si128(key_mm + 10); const __m128i K11 = _mm_loadu_si128(key_mm + 11); const __m128i K12 = _mm_loadu_si128(key_mm + 12); const __m128i K13 = _mm_loadu_si128(key_mm + 13); const __m128i K14 = _mm_loadu_si128(key_mm + 14); while(blocks >= 4) { __m128i B0 = _mm_loadu_si128(in_mm + 0); __m128i B1 = _mm_loadu_si128(in_mm + 1); __m128i B2 = _mm_loadu_si128(in_mm + 2); __m128i B3 = _mm_loadu_si128(in_mm + 3); B0 = _mm_xor_si128(B0, K0); B1 = _mm_xor_si128(B1, K0); B2 = _mm_xor_si128(B2, K0); B3 = _mm_xor_si128(B3, K0); AES_DEC_4_ROUNDS(K1); AES_DEC_4_ROUNDS(K2); AES_DEC_4_ROUNDS(K3); AES_DEC_4_ROUNDS(K4); AES_DEC_4_ROUNDS(K5); AES_DEC_4_ROUNDS(K6); AES_DEC_4_ROUNDS(K7); AES_DEC_4_ROUNDS(K8); AES_DEC_4_ROUNDS(K9); AES_DEC_4_ROUNDS(K10); AES_DEC_4_ROUNDS(K11); AES_DEC_4_ROUNDS(K12); AES_DEC_4_ROUNDS(K13); AES_DEC_4_LAST_ROUNDS(K14); _mm_storeu_si128(out_mm + 0, B0); _mm_storeu_si128(out_mm + 1, B1); _mm_storeu_si128(out_mm + 2, B2); _mm_storeu_si128(out_mm + 3, B3); blocks -= 4; in_mm += 4; out_mm += 4; } for(size_t i = 0; i != blocks; ++i) { __m128i B = _mm_loadu_si128(in_mm + i); B = _mm_xor_si128(B, K0); B = _mm_aesdec_si128(B, K1); B = _mm_aesdec_si128(B, K2); B = _mm_aesdec_si128(B, K3); B = _mm_aesdec_si128(B, K4); B = _mm_aesdec_si128(B, K5); B = _mm_aesdec_si128(B, K6); B = _mm_aesdec_si128(B, K7); B = _mm_aesdec_si128(B, K8); B = _mm_aesdec_si128(B, K9); B = _mm_aesdec_si128(B, K10); B = _mm_aesdec_si128(B, K11); B = _mm_aesdec_si128(B, K12); B = _mm_aesdec_si128(B, K13); B = _mm_aesdeclast_si128(B, K14); _mm_storeu_si128(out_mm + i, B); } } /* * AES-256 Key Schedule */ void aesni_256_key_schedule(const uint8_t input_key[], uint32_t encryption_keys[60], uint32_t decryption_keys[60]) { const __m128i K0 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(input_key)); const __m128i K1 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(input_key + 16)); const __m128i K2 = aes_128_key_expansion(K0, _mm_aeskeygenassist_si128(K1, 0x01)); const __m128i K3 = aes_256_key_expansion(K1, K2); const __m128i K4 = aes_128_key_expansion(K2, _mm_aeskeygenassist_si128(K3, 0x02)); const __m128i K5 = aes_256_key_expansion(K3, K4); const __m128i K6 = aes_128_key_expansion(K4, _mm_aeskeygenassist_si128(K5, 0x04)); const __m128i K7 = aes_256_key_expansion(K5, K6); const __m128i K8 = aes_128_key_expansion(K6, _mm_aeskeygenassist_si128(K7, 0x08)); const __m128i K9 = aes_256_key_expansion(K7, K8); const __m128i K10 = aes_128_key_expansion(K8, _mm_aeskeygenassist_si128(K9, 0x10)); const __m128i K11 = aes_256_key_expansion(K9, K10); const __m128i K12 = aes_128_key_expansion(K10, _mm_aeskeygenassist_si128(K11, 0x20)); const __m128i K13 = aes_256_key_expansion(K11, K12); const __m128i K14 = aes_128_key_expansion(K12, _mm_aeskeygenassist_si128(K13, 0x40)); __m128i* EK_mm = reinterpret_cast<__m128i*>(encryption_keys); _mm_storeu_si128(EK_mm , K0); _mm_storeu_si128(EK_mm + 1, K1); _mm_storeu_si128(EK_mm + 2, K2); _mm_storeu_si128(EK_mm + 3, K3); _mm_storeu_si128(EK_mm + 4, K4); _mm_storeu_si128(EK_mm + 5, K5); _mm_storeu_si128(EK_mm + 6, K6); _mm_storeu_si128(EK_mm + 7, K7); _mm_storeu_si128(EK_mm + 8, K8); _mm_storeu_si128(EK_mm + 9, K9); _mm_storeu_si128(EK_mm + 10, K10); _mm_storeu_si128(EK_mm + 11, K11); _mm_storeu_si128(EK_mm + 12, K12); _mm_storeu_si128(EK_mm + 13, K13); _mm_storeu_si128(EK_mm + 14, K14); // Now generate decryption keys __m128i* DK_mm = reinterpret_cast<__m128i*>(decryption_keys); _mm_storeu_si128(DK_mm , K14); _mm_storeu_si128(DK_mm + 1, _mm_aesimc_si128(K13)); _mm_storeu_si128(DK_mm + 2, _mm_aesimc_si128(K12)); _mm_storeu_si128(DK_mm + 3, _mm_aesimc_si128(K11)); _mm_storeu_si128(DK_mm + 4, _mm_aesimc_si128(K10)); _mm_storeu_si128(DK_mm + 5, _mm_aesimc_si128(K9)); _mm_storeu_si128(DK_mm + 6, _mm_aesimc_si128(K8)); _mm_storeu_si128(DK_mm + 7, _mm_aesimc_si128(K7)); _mm_storeu_si128(DK_mm + 8, _mm_aesimc_si128(K6)); _mm_storeu_si128(DK_mm + 9, _mm_aesimc_si128(K5)); _mm_storeu_si128(DK_mm + 10, _mm_aesimc_si128(K4)); _mm_storeu_si128(DK_mm + 11, _mm_aesimc_si128(K3)); _mm_storeu_si128(DK_mm + 12, _mm_aesimc_si128(K2)); _mm_storeu_si128(DK_mm + 13, _mm_aesimc_si128(K1)); _mm_storeu_si128(DK_mm + 14, K0); } void aesni_256_key_schedule_only_encryption(const uint8_t input_key[], uint32_t encryption_keys[60]) { const __m128i K0 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(input_key)); const __m128i K1 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(input_key + 16)); const __m128i K2 = aes_128_key_expansion(K0, _mm_aeskeygenassist_si128(K1, 0x01)); const __m128i K3 = aes_256_key_expansion(K1, K2); const __m128i K4 = aes_128_key_expansion(K2, _mm_aeskeygenassist_si128(K3, 0x02)); const __m128i K5 = aes_256_key_expansion(K3, K4); const __m128i K6 = aes_128_key_expansion(K4, _mm_aeskeygenassist_si128(K5, 0x04)); const __m128i K7 = aes_256_key_expansion(K5, K6); const __m128i K8 = aes_128_key_expansion(K6, _mm_aeskeygenassist_si128(K7, 0x08)); const __m128i K9 = aes_256_key_expansion(K7, K8); const __m128i K10 = aes_128_key_expansion(K8, _mm_aeskeygenassist_si128(K9, 0x10)); const __m128i K11 = aes_256_key_expansion(K9, K10); const __m128i K12 = aes_128_key_expansion(K10, _mm_aeskeygenassist_si128(K11, 0x20)); const __m128i K13 = aes_256_key_expansion(K11, K12); const __m128i K14 = aes_128_key_expansion(K12, _mm_aeskeygenassist_si128(K13, 0x40)); __m128i* EK_mm = reinterpret_cast<__m128i*>(encryption_keys); _mm_storeu_si128(EK_mm , K0); _mm_storeu_si128(EK_mm + 1, K1); _mm_storeu_si128(EK_mm + 2, K2); _mm_storeu_si128(EK_mm + 3, K3); _mm_storeu_si128(EK_mm + 4, K4); _mm_storeu_si128(EK_mm + 5, K5); _mm_storeu_si128(EK_mm + 6, K6); _mm_storeu_si128(EK_mm + 7, K7); _mm_storeu_si128(EK_mm + 8, K8); _mm_storeu_si128(EK_mm + 9, K9); _mm_storeu_si128(EK_mm + 10, K10); _mm_storeu_si128(EK_mm + 11, K11); _mm_storeu_si128(EK_mm + 12, K12); _mm_storeu_si128(EK_mm + 13, K13); _mm_storeu_si128(EK_mm + 14, K14); } #undef AES_ENC_4_ROUNDS #undef AES_ENC_4_LAST_ROUNDS #undef AES_DEC_4_ROUNDS #undef AES_DEC_4_LAST_ROUNDS #else #include <arm_neon.h> inline void load_le(uint32_t* output, const uint8_t* input, size_t count) { //Not dealing with endianness right now //std::memcpy(output, reinterpret_cast<const uint32_t*>(input), count); std::memcpy(output, input, count * sizeof(uint32_t)); } uint8x16_t aeskeygenassist_si8x16(uint8x16_t a, const int rcon) { // AESE does ShiftRows and SubBytes on A uint8x16_t u8 = vaeseq_u8(a, vdupq_n_u8(0)); uint8x16_t dest = { // Undo ShiftRows step from AESE and extract X1 and X3 u8[0x4], u8[0x1], u8[0xE], u8[0xB], // SubBytes(X1) u8[0x1], u8[0xE], u8[0xB], u8[0x4], // ROT(SubBytes(X1)) u8[0xC], u8[0x9], u8[0x6], u8[0x3], // SubBytes(X3) u8[0x9], u8[0x6], u8[0x3], u8[0xC], // ROT(SubBytes(X3)) }; uint32x4_t r = {0, (unsigned) rcon, 0, (unsigned) rcon}; return veorq_u8(dest, vreinterpretq_u8_u32(r)); } uint8x16_t aes_128_key_expansion(uint8x16_t key, uint8x16_t key_with_rcon) { //_mm_shuffle_epi32_splat((a), 3); // key_with_rcon = vreinterpretq_u8_u32(vdupq_n_u32(vgetq_lane_u32(vreinterpretq_u32_u8(key_with_rcon), 3))); //vextq_s8((key, vdupq_n_u8(0), 16 - 4) key = veorq_u8(key, vextq_u8(vdupq_n_u8(0), key, 16 - 4)); key = veorq_u8(key, vextq_u8(vdupq_n_u8(0), key, 16 - 4)); key = veorq_u8(key, vextq_u8(vdupq_n_u8(0), key, 16 - 4)); return veorq_u8(key, key_with_rcon); } void aes_192_key_expansion(uint8x16_t* K1, uint8x16_t* K2, uint8x16_t key2_with_rcon, uint32_t out[], bool last) { uint8x16_t key1 = *K1; uint8x16_t key2 = *K2; key2_with_rcon = vreinterpretq_u8_u32(vdupq_n_u32(vgetq_lane_u32(vreinterpretq_u32_u8(key2_with_rcon), 1))); key1 = veorq_u8(key1, vextq_u8(vdupq_n_u8(0), key1, 16 - 4)); key1 = veorq_u8(key1, vextq_u8(vdupq_n_u8(0), key1, 16 - 4)); key1 = veorq_u8(key1, vextq_u8(vdupq_n_u8(0), key1, 16 - 4)); key1 = veorq_u8(key1, key2_with_rcon); *K1 = key1; vst1q_u8(reinterpret_cast<uint8_t*>(out), key1); if(last) return; key2 = veorq_u8(key2, vextq_u8(vdupq_n_u8(0), key2, 16 - 4)); key2 = veorq_u8(key2, vreinterpretq_u8_u32(vdupq_n_u32(vgetq_lane_u32(vreinterpretq_u32_u8(key1), 3)))); *K2 = key2; out[4] = vgetq_lane_u32(vreinterpretq_u32_u8(key2), 0); out[5] = vgetq_lane_u32(vreinterpretq_u32_u8(vextq_u8(key2, vdupq_n_u8(0), 16 - 12)), 0); } /* * The second half of the AES-256 key expansion (other half same as AES-128) */ uint8x16_t aes_256_key_expansion(uint8x16_t key, uint8x16_t key2) { uint8x16_t key_with_rcon = aeskeygenassist_si8x16(key2, 0x00); key_with_rcon = vreinterpretq_u8_u32(vdupq_n_u32(vgetq_lane_u32(vreinterpretq_u32_u8(key_with_rcon), 2))); key = veorq_u8(key, vextq_u8(vdupq_n_u8(0), key, 16 - 4)); key = veorq_u8(key, vextq_u8(vdupq_n_u8(0), key, 16 - 4)); key = veorq_u8(key, vextq_u8(vdupq_n_u8(0), key, 16 - 4)); return veorq_u8(key, key_with_rcon); } #define AES_ENC_4_ROUNDS(K) \ do \ { \ B0 = vaesmcq_u8(vaeseq_u8(B0, K)); \ B1 = vaesmcq_u8(vaeseq_u8(B1, K)); \ B2 = vaesmcq_u8(vaeseq_u8(B2, K)); \ B3 = vaesmcq_u8(vaeseq_u8(B3, K)); \ } while(0) #define AES_ENC_4_LAST_ROUNDS(K, K2) \ do \ { \ B0 = veorq_u8(vaeseq_u8(B0, K), K2); \ B1 = veorq_u8(vaeseq_u8(B1, K), K2); \ B2 = veorq_u8(vaeseq_u8(B2, K), K2); \ B3 = veorq_u8(vaeseq_u8(B3, K), K2); \ } while(0) #define AES_DEC_4_ROUNDS(K) \ do \ { \ B0 = vaesimcq_u8(vaesdq_u8(B0, K)); \ B1 = vaesimcq_u8(vaesdq_u8(B1, K)); \ B2 = vaesimcq_u8(vaesdq_u8(B2, K)); \ B3 = vaesimcq_u8(vaesdq_u8(B3, K)); \ } while(0) #define AES_DEC_4_LAST_ROUNDS(K, K2) \ do \ { \ B0 = veorq_u8(vaesdq_u8(B0, K), K2); \ B1 = veorq_u8(vaesdq_u8(B1, K), K2); \ B2 = veorq_u8(vaesdq_u8(B2, K), K2); \ B3 = veorq_u8(vaesdq_u8(B3, K), K2); \ } while(0) /* * AES-128 Encryption */ void aesni_128_encrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t encryption_keys[44]) { const uint8_t *skey = reinterpret_cast<const uint8_t*>(encryption_keys); const uint8x16_t K0 = vld1q_u8(skey + 0*16); const uint8x16_t K1 = vld1q_u8(skey + 1*16); const uint8x16_t K2 = vld1q_u8(skey + 2*16); const uint8x16_t K3 = vld1q_u8(skey + 3*16); const uint8x16_t K4 = vld1q_u8(skey + 4*16); const uint8x16_t K5 = vld1q_u8(skey + 5*16); const uint8x16_t K6 = vld1q_u8(skey + 6*16); const uint8x16_t K7 = vld1q_u8(skey + 7*16); const uint8x16_t K8 = vld1q_u8(skey + 8*16); const uint8x16_t K9 = vld1q_u8(skey + 9*16); const uint8x16_t K10 = vld1q_u8(skey + 10*16); while(blocks >= 4){ uint8x16_t B0 = vld1q_u8(in); uint8x16_t B1 = vld1q_u8(in+16); uint8x16_t B2 = vld1q_u8(in+32); uint8x16_t B3 = vld1q_u8(in+48); AES_ENC_4_ROUNDS(K0); AES_ENC_4_ROUNDS(K1); AES_ENC_4_ROUNDS(K2); AES_ENC_4_ROUNDS(K3); AES_ENC_4_ROUNDS(K4); AES_ENC_4_ROUNDS(K5); AES_ENC_4_ROUNDS(K6); AES_ENC_4_ROUNDS(K7); AES_ENC_4_ROUNDS(K8); AES_ENC_4_LAST_ROUNDS(K9, K10); vst1q_u8(out, B0); vst1q_u8(out+16, B1); vst1q_u8(out+32, B2); vst1q_u8(out+48, B3); in += 16*4; out += 16*4; blocks -= 4; } for(size_t i = 0; i != blocks; ++i) { uint8x16_t B = vld1q_u8(in+16*i); B = vaesmcq_u8(vaeseq_u8(B, K0)); B = vaesmcq_u8(vaeseq_u8(B, K1)); B = vaesmcq_u8(vaeseq_u8(B, K2)); B = vaesmcq_u8(vaeseq_u8(B, K3)); B = vaesmcq_u8(vaeseq_u8(B, K4)); B = vaesmcq_u8(vaeseq_u8(B, K5)); B = vaesmcq_u8(vaeseq_u8(B, K6)); B = vaesmcq_u8(vaeseq_u8(B, K7)); B = vaesmcq_u8(vaeseq_u8(B, K8)); B = veorq_u8(vaeseq_u8(B, K9), K10); vst1q_u8(out+16*i, B); } } /* * AES-128 Decryption */ void aesni_128_decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t decryption_keys[44]) { const uint8_t *skey = reinterpret_cast<const uint8_t*>(decryption_keys); const uint8x16_t K0 = vld1q_u8(skey + 0*16); const uint8x16_t K1 = vld1q_u8(skey + 1*16); const uint8x16_t K2 = vld1q_u8(skey + 2*16); const uint8x16_t K3 = vld1q_u8(skey + 3*16); const uint8x16_t K4 = vld1q_u8(skey + 4*16); const uint8x16_t K5 = vld1q_u8(skey + 5*16); const uint8x16_t K6 = vld1q_u8(skey + 6*16); const uint8x16_t K7 = vld1q_u8(skey + 7*16); const uint8x16_t K8 = vld1q_u8(skey + 8*16); const uint8x16_t K9 = vld1q_u8(skey + 9*16); const uint8x16_t K10 = vld1q_u8(skey + 10*16); while(blocks >= 4){ uint8x16_t B0 = vld1q_u8(in); uint8x16_t B1 = vld1q_u8(in+16); uint8x16_t B2 = vld1q_u8(in+32); uint8x16_t B3 = vld1q_u8(in+48); AES_DEC_4_ROUNDS(K0); AES_DEC_4_ROUNDS(K1); AES_DEC_4_ROUNDS(K2); AES_DEC_4_ROUNDS(K3); AES_DEC_4_ROUNDS(K4); AES_DEC_4_ROUNDS(K5); AES_DEC_4_ROUNDS(K6); AES_DEC_4_ROUNDS(K7); AES_DEC_4_ROUNDS(K8); AES_DEC_4_LAST_ROUNDS(K9, K10); vst1q_u8(out, B0); vst1q_u8(out+16, B1); vst1q_u8(out+32, B2); vst1q_u8(out+48, B3); in += 16*4; out += 16*4; blocks -= 4; } for(size_t i = 0; i != blocks; ++i){ uint8x16_t B = vld1q_u8(in+16*i); B = vaesimcq_u8(vaesdq_u8(B, K0)); B = vaesimcq_u8(vaesdq_u8(B, K1)); B = vaesimcq_u8(vaesdq_u8(B, K2)); B = vaesimcq_u8(vaesdq_u8(B, K3)); B = vaesimcq_u8(vaesdq_u8(B, K4)); B = vaesimcq_u8(vaesdq_u8(B, K5)); B = vaesimcq_u8(vaesdq_u8(B, K6)); B = vaesimcq_u8(vaesdq_u8(B, K7)); B = vaesimcq_u8(vaesdq_u8(B, K8)); B = veorq_u8(vaesdq_u8(B, K9), K10); vst1q_u8(out+16*i, B); } } /* * AES-128 Key Schedule */ void aesni_128_key_schedule(const uint8_t key[], uint32_t encryption_keys[44], uint32_t decryption_keys[44]) { #define AES_128_key_exp(K, RCON) \ aes_128_key_expansion(K, aeskeygenassist_si8x16(K, RCON)) const uint8x16_t K0 = vld1q_u8(key); const uint8x16_t K1 = AES_128_key_exp(K0, 0x01); const uint8x16_t K2 = AES_128_key_exp(K1, 0x02); const uint8x16_t K3 = AES_128_key_exp(K2, 0x04); const uint8x16_t K4 = AES_128_key_exp(K3, 0x08); const uint8x16_t K5 = AES_128_key_exp(K4, 0x10); const uint8x16_t K6 = AES_128_key_exp(K5, 0x20); const uint8x16_t K7 = AES_128_key_exp(K6, 0x40); const uint8x16_t K8 = AES_128_key_exp(K7, 0x80); const uint8x16_t K9 = AES_128_key_exp(K8, 0x1B); const uint8x16_t K10 = AES_128_key_exp(K9, 0x36); uint8x16_t* EK_mm = reinterpret_cast<uint8x16_t*>(encryption_keys); EK_mm[0] = K0; EK_mm[1] = K1; EK_mm[2] = K2; EK_mm[3] = K3; EK_mm[4] = K4; EK_mm[5] = K5; EK_mm[6] = K6; EK_mm[7] = K7; EK_mm[8] = K8; EK_mm[9] = K9; EK_mm[10] = K10; // Now generate decryption keys uint8x16_t* DK_mm = reinterpret_cast<uint8x16_t*>(decryption_keys); DK_mm[0] = K10; DK_mm[1] = vaesimcq_u8(K9); DK_mm[2] = vaesimcq_u8(K8); DK_mm[3] = vaesimcq_u8(K7); DK_mm[4] = vaesimcq_u8(K6); DK_mm[5] = vaesimcq_u8(K5); DK_mm[6] = vaesimcq_u8(K4); DK_mm[7] = vaesimcq_u8(K3); DK_mm[8] = vaesimcq_u8(K2); DK_mm[9] = vaesimcq_u8(K1); DK_mm[10] = K0; } void aesni_128_key_schedule_only_encryption(const uint8_t key[], uint32_t encryption_keys[44]) { #define AES_128_key_exp(K, RCON) \ aes_128_key_expansion(K, aeskeygenassist_si8x16(K, RCON)) const uint8x16_t K0 = vld1q_u8(key); const uint8x16_t K1 = AES_128_key_exp(K0, 0x01); const uint8x16_t K2 = AES_128_key_exp(K1, 0x02); const uint8x16_t K3 = AES_128_key_exp(K2, 0x04); const uint8x16_t K4 = AES_128_key_exp(K3, 0x08); const uint8x16_t K5 = AES_128_key_exp(K4, 0x10); const uint8x16_t K6 = AES_128_key_exp(K5, 0x20); const uint8x16_t K7 = AES_128_key_exp(K6, 0x40); const uint8x16_t K8 = AES_128_key_exp(K7, 0x80); const uint8x16_t K9 = AES_128_key_exp(K8, 0x1B); const uint8x16_t K10 = AES_128_key_exp(K9, 0x36); uint8x16_t* EK_mm = reinterpret_cast<uint8x16_t*>(encryption_keys); EK_mm[0] = K0; EK_mm[1] = K1; EK_mm[2] = K2; EK_mm[3] = K3; EK_mm[4] = K4; EK_mm[5] = K5; EK_mm[6] = K6; EK_mm[7] = K7; EK_mm[8] = K8; EK_mm[9] = K9; EK_mm[10] = K10; } /* * AES-192 Encryption */ void aesni_192_encrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t encryption_keys[52]) { const uint8_t *skey = reinterpret_cast<const uint8_t*>(encryption_keys); const uint8x16_t K0 = vld1q_u8(skey + 0*16); const uint8x16_t K1 = vld1q_u8(skey + 1*16); const uint8x16_t K2 = vld1q_u8(skey + 2*16); const uint8x16_t K3 = vld1q_u8(skey + 3*16); const uint8x16_t K4 = vld1q_u8(skey + 4*16); const uint8x16_t K5 = vld1q_u8(skey + 5*16); const uint8x16_t K6 = vld1q_u8(skey + 6*16); const uint8x16_t K7 = vld1q_u8(skey + 7*16); const uint8x16_t K8 = vld1q_u8(skey + 8*16); const uint8x16_t K9 = vld1q_u8(skey + 9*16); const uint8x16_t K10 = vld1q_u8(skey + 10*16); const uint8x16_t K11 = vld1q_u8(skey + 11*16); const uint8x16_t K12 = vld1q_u8(skey + 12*16); while(blocks >= 4) { uint8x16_t B0 = vld1q_u8(in); uint8x16_t B1 = vld1q_u8(in+16); uint8x16_t B2 = vld1q_u8(in+32); uint8x16_t B3 = vld1q_u8(in+48); AES_ENC_4_ROUNDS(K0); AES_ENC_4_ROUNDS(K1); AES_ENC_4_ROUNDS(K2); AES_ENC_4_ROUNDS(K3); AES_ENC_4_ROUNDS(K4); AES_ENC_4_ROUNDS(K5); AES_ENC_4_ROUNDS(K6); AES_ENC_4_ROUNDS(K7); AES_ENC_4_ROUNDS(K8); AES_ENC_4_ROUNDS(K9); AES_ENC_4_ROUNDS(K10); AES_ENC_4_LAST_ROUNDS(K11, K12); vst1q_u8(out, B0); vst1q_u8(out+16, B1); vst1q_u8(out+32, B2); vst1q_u8(out+48, B3); in += 16*4; out += 16*4; blocks -= 4; } for(size_t i = 0; i != blocks; ++i) { uint8x16_t B = vld1q_u8(in+16*i); B = vaesmcq_u8(vaeseq_u8(B, K0)); B = vaesmcq_u8(vaeseq_u8(B, K1)); B = vaesmcq_u8(vaeseq_u8(B, K2)); B = vaesmcq_u8(vaeseq_u8(B, K3)); B = vaesmcq_u8(vaeseq_u8(B, K4)); B = vaesmcq_u8(vaeseq_u8(B, K5)); B = vaesmcq_u8(vaeseq_u8(B, K6)); B = vaesmcq_u8(vaeseq_u8(B, K7)); B = vaesmcq_u8(vaeseq_u8(B, K8)); B = vaesmcq_u8(vaeseq_u8(B, K9)); B = vaesmcq_u8(vaeseq_u8(B, K10)); B = veorq_u8(vaeseq_u8(B, K11), K12); vst1q_u8(out+16*i, B); } } /* * AES-192 Decryption */ void aesni_192_decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t decryption_keys[52]) { const uint8_t *skey = reinterpret_cast<const uint8_t*>(decryption_keys); const uint8x16_t K0 = vld1q_u8(skey + 0*16); const uint8x16_t K1 = vld1q_u8(skey + 1*16); const uint8x16_t K2 = vld1q_u8(skey + 2*16); const uint8x16_t K3 = vld1q_u8(skey + 3*16); const uint8x16_t K4 = vld1q_u8(skey + 4*16); const uint8x16_t K5 = vld1q_u8(skey + 5*16); const uint8x16_t K6 = vld1q_u8(skey + 6*16); const uint8x16_t K7 = vld1q_u8(skey + 7*16); const uint8x16_t K8 = vld1q_u8(skey + 8*16); const uint8x16_t K9 = vld1q_u8(skey + 9*16); const uint8x16_t K10 = vld1q_u8(skey + 10*16); const uint8x16_t K11 = vld1q_u8(skey + 11*16); const uint8x16_t K12 = vld1q_u8(skey + 12*16); while(blocks >= 4) { uint8x16_t B0 = vld1q_u8(in); uint8x16_t B1 = vld1q_u8(in+16); uint8x16_t B2 = vld1q_u8(in+32); uint8x16_t B3 = vld1q_u8(in+48); AES_DEC_4_ROUNDS(K0); AES_DEC_4_ROUNDS(K1); AES_DEC_4_ROUNDS(K2); AES_DEC_4_ROUNDS(K3); AES_DEC_4_ROUNDS(K4); AES_DEC_4_ROUNDS(K5); AES_DEC_4_ROUNDS(K6); AES_DEC_4_ROUNDS(K7); AES_DEC_4_ROUNDS(K8); AES_DEC_4_ROUNDS(K9); AES_DEC_4_ROUNDS(K10); AES_DEC_4_LAST_ROUNDS(K11, K12); vst1q_u8(out, B0); vst1q_u8(out+16, B1); vst1q_u8(out+32, B2); vst1q_u8(out+48, B3); in += 16*4; out += 16*4; blocks -= 4; } for(size_t i = 0; i != blocks; ++i) { uint8x16_t B = vld1q_u8(in+16*i); B = vaesimcq_u8(vaesdq_u8(B, K0)); B = vaesimcq_u8(vaesdq_u8(B, K1)); B = vaesimcq_u8(vaesdq_u8(B, K2)); B = vaesimcq_u8(vaesdq_u8(B, K3)); B = vaesimcq_u8(vaesdq_u8(B, K4)); B = vaesimcq_u8(vaesdq_u8(B, K5)); B = vaesimcq_u8(vaesdq_u8(B, K6)); B = vaesimcq_u8(vaesdq_u8(B, K7)); B = vaesimcq_u8(vaesdq_u8(B, K8)); B = vaesimcq_u8(vaesdq_u8(B, K9)); B = vaesimcq_u8(vaesdq_u8(B, K10)); B = veorq_u8(vaesdq_u8(B, K11), K12); vst1q_u8(out+16*i, B); } } /* * AES-192 Key Schedule */ void aesni_192_key_schedule(const uint8_t input_key[], uint32_t encryption_keys[52], uint32_t decryption_keys[52]) { uint8x16_t K0 = vld1q_u8(input_key); uint8x16_t K1 = vld1q_u8(input_key + 8); //vextq_u8 K1 = vextq_u8(K1, vdupq_n_u8(0), 16 - 8); load_le(encryption_keys, input_key, 6); #define AES_192_key_exp(RCON, EK_OFF) \ aes_192_key_expansion(&K0, &K1, \ aeskeygenassist_si8x16(K1, RCON), \ (uint32_t*)(&encryption_keys[EK_OFF]), EK_OFF == 48) AES_192_key_exp(0x01, 6); AES_192_key_exp(0x02, 12); AES_192_key_exp(0x04, 18); AES_192_key_exp(0x08, 24); AES_192_key_exp(0x10, 30); AES_192_key_exp(0x20, 36); AES_192_key_exp(0x40, 42); AES_192_key_exp(0x80, 48); #undef AES_192_key_exp // Now generate decryption keys const uint8x16_t* EK_mm = reinterpret_cast<const uint8x16_t*>(encryption_keys); uint8x16_t* DK_mm = reinterpret_cast<uint8x16_t*>(decryption_keys); DK_mm[0] = EK_mm[12]; DK_mm[1] = vaesimcq_u8(EK_mm[11]); DK_mm[2] = vaesimcq_u8(EK_mm[10]); DK_mm[3] = vaesimcq_u8(EK_mm[9]); DK_mm[4] = vaesimcq_u8(EK_mm[8]); DK_mm[5] = vaesimcq_u8(EK_mm[7]); DK_mm[6] = vaesimcq_u8(EK_mm[6]); DK_mm[7] = vaesimcq_u8(EK_mm[5]); DK_mm[8] = vaesimcq_u8(EK_mm[4]); DK_mm[9] = vaesimcq_u8(EK_mm[3]); DK_mm[10] = vaesimcq_u8(EK_mm[2]); DK_mm[11] = vaesimcq_u8(EK_mm[1]); DK_mm[12] = EK_mm[0]; } void aesni_192_key_schedule_only_encryption(const uint8_t input_key[], uint32_t encryption_keys[52]) { uint8x16_t K0 = vld1q_u8(input_key); uint8x16_t K1 = vld1q_u8(input_key + 8); K1 = vextq_u8(vdupq_n_u8(0), K1, 16 - 4); load_le(encryption_keys, input_key, 6); #define AES_192_key_exp(RCON, EK_OFF) \ aes_192_key_expansion(&K0, &K1, \ aeskeygenassist_si8x16(K1, RCON), \ (uint32_t*)(&encryption_keys[EK_OFF]), EK_OFF == 48) AES_192_key_exp(0x01, 6); AES_192_key_exp(0x02, 12); AES_192_key_exp(0x04, 18); AES_192_key_exp(0x08, 24); AES_192_key_exp(0x10, 30); AES_192_key_exp(0x20, 36); AES_192_key_exp(0x40, 42); AES_192_key_exp(0x80, 48); #undef AES_192_key_exp } /* * AES-256 Encryption */ void aesni_256_encrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t encryption_keys[60]) { const uint8_t *skey = reinterpret_cast<const uint8_t*>(encryption_keys); const uint8x16_t K0 = vld1q_u8(skey + 0*16); const uint8x16_t K1 = vld1q_u8(skey + 1*16); const uint8x16_t K2 = vld1q_u8(skey + 2*16); const uint8x16_t K3 = vld1q_u8(skey + 3*16); const uint8x16_t K4 = vld1q_u8(skey + 4*16); const uint8x16_t K5 = vld1q_u8(skey + 5*16); const uint8x16_t K6 = vld1q_u8(skey + 6*16); const uint8x16_t K7 = vld1q_u8(skey + 7*16); const uint8x16_t K8 = vld1q_u8(skey + 8*16); const uint8x16_t K9 = vld1q_u8(skey + 9*16); const uint8x16_t K10 = vld1q_u8(skey + 10*16); const uint8x16_t K11 = vld1q_u8(skey + 11*16); const uint8x16_t K12 = vld1q_u8(skey + 12*16); const uint8x16_t K13 = vld1q_u8(skey + 13*16); const uint8x16_t K14 = vld1q_u8(skey + 14*16); while(blocks >= 4) { uint8x16_t B0 = vld1q_u8(in); uint8x16_t B1 = vld1q_u8(in+16); uint8x16_t B2 = vld1q_u8(in+32); uint8x16_t B3 = vld1q_u8(in+48); AES_ENC_4_ROUNDS(K0); AES_ENC_4_ROUNDS(K1); AES_ENC_4_ROUNDS(K2); AES_ENC_4_ROUNDS(K3); AES_ENC_4_ROUNDS(K4); AES_ENC_4_ROUNDS(K5); AES_ENC_4_ROUNDS(K6); AES_ENC_4_ROUNDS(K7); AES_ENC_4_ROUNDS(K8); AES_ENC_4_ROUNDS(K9); AES_ENC_4_ROUNDS(K10); AES_ENC_4_ROUNDS(K11); AES_ENC_4_ROUNDS(K12); AES_ENC_4_LAST_ROUNDS(K13, K14); vst1q_u8(out, B0); vst1q_u8(out+16, B1); vst1q_u8(out+32, B2); vst1q_u8(out+48, B3); in += 16*4; out += 16*4; blocks -= 4; } for(size_t i = 0; i != blocks; ++i) { uint8x16_t B = vld1q_u8(in+16*i); B = vaesmcq_u8(vaeseq_u8(B, K0)); B = vaesmcq_u8(vaeseq_u8(B, K1)); B = vaesmcq_u8(vaeseq_u8(B, K2)); B = vaesmcq_u8(vaeseq_u8(B, K3)); B = vaesmcq_u8(vaeseq_u8(B, K4)); B = vaesmcq_u8(vaeseq_u8(B, K5)); B = vaesmcq_u8(vaeseq_u8(B, K6)); B = vaesmcq_u8(vaeseq_u8(B, K7)); B = vaesmcq_u8(vaeseq_u8(B, K8)); B = vaesmcq_u8(vaeseq_u8(B, K9)); B = vaesmcq_u8(vaeseq_u8(B, K10)); B = vaesmcq_u8(vaeseq_u8(B, K11)); B = vaesmcq_u8(vaeseq_u8(B, K12)); B = veorq_u8(vaeseq_u8(B, K13), K14); vst1q_u8(out+16*i, B); } } /* * AES-256 Decryption */ void aesni_256_decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t decryption_keys[60]) { const uint8_t *skey = reinterpret_cast<const uint8_t*>(decryption_keys); const uint8x16_t K0 = vld1q_u8(skey + 0*16); const uint8x16_t K1 = vld1q_u8(skey + 1*16); const uint8x16_t K2 = vld1q_u8(skey + 2*16); const uint8x16_t K3 = vld1q_u8(skey + 3*16); const uint8x16_t K4 = vld1q_u8(skey + 4*16); const uint8x16_t K5 = vld1q_u8(skey + 5*16); const uint8x16_t K6 = vld1q_u8(skey + 6*16); const uint8x16_t K7 = vld1q_u8(skey + 7*16); const uint8x16_t K8 = vld1q_u8(skey + 8*16); const uint8x16_t K9 = vld1q_u8(skey + 9*16); const uint8x16_t K10 = vld1q_u8(skey + 10*16); const uint8x16_t K11 = vld1q_u8(skey + 11*16); const uint8x16_t K12 = vld1q_u8(skey + 12*16); const uint8x16_t K13 = vld1q_u8(skey + 13*16); const uint8x16_t K14 = vld1q_u8(skey + 14*16); while(blocks >= 4) { uint8x16_t B0 = vld1q_u8(in); uint8x16_t B1 = vld1q_u8(in+16); uint8x16_t B2 = vld1q_u8(in+32); uint8x16_t B3 = vld1q_u8(in+48); AES_DEC_4_ROUNDS(K0); AES_DEC_4_ROUNDS(K1); AES_DEC_4_ROUNDS(K2); AES_DEC_4_ROUNDS(K3); AES_DEC_4_ROUNDS(K4); AES_DEC_4_ROUNDS(K5); AES_DEC_4_ROUNDS(K6); AES_DEC_4_ROUNDS(K7); AES_DEC_4_ROUNDS(K8); AES_DEC_4_ROUNDS(K9); AES_DEC_4_ROUNDS(K10); AES_DEC_4_ROUNDS(K11); AES_DEC_4_ROUNDS(K12); AES_DEC_4_LAST_ROUNDS(K13, K14); vst1q_u8(out, B0); vst1q_u8(out+16, B1); vst1q_u8(out+32, B2); vst1q_u8(out+48, B3); in += 16*4; out += 16*4; blocks -= 4; } for(size_t i = 0; i != blocks; ++i) { uint8x16_t B = vld1q_u8(in+16*i); B = vaesimcq_u8(vaesdq_u8(B, K0)); B = vaesimcq_u8(vaesdq_u8(B, K1)); B = vaesimcq_u8(vaesdq_u8(B, K2)); B = vaesimcq_u8(vaesdq_u8(B, K3)); B = vaesimcq_u8(vaesdq_u8(B, K4)); B = vaesimcq_u8(vaesdq_u8(B, K5)); B = vaesimcq_u8(vaesdq_u8(B, K6)); B = vaesimcq_u8(vaesdq_u8(B, K7)); B = vaesimcq_u8(vaesdq_u8(B, K8)); B = vaesimcq_u8(vaesdq_u8(B, K9)); B = vaesimcq_u8(vaesdq_u8(B, K10)); B = vaesimcq_u8(vaesdq_u8(B, K11)); B = vaesimcq_u8(vaesdq_u8(B, K12)); B = veorq_u8(vaesdq_u8(B, K13), K14); vst1q_u8(out+16*i, B); } } /* * AES-256 Key Schedule */ void aesni_256_key_schedule(const uint8_t input_key[], uint32_t encryption_keys[60], uint32_t decryption_keys[60]) { const uint8x16_t K0 = vld1q_u8(input_key); const uint8x16_t K1 = vld1q_u8(input_key + 16); const uint8x16_t K2 = aes_128_key_expansion(K0, aeskeygenassist_si8x16(K1, 0x01)); const uint8x16_t K3 = aes_256_key_expansion(K1, K2); const uint8x16_t K4 = aes_128_key_expansion(K2, aeskeygenassist_si8x16(K3, 0x02)); const uint8x16_t K5 = aes_256_key_expansion(K3, K4); const uint8x16_t K6 = aes_128_key_expansion(K4, aeskeygenassist_si8x16(K5, 0x04)); const uint8x16_t K7 = aes_256_key_expansion(K5, K6); const uint8x16_t K8 = aes_128_key_expansion(K6, aeskeygenassist_si8x16(K7, 0x08)); const uint8x16_t K9 = aes_256_key_expansion(K7, K8); const uint8x16_t K10 = aes_128_key_expansion(K8, aeskeygenassist_si8x16(K9, 0x10)); const uint8x16_t K11 = aes_256_key_expansion(K9, K10); const uint8x16_t K12 = aes_128_key_expansion(K10, aeskeygenassist_si8x16(K11, 0x20)); const uint8x16_t K13 = aes_256_key_expansion(K11, K12); const uint8x16_t K14 = aes_128_key_expansion(K12, aeskeygenassist_si8x16(K13, 0x40)); uint8x16_t* EK_mm = reinterpret_cast<uint8x16_t*>(encryption_keys); EK_mm[0] = K0; EK_mm[1] = K1; EK_mm[2] = K2; EK_mm[3] = K3; EK_mm[4] = K4; EK_mm[5] = K5; EK_mm[6] = K6; EK_mm[7] = K7; EK_mm[8] = K8; EK_mm[9] = K9; EK_mm[10] = K10; EK_mm[11] = K11; EK_mm[12] = K12; EK_mm[13] = K13; EK_mm[14] = K14; // Now generate decryption keys uint8x16_t* DK_mm = reinterpret_cast<uint8x16_t*>(decryption_keys); DK_mm[0] = K14; DK_mm[1] = vaesimcq_u8(K13); DK_mm[2] = vaesimcq_u8(K12); DK_mm[3] = vaesimcq_u8(K11); DK_mm[4] = vaesimcq_u8(K10); DK_mm[5] = vaesimcq_u8(K9); DK_mm[6] = vaesimcq_u8(K8); DK_mm[7] = vaesimcq_u8(K7); DK_mm[8] = vaesimcq_u8(K6); DK_mm[9] = vaesimcq_u8(K5); DK_mm[10] = vaesimcq_u8(K4); DK_mm[11] = vaesimcq_u8(K3); DK_mm[12] = vaesimcq_u8(K2); DK_mm[13] = vaesimcq_u8(K1); DK_mm[14] = K0; } void aesni_256_key_schedule_only_encryption(const uint8_t input_key[], uint32_t encryption_keys[60]) { const uint8x16_t K0 = vld1q_u8(input_key); const uint8x16_t K1 = vld1q_u8(input_key + 16); const uint8x16_t K2 = aes_128_key_expansion(K0, aeskeygenassist_si8x16(K1, 0x01)); const uint8x16_t K3 = aes_256_key_expansion(K1, K2); const uint8x16_t K4 = aes_128_key_expansion(K2, aeskeygenassist_si8x16(K3, 0x02)); const uint8x16_t K5 = aes_256_key_expansion(K3, K4); const uint8x16_t K6 = aes_128_key_expansion(K4, aeskeygenassist_si8x16(K5, 0x04)); const uint8x16_t K7 = aes_256_key_expansion(K5, K6); const uint8x16_t K8 = aes_128_key_expansion(K6, aeskeygenassist_si8x16(K7, 0x08)); const uint8x16_t K9 = aes_256_key_expansion(K7, K8); const uint8x16_t K10 = aes_128_key_expansion(K8, aeskeygenassist_si8x16(K9, 0x10)); const uint8x16_t K11 = aes_256_key_expansion(K9, K10); const uint8x16_t K12 = aes_128_key_expansion(K10, aeskeygenassist_si8x16(K11, 0x20)); const uint8x16_t K13 = aes_256_key_expansion(K11, K12); const uint8x16_t K14 = aes_128_key_expansion(K12, aeskeygenassist_si8x16(K13, 0x40)); uint8x16_t* EK_mm = reinterpret_cast<uint8x16_t*>(encryption_keys); EK_mm[0] = K0; EK_mm[1] = K1; EK_mm[2] = K2; EK_mm[3] = K3; EK_mm[4] = K4; EK_mm[5] = K5; EK_mm[6] = K6; EK_mm[7] = K7; EK_mm[8] = K8; EK_mm[9] = K9; EK_mm[10] = K10; EK_mm[11] = K11; EK_mm[12] = K12; EK_mm[13] = K13; EK_mm[14] = K14; } #undef AES_ENC_4_ROUNDS #undef AES_ENC_4_LAST_ROUNDS #undef AES_DEC_4_ROUNDS #undef AES_DEC_4_LAST_ROUNDS #endif
53,792
33,380