text
stringlengths
8
6.88M
#include<bits/stdc++.h> using namespace std; main() { double t, radius,i,length,leftside,rightside,wide,half; while(scanf("%lf",&t)==1) { for(i=1; i<=t; i++) { scanf("%lf",&radius); length=radius*5; leftside=(length*0.45); rightside=(length*0.55); wide=(length*0.6); half=wide/2; printf("Case %.lf:\n",i); printf("-%.lf %.lf\n",leftside,half); printf("%.lf %.lf\n",rightside,half); printf("%.lf -%.lf\n",rightside,half); printf("-%.lf -%.lf\n",leftside,half); } } return 0; }
#pragma once #include "basis.hpp" #include "haar_basis.hpp" #include "hierarchical_basis.hpp" #include "orthonormal_basis.hpp" #include "three_point_basis.hpp" namespace Time { // Convenience object for constructing all the time trees. struct Bases { // The element tree. datastructures::Tree<Element1D> elem_tree; Element1D* mother_element; // The haar tree. datastructures::Tree<DiscConstantScalingFn> disc_cons_tree; datastructures::Tree<HaarWaveletFn> haar_tree; // The 3pt tree. datastructures::Tree<ContLinearScalingFn> cont_lin_tree; datastructures::Tree<ThreePointWaveletFn> three_point_tree; // The orthonormal tree. datastructures::Tree<DiscLinearScalingFn> disc_lin_tree; datastructures::Tree<OrthonormalWaveletFn> ortho_tree; // The hierarhical basisfn tree. datastructures::Tree<HierarchicalWaveletFn> hierarch_tree; Bases() : elem_tree(), mother_element(elem_tree.meta_root()->children()[0]), disc_cons_tree(mother_element), haar_tree(disc_cons_tree.meta_root()->children()[0]), cont_lin_tree(mother_element), three_point_tree(cont_lin_tree.meta_root()->children()), disc_lin_tree(mother_element), ortho_tree(disc_lin_tree.meta_root()->children()), hierarch_tree(cont_lin_tree.meta_root()->children()) {} }; } // namespace Time
/* * HttpGiftWithIdItem.h * * Created on: 2017-8-28 * Author: Alex * Email: Kingsleyyau@gmail.com */ #ifndef HTTPGIFTITEM_H_ #define HTTPGIFTITEM_H_ #include <string> using namespace std; #include <json/json/json.h> class HttpGiftWithIdItem { public: void Parse(const Json::Value& root) { if( root.isObject() ) { /* giftId */ if( root[LIVEROOM_GIFTINFO_ID].isString() ) { giftId = root[LIVEROOM_GIFTINFO_ID].asString(); } /* isShow */ if( root[LIVEROOM_GETGIFTLISTBYUSERID_ISHOW].isIntegral() ) { isShow = root[LIVEROOM_GETGIFTLISTBYUSERID_ISHOW].asInt() == 1 ? true : false; } /* isPromo */ if( root[LIVEROOM_GETGIFTLISTBYUSERID_ISPROMO].isIntegral() ) { isPromo = root[LIVEROOM_GETGIFTLISTBYUSERID_ISPROMO].asInt() == 1 ? true : false; } } } HttpGiftWithIdItem() { giftId = ""; isShow = false; isPromo = false; } virtual ~HttpGiftWithIdItem() { } /** * 礼物显示结构体 * giftId 礼物ID * isShow 是否在礼物列表显示(0:否 1:是) (不包括背包礼物列表) * isPromo 是否推荐礼物(0:否 1:是)(不包括背包礼物列表) */ string giftId; bool isShow; bool isPromo; }; typedef list<HttpGiftWithIdItem> GiftWithIdItemList; #endif /* HTTPGIFTITEM_H_ */
#include <cmath> #include <iostream> #include "predefine.h" #include "matrix_elements.h" #include "lorentz.h" #include "simpleLogger.h" /// g+g --> g+g double M2_gg2gg(const double t, void * params){ // unpacking parameters double * p = static_cast<double*>(params); double s = p[0], Temp = p[1], M2 = 0.; // Deybe mass (t-channel) double mt2 = t_channel_mD2->get_mD2(Temp); if (t>-cut*mt2) return 0; // define energy scales for each channel double Q2s = s - M2, Q2t = t, Q2u = M2 - s - t; // define coupling constant for each channel double At = alpha_s(Q2t, Temp); double result = 72.*M_PI*M_PI*At*At*(-Q2s*Q2u/Q2t/Q2t); if (result < 0.) return 0.; return result; } double dX_gg2gg_dt(const double t, void * params){ double * p = static_cast<double*>(params); double s = p[0], M2 = 0.; return M2_gg2gg(t, params)/c16pi/(std::pow(s-M2, 2)); } /// g+q --> g+q double M2_gq2gq(const double t, void * params){ // unpacking parameters double * p = static_cast<double*>(params); double s = p[0], Temp = p[1], M2 = 0.; // Deybe mass (t-channel) double mt2 = t_channel_mD2->get_mD2(Temp); if (t>-cut*mt2) return 0; // define energy scales for each channel double Q2s = s - M2, Q2t = t, Q2u = M2 - s - t; // define coupling constant for each channel double At = alpha_s(Q2t, Temp); double result = At*At*64.*M_PI*M_PI/9.*(Q2s*Q2s+Q2u*Q2u)*( 9./4./Q2t/Q2t); if (result < 0.) return 0.; return result; } double dX_gq2gq_dt(const double t, void * params){ double * p = static_cast<double*>(params); double s = p[0], M2 = 0.; return M2_gq2gq(t, params)/c16pi/(std::pow(s-M2, 2)); } /// Q+q --> Q+q double M2_Qq2Qq(const double t, void * params){ // unpacking parameters double * p = static_cast<double*>(params); double s = p[0], Temp = p[1], M2 = p[2]*p[2]; // Deybe mass (t-channel) double mt2 = t_channel_mD2->get_mD2(Temp); if (t>-cut*mt2) return 0; // define energy scales for each channel double Q2s = s - M2, Q2t = t, Q2u = M2 - s - t; double At = alpha_s(Q2t, Temp); double result = c64d9pi2*At*At*(Q2u*Q2u + Q2s*Q2s + 2.*M2*t)/Q2t/Q2t; if (result < 0.) return 0.; else return result; } double dX_Qq2Qq_dt(const double t, void * params){ double * p = static_cast<double*>(params); double s = p[0], M2 = p[2]*p[2]; return M2_Qq2Qq(t, params)/c16pi/std::pow(s-M2, 2); } double M2_Qg2Qg(const double t, void * params) { // unpacking parameters double * p = static_cast<double *>(params); double s = p[0], Temp = p[1], M2 = p[2]*p[2]; // Deybe mass (t-channel) double mt2 = t_channel_mD2->get_mD2(Temp); if (t>-cut*mt2) return 0; double Q2s = s - M2, Q2t = t, Q2u = M2 - s - t; double At = alpha_s(Q2t, Temp); double result = c16pi2*2.*At*At * Q2s*(-Q2u)/Q2t/Q2t; if (result < 0.) return 0.; else return result; } double dX_Qg2Qg_dt(const double t, void * params){ double * p = static_cast<double*>(params); double s = p[0], M2 = p[2]*p[2]; return M2_Qg2Qg(t, params)/c16pi/std::pow(s-M2, 2); } /// full Q+g --> Q+g |s+u+t channel|^2 double M2_Qg2Qg_full(const double t, void * params){ // unpacking parameters double * p = static_cast<double*>(params); double s = p[0], Temp = p[1], M2 = p[2]*p[2]; // Deybe mass (t-channel) double mt2 = t_channel_mD2->get_mD2(Temp); if (t>-cut*mt2) return 0; // define energy scales for each channel double Q2s = s - M2, Q2t = t, Q2u = M2 - s - t; // define coupling constant for each channel double At = alpha_s(Q2t, Temp), Au = alpha_s(Q2u, Temp), As = alpha_s(Q2s, Temp); double Q2s_reg = Q2s + mt2; double Q2u_reg = Q2u>0?(Q2u + mt2):(Q2u-mt2); double result = 0.0; // t*t result += 2.*At*At * Q2s*(-Q2u)/Q2t/Q2t; // s*s result += c4d9*As*As * ( Q2s*(-Q2u) + 2.*M2*(Q2s + 2.*M2) ) / std::pow(Q2s_reg, 2); // u*u result += c4d9*Au*Au * ( Q2s*(-Q2u) + 2.*M2*(Q2u + 2.*M2) ) / std::pow(Q2u_reg, 2); // s*u result += c1d9*As*Au * M2*(4.*M2 - t) / Q2s_reg / (-Q2u_reg); // t*s result += At*As * ( Q2s*(-Q2u) + M2*(Q2s - Q2u) ) / Q2t / Q2s_reg; // t*u result += -At*Au * ( Q2s*(-Q2u) - M2*(Q2s - Q2u) ) / Q2t / (-Q2u_reg); if (result < 0.) return 0.; return result*c16pi2; } double dX_Qg2Qg_dt_full(const double t, void * params){ double * p = static_cast<double*>(params); double s = p[0], M2 = p[2]*p[2]; return M2_Qg2Qg_full(t, params)/c16pi/std::pow(s-M2, 2); } // for hard jet parton induced heavy flavor pair production double M2_gg2QQbar(const double t, void * params){ // unpacking parameters double * p = static_cast<double*>(params); double s = p[0], Temp = p[1], M2 = p[2]*p[2]; // Deybe mass (t-channel) double mt2 = t_channel_mD2->get_mD2(Temp); // define energy scales for each channel double S = s; double T = t - M2; double U = - S - T; // define coupling constant for each channel double As = .3;//alpha_s(S, Temp); double At = .3;//alpha_s(T, Temp); double Au = .3;//alpha_s(U, Temp); return std::pow(M_PI,2) * ( 12.*U*T/S/S*As*As + 8./3.*(U/T+T/U)*At*Au - 16./3.*M2*((2*M2+T)/T/T*At*At + (2*M2+U)/U/U*Au*Au) + 6.*(T+U)/S*As*As + 6.*M2/S*std::pow(T-U,2)/T/U*At*Au - 2./3.*M2*(S-4.*M2)/T/U*At*Au ) ; } double dX_gg2QQbar_dt(const double t, void * params){ double * p = static_cast<double*>(params); double s = p[0], M2 = p[2]*p[2]; return M2_gg2QQbar(t, params)/c16pi/std::pow(s, 2); } double M2_qqbar2QQbar(const double t, void * params){ // unpacking parameters double * p = static_cast<double*>(params); double s = p[0], Temp = p[1], M2 = p[2]*p[2]; // Deybe mass (t-channel) double mt2 = t_channel_mD2->get_mD2(Temp); // define energy scales for each channel double S = s; double T = t - M2; double U = - S - T; // define coupling constant for each channel double As = .3;//alpha_s(S, Temp); return 64./9.*std::pow(M_PI*As,2)*( T*T+U*U+2.*M2*S )/S/S; } double dX_qqbar2QQbar_dt(const double t, void * params){ double * p = static_cast<double*>(params); double s = p[0], M2 = p[2]*p[2]; return M2_qqbar2QQbar(t, params)/c16pi/std::pow(s, 2); }
// Created on: 2001-09-14 // Created by: Alexander GRIGORIEV // Copyright (c) 2001-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 _XmlMNaming_NamedShapeDriver_HeaderFile #define _XmlMNaming_NamedShapeDriver_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <BRepTools_ShapeSet.hxx> #include <XmlMDF_ADriver.hxx> #include <TDocStd_FormatVersion.hxx> #include <XmlObjMgt_RRelocationTable.hxx> #include <XmlObjMgt_SRelocationTable.hxx> #include <XmlObjMgt_Element.hxx> class Message_Messenger; class TDF_Attribute; class XmlObjMgt_Persistent; class TopTools_LocationSet; class XmlMNaming_NamedShapeDriver; DEFINE_STANDARD_HANDLE(XmlMNaming_NamedShapeDriver, XmlMDF_ADriver) class XmlMNaming_NamedShapeDriver : public XmlMDF_ADriver { public: Standard_EXPORT XmlMNaming_NamedShapeDriver(const Handle(Message_Messenger)& aMessageDriver); Standard_EXPORT virtual Handle(TDF_Attribute) NewEmpty() const Standard_OVERRIDE; Standard_EXPORT virtual Standard_Boolean Paste (const XmlObjMgt_Persistent& theSource, const Handle(TDF_Attribute)& theTarget, XmlObjMgt_RRelocationTable& theRelocTable) const Standard_OVERRIDE; Standard_EXPORT virtual void Paste (const Handle(TDF_Attribute)& theSource, XmlObjMgt_Persistent& theTarget, XmlObjMgt_SRelocationTable& theRelocTable) const Standard_OVERRIDE; //! Input the shapes from DOM element Standard_EXPORT void ReadShapeSection (const XmlObjMgt_Element& anElement, const Message_ProgressRange& theRange = Message_ProgressRange()); //! Output the shapes into DOM element Standard_EXPORT void WriteShapeSection (XmlObjMgt_Element& anElement, TDocStd_FormatVersion theStorageFormatVersion, const Message_ProgressRange& theRange = Message_ProgressRange()); //! Clear myShapeSet Standard_EXPORT void Clear(); //! get the format of topology TopTools_LocationSet& GetShapesLocations(); DEFINE_STANDARD_RTTIEXT(XmlMNaming_NamedShapeDriver,XmlMDF_ADriver) private: BRepTools_ShapeSet myShapeSet; }; #include <XmlMNaming_NamedShapeDriver.lxx> #endif // _XmlMNaming_NamedShapeDriver_HeaderFile
#include <iostream> #include <vector> #include <algorithm> using namespace std; long long n, k, a[200001], freq[200001]; vector<pair<int, int>> eleFreq; bool check(int x) { int count = 0; for (int i = 0; i <= eleFreq.size(); i++) count += eleFreq[i].first / x; if (count >= k) return true; return false; } int main() { cin >> n >> k; for (int i = 0; i < n; i++) { cin >> a[i]; freq[a[i]]++; } for (int i = 0; i < 200001; i++) { if (freq[i] != 0) eleFreq.push_back(make_pair(freq[i], i)); } sort(eleFreq.begin(), eleFreq.end(), greater<>()); int b = 0, e = n - 1, m, best = 0; while (b <= e) { m = (b + e) / 2; if (check(m)) { best = m; b = m + 1; } else e = m - 1; } int count = 0, current = 0, curIdx = 0; while(count != k) { current = eleFreq[curIdx].first / best; while(count != k && current != 0) { cout << eleFreq[curIdx].second << " "; count++; current--; } curIdx++; } }
#include "brickstest.hpp" #include <bricks/collections/autoarray.h> #include <bricks/collections/listguard.h> using namespace Bricks; using namespace Bricks::Collections; TEST(BricksCollectionsListGuardTest, Test) { ArrayGuard<int> guarded; int i; for (i = 0; i < 4; i++) guarded.AddItem(i); i = 0; int ocount = guarded.GetCount(); foreach (int num, guarded) { EXPECT_EQ(i, num); i++; guarded.AddItem(num); ocount++; guarded.RemoveItemAt(i - 1); ocount--; ocount += ocount; foreach (int subnum, guarded) guarded.AddItem(subnum); } EXPECT_EQ(4, i); EXPECT_EQ(ocount, guarded.GetCount()); } TEST(BricksCollectionsListGuardTest, ObjectTest) { Array<AutoPointer<String> > list; ListGuard<Array<AutoPointer<String> > > guarded(tempnew list); guarded.AddItem(autonew String("ohai")); guarded.AddItem(autonew String("thar")); guarded.AddItem(autonew String("sir ")); foreach (String* string, guarded) { EXPECT_EQ(4, string->GetLength()); guarded.RemoveItemAt(0); } EXPECT_EQ(0, guarded.GetCount()); } TEST(BricksCollectionsListGuardTest, ObjectAutoArrayTest) { AutoArray<String> list; ListGuard<AutoArray<String> > guarded(tempnew list); guarded.AddItem(autonew String("ohai")); guarded.AddItem(autonew String("thar")); guarded.AddItem(autonew String("sir ")); foreach (String* string, guarded) { EXPECT_EQ(4, string->GetLength()); guarded.RemoveItemAt(0); } EXPECT_EQ(0, guarded.GetCount()); } int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
#ifndef USER_INTERFACE_H #define USER_INTERFACE_H #include <QMainWindow> #include <QWidget> #include <QLabel> #include <QTimer> #include <QSlider> #include <opencv2/core/core.hpp> #include <opencv2/opencv.hpp> #include "HSVWidget.h" class CvImageViewer; class CvVideoViewer; using namespace cv; class UserInterface : public QMainWindow { Q_OBJECT public: UserInterface(QWidget *parent = 0); public slots: void refresh(); private: VideoCapture m_capture; QTimer m_timer; CvImageViewer *p_camera_viewer; CvImageViewer *p_filtered_viewer; CvImageViewer *p_eroded_viewer; HSVWidget *hsv; QSlider *p_erodeSlider; QSlider *p_dilateSlider; }; #endif
#include "GnMainPCH.h" #ifdef WIN32 GNMAIN_ENTRY void LinkError_GnMainFunc() { return; } #endif // WIN32
#pragma once #include <opencv2/opencv.hpp> #include <iostream> #include <math.h> #include<string> using namespace cv; using namespace std; //@breif generate code //@author shitaotao class QRCodeDrawer { private: string data; int currentX;//当前所需绘制矩形左上角的x坐标 int currentY;//当前所需绘制矩形左上角的y坐标 int code_pixel_col;//二维码纵向像素数 int code_pixel_row;//二维码横向像素数 int code_col;//二维码列数 int code_row;//二维码行数 int frame_wid;//边框宽度 int rect_len;//二维码中单位正方形的边长 int code_num;//根据信息长度所需二维码数量 int data_index; void draw_frame(); void set_code_num(); void draw_code(); void initial(); public: Mat code; QRCodeDrawer(); void set_data(string data); int generate_code(string file_path,int number_of_head); }; void Add_Head(string file); void Add_Tail(int number_of_head_plus_content,string file);
/* * License: * License does not expire. * Can be distributed in infinitely projects * Can be distributed and / or packaged as a code or binary product (sublicensed) * Commercial use allowed under the following conditions : * - Crediting the Author * Can modify source-code */ /* * File: VertexBufferObject.cpp * Author: Suirad <darius-suirad@gmx.de> * * Created on 14. Januar 2018, 16:36 */ #include <GL/glew.h> #include "VertexArrayObject.h" VertexArrayObject::VertexArrayObject() { glGenVertexArrays(1, &id); } void VertexArrayObject::addVertexBuffer(std::vector<float> values, int dimension, int row) { //Bind Vertex Array bind(); //Generate Vertex Buffer Id unsigned int b_id; glGenBuffers(1, &b_id); //Fill Data inside VBO glBindBuffer(GL_ARRAY_BUFFER, b_id); //Bind VBO glBufferData(GL_ARRAY_BUFFER, sizeof(float) * values.size(), &values[0], GL_STATIC_DRAW); //Fill Values into Vbo glVertexAttribPointer(row, dimension, GL_FLOAT, GL_FALSE, 0, 0); //Set Attribute Pointer to Row and Dimension glBindBuffer(GL_ARRAY_BUFFER, 0); //Unbind VBO //Unbind Vertex Array unbind(); //Add Buffer Id to VBO Ids vboIds.push_back(b_id); attribs.push_back(row); } void VertexArrayObject::addIndexBuffer(std::vector<unsigned int> indices, IndexBuffer &index) { //Bind Vertex Array bind(); //Generate Indice Vbo Id unsigned int i_id; glGenBuffers(1, &i_id); //Fill Data inside VBO glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, i_id); //Bind Vbo glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * indices.size(), &indices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //Unbind Vbo //Unbind Vertex Array unbind(); //Create and Return New IndexBuffer index.id = i_id; index.size = indices.size(); //Add Index Buffer VBO ID to Vbo Ids vboIds.push_back(i_id); } void VertexArrayObject::bind() { glBindVertexArray(id); //Enable Vertex Attributes for(int i = 0; i < attribs.size(); i++) { glEnableVertexAttribArray(attribs[i]); } } void VertexArrayObject::unbind() { //Disable Vertex Attributes for(int i = 0; i < attribs.size(); i++) { glDisableVertexAttribArray(attribs[i]); } glBindVertexArray(0); } VertexArrayObject::~VertexArrayObject() { glDeleteBuffers(vboIds.size(), &vboIds[0]); glDeleteVertexArrays(1, &id); }
#ifndef TRT_BUILDER_HPP #define TRT_BUILDER_HPP #include <string> #include <vector> #include <functional> #include <opencv2/opencv.hpp> namespace TRTBuilder { typedef std::function<void(int current, int count, cv::Mat& inputOutput)> Int8Process; void setDevice(int device_id); bool caffeToTRTFP32OrFP16( const std::string& deployFile, const std::string& modelFile, const std::vector<std::string>& outputs, unsigned int maxBatchSize, const std::string& savepath, const std::string& mode = "FP32"); //if fp16, set mode = "FP16" bool caffeToTRT_INT8( const std::string& deployFile, const std::string& modelFile, const std::vector<std::string>& outputs, unsigned int maxBatchSize, const std::string& savepath, const std::string& imageDirectory, const Int8Process& preprocess); bool onnxToTRTFP32OrFP16( const std::string& modelFile, unsigned int maxBatchSize, const std::string& savepath, const std::string& mode = "FP32"); }; #endif //TRT_BUILDER_HPP
#include "../render.hpp" namespace svg { void hypothetical(Graph const &, typename Graph::vertex_descriptor root, std::stringstream & ss); }
#ifndef DIALOG_H #define DIALOG_H #include <QDialog> #include <QPainter> //painter #include <QKeyEvent> #include "draw.h" namespace Ui { class Dialog; } class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = 0); ~Dialog(); //-------------------------------------- void paintEvent(QPaintEvent*); void connectWithGame(GameManager *g); void keyPressEvent(QKeyEvent *event); private: GameManager *game; Draw *draw; Ui::Dialog *ui; int fps; }; #endif // DIALOG_H
//-------------------------------------------------------- // musket/include/musket/widget/scroll_bar.hpp // // Copyright (C) 2018 LNSEAB // // released under the MIT License. // https://opensource.org/licenses/MIT //-------------------------------------------------------- #ifndef MUSKET_WIDGET_SCROLL_BAR_HPP_ #define MUSKET_WIDGET_SCROLL_BAR_HPP_ #include "facade.hpp" #include "../widget.hpp" #include "button.hpp" namespace musket { namespace scroll_bar_event { struct scroll { template <typename> using type = void (std::uint32_t, std::uint32_t); }; } // namespace scroll_bar_event using scroll_bar_events = events_holder< scroll_bar_event::scroll >; struct scroll_bar_style { std::optional< rgba_color_t > bg_color; std::optional< edge_property > edge; float min_thumb_size; }; struct scroll_bar_thumb_style { std::optional< rgba_color_t > fg_color; std::optional< edge_property > edge; }; enum struct scroll_bar_thumb_state : std::uint8_t { idle, over, pressed, }; template <axis_flag> class scroll_bar; template <axis_flag Axis> class default_style_t< scroll_bar< Axis > > { inline static scroll_bar_style style_ = { rgba_color_t{ 0.4f, 0.4f, 0.4f, 1.0f }, {}, 10.0f }; inline static scroll_bar_thumb_style thumb_idle_ = { rgba_color_t{ 0.65f, 0.65f, 0.65f, 1.0f }, {} }; inline static scroll_bar_thumb_style thumb_over_ = { rgba_color_t{ 0.75f, 0.75f, 0.75f, 1.0f }, {} }; inline static scroll_bar_thumb_style thumb_pressed_ = { rgba_color_t{ 0.9f, 0.9f, 0.9f, 1.0f }, {} }; inline static std::mutex mtx_ = {}; public: static void set(scroll_bar_style const& style) noexcept { std::lock_guard lock{ mtx_ }; style_ = style; } static void set(scroll_bar_thumb_state state, scroll_bar_thumb_style const& style) noexcept { std::lock_guard lock{ mtx_ }; switch( state ) { case scroll_bar_thumb_state::idle: thumb_idle_ = style; break; case scroll_bar_thumb_state::over: thumb_over_ = style; break; case scroll_bar_thumb_state::pressed: thumb_pressed_ = style; break; } } static scroll_bar_style get() noexcept { std::lock_guard lock{ mtx_ }; return style_; } static scroll_bar_thumb_style get(scroll_bar_thumb_state state) noexcept { std::lock_guard lock{ mtx_ }; switch( state ) { case scroll_bar_thumb_state::idle: return thumb_idle_; case scroll_bar_thumb_state::over: return thumb_over_; case scroll_bar_thumb_state::pressed: return thumb_pressed_; } return {}; } }; struct scroll_bar_property { std::optional< scroll_bar_style > style; std::optional< scroll_bar_thumb_style > idle_style; std::optional< scroll_bar_thumb_style > over_style; std::optional< scroll_bar_thumb_style > pressed_style; }; namespace detail { template <typename Parent, axis_flag Direction> class scroll_bar_thumb : public widget_facade< scroll_bar_thumb< Parent, Direction > > { using state = scroll_bar_thumb_state; using style_data_type = style_data_t< scroll_bar_thumb_style >; using state_machine_type = state_machine< style_data_type, state, state::idle, state::over, state::pressed >; Parent* parent_; state_machine_type states_; spirea::point_t< std::int32_t > prev_pt_; connection conn_sliding_; connection conn_finish_sliding_; std::uint32_t pos_ = 0; event_handler< scroll_bar_events, Parent > handler_; public: scroll_bar_thumb( Parent* parent, spirea::rect_t< float > const& rc, scroll_bar_thumb_style const& idle_style, scroll_bar_thumb_style const& over_style, scroll_bar_thumb_style const& pressed_style ) : widget_facade< scroll_bar_thumb >{ rc }, parent_{ parent }, states_{ state::idle, style_data_type{ idle_style }, style_data_type{ over_style }, style_data_type{ pressed_style } } { } ~scroll_bar_thumb() noexcept { conn_sliding_.disconnect(); } template <typename Event, typename F> auto connect(Event, F&& f) { return handler_.connect( Event{}, std::forward< F >( f ) ); } std::uint32_t position() const noexcept { return pos_; } template <typename Object> void on_event(event::draw, Object& obj) { if( !this->is_visible() ) { return; } auto const rc = spirea::rect_traits< spirea::d2d1::rect_f >::construct( this->size() ); auto const rt = obj.render_target(); auto const& data = states_.get(); data.draw_foreground( rt, rc ); data.draw_edge( rt, rc ); } template <typename Object> void on_event(event::recreated_target, Object& obj) { for( auto& i : states_.data() ) { i.recreated_target( obj.render_target() ); } } template <typename Object> void on_event(event::mouse_button_pressed, Object& obj, mouse_button btn, mouse_button, spirea::point_t< std::int32_t > const& pt) { if( spirea::enabled( btn, mouse_button::left ) ) { states_.trasition( state::pressed ); press_left_button( obj, pt ); } } template <typename Object> void on_event(event::mouse_button_released, Object& obj, mouse_button btn, mouse_button, spirea::point_t< std::int32_t > const&) { if( spirea::enabled( btn, mouse_button::left ) ) { states_.trasition( state::over ); obj.redraw(); } } template <typename Object> void on_event(event::mouse_entered, Object& obj, mouse_button btns) { if( spirea::enabled( btns, mouse_button::left ) ) { states_.trasition( state::pressed ); } else { states_.trasition( state::over ); } obj.redraw(); } template <typename Object> void on_event(event::mouse_leaved, Object& obj, mouse_button) { if( !conn_sliding_.is_connected() ) { states_.trasition( state::idle ); } obj.redraw(); } private: template <typename Object> void press_left_button(Object& obj, spirea::point_t< std::int32_t > const& pt) { prev_pt_ = pt; conn_sliding_ = obj.connect( event::mouse_moved{}, [this](auto& obj, mouse_button, spirea::point_t< std::int32_t > const& now_pt) mutable { auto const rc = this->size(); auto const parent_rc = parent_->size(); if constexpr( Direction == axis_flag::vertical ) { auto top = rc.top + ( now_pt.y - prev_pt_.y ); if( top < parent_rc.top ) { top = parent_rc.top; } if( top + rc.height() > parent_rc.bottom ) { top = parent_rc.bottom - rc.height(); } this->resize( spirea::rect_t< float >{ { rc.left, top }, rc.area() } ); auto const prev_pos = pos_; pos_ = static_cast< std::uint32_t >( std::floor( ( top - parent_rc.top ) * ( parent_->max_value() - parent_->page_value() ) / ( parent_rc.height() - rc.height() ) ) ); if( pos_ != prev_pos ) { handler_.invoke( scroll_bar_event::scroll{}, pos_, pos_ + parent_->page_value() ); } } else { auto left = rc.left + ( now_pt.x - prev_pt_.x ); if( left < parent_rc.left ) { left = parent_rc.left; } if( left + rc.width() > parent_rc.right ) { left = parent_rc.right - rc.width(); } this->resize( spirea::rect_t< float >{ { left, rc.top }, rc.area() } ); auto const prev_pos = pos_; pos_ = static_cast< std::uint32_t >( std::floor( ( left - parent_rc.left ) * ( parent_->max_value() - parent_->page_value() ) / ( parent_rc.width() - rc.width() ) ) ); if( pos_ != prev_pos ) { handler_.invoke( scroll_bar_event::scroll{}, pos_, pos_ + parent_->page_value() ); } } obj.redraw(); prev_pt_ = now_pt; } ); conn_finish_sliding_ = obj.connect( event::mouse_button_released{}, [this](auto& obj, mouse_button btn, mouse_button, spirea::point_t< std::int32_t > const&) mutable { if( spirea::enabled( btn, mouse_button::left ) ) { states_.trasition( state::idle ); obj.redraw(); conn_sliding_.disconnect(); conn_finish_sliding_.disconnect(); } } ); obj.redraw(); } }; } // namespace detail template <axis_flag Direction> class scroll_bar : public widget_facade< scroll_bar< Direction > > { static_assert( Direction == axis_flag::vertical || Direction == axis_flag::horizontal ); using style_data_type = style_data_t< scroll_bar_style >; widget< detail::scroll_bar_thumb< scroll_bar, Direction > > thumb_; style_data_type sd_; std::uint32_t page_value_; std::uint32_t max_value_; public: template <typename Rect> scroll_bar( Rect const& rc, std::uint32_t page_v, std::uint32_t max_v, scroll_bar_property const& prop = {} ) : widget_facade< scroll_bar >{ rc }, sd_{ deref_style< scroll_bar >( prop.style ) }, page_value_{ page_v }, max_value_{ max_v } { thumb_ = { this, spirea::rect_t< float >{ { rc.left, rc.top }, get_thumb_size( sd_.get_style() ) }, deref_style< scroll_bar >( prop.idle_style, scroll_bar_thumb_state::idle ), deref_style< scroll_bar >( prop.over_style, scroll_bar_thumb_state::over ), deref_style< scroll_bar >( prop.pressed_style, scroll_bar_thumb_state::pressed ) }; } void show() noexcept { widget_facade< scroll_bar >::show(); thumb_->show(); } void hide() noexcept { widget_facade< scroll_bar >::hide(); thumb_->hide(); } template <typename Rect> void resize(Rect const& rc) noexcept { widget_facade< scroll_bar >::resize( rc ); spirea::point_t< float > pt; if constexpr( Direction == axis_flag::vertical ) { pt.x = rc.left; pt.y = rc.top + rc.height() * static_cast< float >( thumb_->position() ) / static_cast< float >( max_value() - page_value() ); } else { pt.x = rc.left + rc.width() * static_cast< float >( thumb_->position() ) / static_cast< float >( max_value() - page_value() ); pt.y = rc.top; } thumb_->resize( spirea::rect_t{ pt, get_thumb_size( sd_.get_style() ) } ); } std::uint32_t page_value() const noexcept { return page_value_; } std::uint32_t max_value() const noexcept { return max_value_; } std::uint32_t position() const noexcept { return thumb_->position(); } void set_values(std::uint32_t page_value, std::uint32_t max_value) noexcept { auto const thumb_rc = thumb_->size(); page_value_ = page_value; max_value_ = max_value; thumb_->resize( spirea::rect_t{ spirea::point_t{ thumb_rc.left, thumb_rc.top }, get_thumb_size( sd_.style ) } ); } template <typename Event, typename F> auto connect(Event, F&& f) { return thumb_->connect( Event{}, std::forward< F >( f ) ); } template <typename Object> void on_event(event::draw, Object& obj) { if( !this->is_visible() ) { return; } auto const rc = spirea::rect_traits< spirea::d2d1::rect_f >::construct( this->size() ); auto const rt = obj.render_target(); sd_.draw_background( rt, rc ); sd_.draw_edge( rt, rc ); } template <typename Object> void on_event(event::recreated_target, Object& obj) { sd_.recreated_target( obj.render_target() ); } template <typename Object> void on_event(event::attached_widget, Object& obj) { obj.attach_widget( thumb_ ); } private: spirea::area_t< float > get_thumb_size(scroll_bar_style const& style) const noexcept { spirea::area_t< float > thumb_sz = this->size().area(); if( page_value() >= max_value() ) { return thumb_sz; } if constexpr( Direction == axis_flag::vertical ) { thumb_sz.height = thumb_sz.height * page_value() / max_value(); if( thumb_sz.height <= style.min_thumb_size ) { thumb_sz.height = style.min_thumb_size; } } else { thumb_sz.width = thumb_sz.width * page_value() / max_value(); if( thumb_sz.width <= style.min_thumb_size ) { thumb_sz.width = style.min_thumb_size; } } return thumb_sz; } }; template <axis_flag Direction> using auto_scaling_scroll_bar = std::conditional_t< Direction == axis_flag::vertical, auto_relocator< auto_resizer< scroll_bar< Direction >, axis_flag::vertical >, axis_flag::horizontal >, auto_relocator< auto_resizer< scroll_bar< Direction >, axis_flag::horizontal >, axis_flag::vertical > >; } // namespace musket #endif // MUSKET_WIDGET_SCROLL_BAR_HPP_
#ifndef _IMAGELIB_H_ #define _IMAGELIB_H_ #include <opencv2/core/utility.hpp> #include <opencv2/opencv.hpp> using namespace cv; struct ImgSet { Mat InitImg; Mat GrayImg; Mat FilterImg; }; Mat GetInitImg(String filename) { Mat InitImg; InitImg = imread(filename, 1); if (InitImg.empty()) { printf("Error:load image failed."); exit(1); } return InitImg; } Mat GetGrayImg(Mat InitImg) { Mat GrayImg; cvtColor(InitImg, GrayImg, CV_BGR2GRAY); return GrayImg; } Mat GetFilterImg(Mat GrayImg) { Mat FilterImg; GaussianBlur(GrayImg, FilterImg, Size(5, 5), 0, 0); return FilterImg; } uchar* GetImgData(Mat Img) { return Img.data; } uint Getxsize(Mat Img) { return Img.cols; } uint Getysize(Mat Img) { return Img.rows; } #endif
#include <ESP8266WiFi.h> #include <WiFiUdp.h> const char *ssid = "__My_Disco__"; const char *password = "andy1996"; unsigned int localPort = 8888; // local port to listen on char packetBuffer[20]; //buffer to hold incoming packet, char ReplyBuffer[] = "ACK"; // a string to send back String data = ""; WiFiUDP Udp; void setup() { Serial.begin(74880); Serial.println(); Serial.print("Configuring access point..."); WiFi.softAP(ssid, password); IPAddress myIP = WiFi.softAPIP(); Serial.print("AP IP address: "); Serial.println(myIP); Serial.println("HTTP server started"); Udp.begin(localPort); } void loop() { int packetSize = Udp.parsePacket(); if (packetSize) { //Serial.print("port "); //Serial.println(Udp.remotePort()); // read the packet into packetBufffer Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); data = packetBuffer; clearPacketBuffer (); Serial.println(data); // send a reply, to the IP address and port that sent us the packet we received //Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); //Udp.write(ReplyBuffer); //Udp.endPacket(); } } void clearPacketBuffer () { for(int i =0;i<20;i++)packetBuffer[i]='\0'; }
/** *AUTHOR:Harsh Agrawal* *Birla Institute of Technology,Mesra* **/ #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; const int N=2e5+1; #define for0(i,e) for(ll i=0;i<e;i++) #define forx(i,x,e) for(ll i=x;i<e;i++) #define ln "\n" #define pb push_back #define in(a) cin>>a #define out(a) cout>>a; #define vll vector<ll> #define vvll vector<vll> #define qll queue<ll> #define fastIO ios_base::sync_with_stdio(0);\ cin.tie(NULL);\ cout.tie(NULL) struct cmpp { bool operator()(pair<ll,ll> a, pair<ll,ll> b){ return a.second>b.second; } }; void solve(ll s, vector<vector<pair<ll,ll>>> &adj, ll n){ //Adatrip , do it using priority queue , to avoid TLE; priority_queue<pair<ll,ll>, vector<pair<ll,ll>> , cmpp> pq; pq.push({s,0}); vector<bool> u(n,false); vll d(n,LLONG_MAX); d[s] = 0; while(!pq.empty()){ ll v = pq.top().first; pq.pop(); if(d[v]==LLONG_MAX) break; u[v] = true; for(auto edge: adj[v]){ ll len = edge.second; ll to = edge.first; if(d[v]+len < d[to] && !u[to]){ d[to] = d[v]+len; pq.push({to,d[to]}); } } } ll count = 1;ll mx = -1; for0(i,n){ if(d[i]>mx && d[i]!=LLONG_MAX){ count=1; mx = d[i]; } else if(d[i]==mx){ count++; } } cout<<mx<<" "<<count<<endl; } int main(){ fastIO; ll n,m,q; cin>>n>>m>>q; vector<vector<pair<ll,ll>>> adj(n); for0(i,m){ ll u,v,c;cin>>u>>v>>c; adj[u].pb({v,c}); adj[v].pb({u,c}); } for0(i,q){ ll x; cin>>x; solve(x,adj,n); } }
#include<bits/stdc++.h> using namespace std; int f(int a){ for(int i=0;i<32;i++)if(!((a>>i)&1))return 1<<i;//返回最后1个0,的2的次方 } int main(){ int t,n; scanf("%d",&t); while(t--){ scanf("%d",&n); if(f(n)<n)printf("0\n"); else printf("1\n"); for(int i=2;i<n;i++)printf("%d ",f(i)); if(f(n)<n)printf("%d\n",f(n)); else printf("1\n"); } }
#pragma once #include <string> // ShortForcast 对话框 class ShortForcast : public CDialog { DECLARE_DYNAMIC(ShortForcast) public: ShortForcast(CWnd* pParent = NULL); // 标准构造函数 virtual ~ShortForcast(); // 对话框数据 enum { IDD = IDD_DLG_ShortForcast }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: CString forcast_content,file_path; virtual BOOL OnInitDialog(); bool PutShortForcast(); afx_msg void OnBnClickedOk(); };
#include "Components.h" #include <list> #include <functional> #include <glm/glm.hpp> class Texture; //! The Button class. /*! By adding this Button to your object you can then add callbacks to it to run when the button is clicked. Button is a child of Component so please use the Object class to add one to an Object. Example.. shared<Button> example = exampleObject->AddComponent<Button>(); */ class Button : public Component { public: //!This function will add a callback for when the button is click /*! this function takes a function as a parameter that will be added to a list of callbacks that will be called when the button is clicked with the Mouse. */ void RegisterCallback(const std::function<void()> &_callback); //!This function will run all the callbacks you have set /*! this runs all the functions you have set on this Button This is run automataclly on the OnUpdate, but you can call it yourself */ void OnClick(); //!The OnInit function inherited from Component. /*! This is mainly called by the Object call when it's created so you don't need to use this function. */ void OnInit(std::shared_ptr<Texture> image); //!This sets the Image of the button /*! This sets the image of the button, Though you set this in when creating the button you can change it durring the game */ void SetImage(std::shared_ptr<Texture> image); //!This sets the size of the button /*! This sets the size of the button, if no size is set then the size will be that of the image you've passed in. */ void SetSize(glm::vec2 _size); //!This sets the position of the button /*! This sets the position of the button, if no position is set then the button will apear in the top left corner of the screen. */ void SetPosition(glm::vec2 _position); void SetClickedImage(std::shared_ptr<Texture> _image); private: void OnUpdate(); void OnGUI(); std::shared_ptr<Texture> normalImage; std::shared_ptr<Texture> clickedImage; std::shared_ptr<Texture> currentImage; glm::vec2 size; glm::vec2 position; std::list<std::function<void()>> callbacks; };
#ifndef __RESMANAGER_H #define __RESMANAGER_H #include "_pch.h" #define DEFINE_ICO(name,size) const wxIcon m_ico_##name##size #define LOAD_ICO(name,size,pos) m_ico_##name##size.CopyFromBitmap( wxImage( "..\\..\\RESOURCES\\"#name".ico",wxBITMAP_TYPE_ANY,##pos)) #define DEFINE_ICO_ALL(name) \ DEFINE_ICO(name,32); \ DEFINE_ICO(name,24); \ DEFINE_ICO(name,16); #define LOAD_ICO_ALL(name) \ LOAD_ICO(name,32,0); \ LOAD_ICO(name,24,1); \ LOAD_ICO(name,16,2); #define DEF_INIT_ICO(name,size) const wxIcon m_ico_##name##size = wxIcon("..\\..\\RESOURCES\\"#size"\\"#name".ico", wxBITMAP_TYPE_ANY, ##size, ##size); #define DEF_INIT_ICO16(name) DEF_INIT_ICO(name,16) #define DEF_INIT_ICO24(name) DEF_INIT_ICO(name,24) #define DEF_INIT_ICO32(name) DEF_INIT_ICO(name,32) #define DEF_INIT_ICO_ALL(name) \ DEF_INIT_ICO(name,32); \ DEF_INIT_ICO(name,24); \ DEF_INIT_ICO(name,16); class ResMgr { private: ResMgr(ResMgr const&) = delete; void operator=(ResMgr const&) = delete; public: static ResMgr* GetInstance() { static ResMgr instance; // Guaranteed to be destroyed. // Instantiated on first use. return &instance; } DEF_INIT_ICO24(acts); DEF_INIT_ICO24(rule); DEF_INIT_ICO24(folder); DEF_INIT_ICO24(folder_obj); DEF_INIT_ICO24(back); DEF_INIT_ICO24(type); DEF_INIT_ICO24(views); DEF_INIT_ICO24(obj); DEF_INIT_ICO24(move); DEF_INIT_ICO24(movehere); DEF_INIT_ICO24(add_obj_tab); DEF_INIT_ICO24(refresh); DEF_INIT_ICO24(newfolder); DEF_INIT_ICO24(edit); DEF_INIT_ICO24(plus); DEF_INIT_ICO24(delete); DEF_INIT_ICO24(filter); DEF_INIT_ICO24(addfilter); DEF_INIT_ICO24(add_type); DEF_INIT_ICO24(add_obj); DEF_INIT_ICO24(favorites); DEF_INIT_ICO24(objtype); DEF_INIT_ICO24(connect); DEF_INIT_ICO24(disconnect); DEF_INIT_ICO24(user); DEF_INIT_ICO24(usergroup); DEF_INIT_ICO24(classprop); DEF_INIT_ICO24(save); DEF_INIT_ICO24(db); DEF_INIT_ICO24(folder_type); DEF_INIT_ICO24(act); DEF_INIT_ICO24(create); DEF_INIT_ICO24(minus); DEF_INIT_ICO24(accept); DEF_INIT_ICO24(reject); DEF_INIT_ICO24(history); DEF_INIT_ICO24(options); DEF_INIT_ICO24(type_abstract); DEF_INIT_ICO24(type_num); DEF_INIT_ICO24(type_qty); DEF_INIT_ICO24(obj_num); DEF_INIT_ICO24(obj_qty); DEF_INIT_ICO24(obj_num_group); DEF_INIT_ICO24(obj_qty_group); DEF_INIT_ICO24(favprop_select); DEF_INIT_ICO24(list_prop); DEF_INIT_ICO24(report); DEF_INIT_ICO24(report_list); DEF_INIT_ICO24(export_excel); DEF_INIT_ICO24(group_by_type); DEF_INIT_ICO16(connect); DEF_INIT_ICO16(disconnect); DEF_INIT_ICO16(usergroup); DEF_INIT_ICO16(user); DEF_INIT_ICO16(list_prop); DEF_INIT_ICO16(acts); DEF_INIT_ICO16(newfolder); DEF_INIT_ICO16(sort_asc); DEF_INIT_ICO16(sort_desc); DEF_INIT_ICO16(plus); DEF_INIT_ICO16(delete); DEF_INIT_ICO16(slot_list); DEF_INIT_ICO16(save); DEF_INIT_ICO16(db); DEF_INIT_ICO16(create); DEF_INIT_ICO16(minus); DEF_INIT_ICO16(edit); DEF_INIT_ICO16(refresh); DEF_INIT_ICO16(act_previos); DEF_INIT_ICO16(act_period); DEF_INIT_ICO16(act_next); DEF_INIT_ICO16(act_left); DEF_INIT_ICO16(dir_obj); DEF_INIT_ICO16(dir_cls); DEF_INIT_ICO16(favorite); protected: ResMgr(){ } }; //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- /** Менеджер ресурсов - наследуя этот класс, потомки получают доступ к менеджеру ресурсов посредством вызова GetResMgr() или напрямую указателя m_ResMgr */ class ctrlWithResMgr { public: ResMgr* m_ResMgr; ctrlWithResMgr() { m_ResMgr = ResMgr::GetInstance(); } const ResMgr* GetResMgr()const { return m_ResMgr; } }; #endif // __RESMANAGER_H
#pragma once #include <cppunit/extensions/AutoRegisterSuite.h> namespace BeeeOn { typedef bool (*SkipTestFunc)(); template <typename Type> class SkippableAutoRegisterSuite { public: SkippableAutoRegisterSuite(SkipTestFunc skip) { if (!skip()) m_suite = new CppUnit::AutoRegisterSuite<Type>(); } ~SkippableAutoRegisterSuite() { delete m_suite; } private: CppUnit::AutoRegisterSuite<Type> *m_suite; }; #define CPPUNIT_TEST_SUITE_REGISTRATION_SKIPPABLE(Type, func) \ static BeeeOn::SkippableAutoRegisterSuite<Type> \ CPPUNIT_MAKE_UNIQUE_NAME(skippableAutoRegisterRegistry__)(func) }
/**************************************** Cat Got Bored *****************************************/ #include <bits/stdc++.h> #define loop(i,s,e) for(int i = s;i<e;i++) //excluding end point #define pb(a) push_back(a) #define sqr(x) ((x)*(x)) #define CIN ios_base::sync_with_stdio(0); cin.tie(0); #define ll long long #define ull unsigned long long #define SZ(a) int(a.size()) #define read() freopen("input.txt", "r", stdin) #define write() freopen("output.txt", "w", stdout) #define ms(a,b) memset(a, b, sizeof(a)) #define all(v) v.begin(), v.end() #define PI acos(-1.0) #define pf printf #define sfi(a) scanf("%d",&a); #define sfii(a,b) scanf("%d %d",&a,&b); #define sfl(a) scanf("%lld",&a); #define sfll(a,b) scanf("%lld %lld",&a,&b); #define mp make_pair #define paii pair<int, int> #define padd pair<dd, dd> #define pall pair<ll, ll> #define fs first #define sc second #define CASE(t) printf("Case %d: ",++t) // t initialized 0 #define INF 1000000000 //10e9 #define EPS 1e-9 using namespace std; int coins[109]; int dp[109][50009]; int m; int rec(int i,int W) { int pos1 = 0;int pos2 = 0; if(i==m) return 0; else if(W-coins[i]==0) return dp[i][W]=W; else if(dp[i][W]!=-1) return dp[i][W]; if(W-coins[i]>0) { pos1=coins[i]+rec(i+1,W-coins[i]); } pos2=rec(i+1,W); return dp[i][W]=max(pos1,pos2); } int main() { int T; cin>>T; while(T--) { ms(coins,0); ms(dp,-1); int sub_sum = 0; cin>>m; // n = m; for(int a = 0;a<m;a++) { cin>>coins[a]; sub_sum+=coins[a]; } int person1_cum_sum = coins[0]; int person2_cum_sum = coins[1]; /* if(m<=2) cout<<abs(person1_cum_sum - person2_cum_sum)<<endl; */ int mx_dividend = rec(0,sub_sum/2); cout<<sub_sum - 2*mx_dividend<<endl; } return 0; }
#include<iostream> #include<cstring> #include<vector> #include <fstream> using namespace std; int main() { /*利用循环输入文本*/ //这个代码模式适合EOF为结束的输入。具体细节,视系统而定 /*每次读取一个字符,直到遇到EOF的输入循环的基本设计如下:*/ ifstream fcin; fcin.open("test.txt",ios::in); string str; vector<char> str1; char ch; while(fcin.get(ch)) //cin会在需要bool值得地方自动转换,检测到eof,自动返回false,此外这是最通用的设计 { //str1.push_back(ch); //cin.get(ch)储存了换行 str+=ch; } //检测default位 if(fcin.fail()) //判断是不是eof cout<<"检测到EOF"<<endl; fcin.close(); //如果键盘模拟的eof之后还有其它输入,加上cin.clear(),这里用的是文件流不需要加 /* ofstream ffout("keyword.txt",ios::out|ios::app); ffout<<str<<endl; */ cout<<"文本内容是:"<<endl<<str<<ends; }
/* ** EPITECH PROJECT, 2019 ** OOP_indie_studio_2018 ** File description: ** Map */ #include <fstream> #include <iostream> #include <exception> #include <string> #include <vector> #include <string.h> #include "Map.hpp" #include "Core.hpp" #include "Assets.hpp" #include "Exception.hpp" Map::Map() { } Map::~Map() { } void Map::display(std::vector<std::string> map) { int x = 0; int y = 0; while (y < map.size()) { if (map.at(y)[x] == '\0') { printf("\n"); y += 1; x = 0; } else { printf("%c", map.at(y)[x]); x += 1; } } } void Map::link_map(Core *_core) { _smgr = _core->getSceneManager(); _driver = _core->getVideoDriver(); scene::ISceneNode *_scene = _smgr->addEmptySceneNode(); std::vector<std::string> NewMap = getMap(); int x = 0; int y = 0; while (y < NewMap.size()) { if (NewMap.at(y)[x] == '\0') { y += 1; x = 0; } else { irr::scene::ISceneNode *bl = nullptr; if (NewMap.at(y)[x] == 'M') { // printf("WALL\n"); bl = creatObj(core::vector3df(0.06f, 0.06f, 0.06f), core::vector3df(x * 4.9f, 4.7f, 4.9f * y), _smgr, _assets.getFile(Assets::FILES::WALL3D), _assets.getFile(Assets::FILES::WALLTEX), _scene); } else if (NewMap.at(y)[x] == '*' || NewMap.at(y)[x] == '1' || NewMap.at(y)[x] == '2' || NewMap.at(y)[x] == '3' || NewMap.at(y)[x] == '4') { creatSquare(irr::core::vector3df(3.5f, 0.0f, 3.7f), irr::core::vector3df(x * 5.0f, 0, 4.9f * y), _smgr, _assets.getFile(Assets::FILES::GROUNDTEX), _scene); } else if (NewMap.at(y)[x] == 'C') { bl = creatObj(core::vector3df(0.05f, 0.05f, 0.05f), core::vector3df(x * 4.9f, 4.7f, 4.9f * y), _smgr, _assets.getFile(Assets::FILES::WALL3D), _assets.getFile(Assets::FILES::WOODTEX), _scene); } x += 1; } } } void Map::PutBomb(Core *_core, core::vector3df pos) { _smgr = _core->getSceneManager(); _driver = _core->getVideoDriver(); scene::ISceneNode *_scene = _smgr->addEmptySceneNode(); irr::scene::ISceneNode *bl = creatObj(core::vector3df(15.0f, 15.0f, 15.0f), pos, _smgr, _assets.getFile(Assets::FILES::BOMB3D), _assets.getFile(Assets::FILES::BOMBTEX), _scene); } irr::scene::ISceneNode *Map::creatSquare( const irr::core::vector3df &scale, const irr::core::vector3df &pos, irr::scene::ISceneManager *smgr, const std::string &path, irr::scene::ISceneNode *scene) { irr::scene::ISceneNode *news = smgr->addCubeSceneNode(4.0f, scene); news->setScale(scale); news->setPosition(pos); news->setMaterialTexture(0, _driver->getTexture(path.c_str())); news->setMaterialFlag(irr::video::EMF_LIGHTING, false); return (news); } scene::ISceneNode *Map::creatObj( const core::vector3df &scale, const core::vector3df &pos, scene::ISceneManager *smgr, const std::string &path, const std::string &path2, scene::ISceneNode *scene) { scene::ISceneNode *news = smgr->addMeshSceneNode(smgr->getMesh(path.c_str()), scene); news->setScale(scale); news->setPosition(pos); news->setMaterialTexture(0, _driver->getTexture(path2.c_str())); news->setMaterialFlag(video::EMF_LIGHTING, false); return (news); } void Map::init(const std::string &mapAsset) { std::string line; std::vector<std::string> mapVector; std::ifstream myfile(mapAsset); if (myfile.is_open()) { while (getline(myfile, line)) mapVector.push_back(line); } else { throw Exception("Map: unable to open file"); } myfile.close(); setMap(mapVector); } void Map::setMap(std::vector<std::string> newmap) { this->_map = newmap; } std::vector<std::string> Map::getMap() { return(this->_map); }
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=// // Подсчёт символов в слове. // V 0.1 beta // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=// #include<iostream> #include<string> using namespace std; int main() { cout << "Enter a word: "; string userWord; getline(cin, userWord); cout << "Length you word: " << userWord.length() << " characters\n"; return 0; } /* Output: Enter a word: Alex Length you word: 4 characters */ // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // END FILE // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //
class SmokeLauncherMag { weight = 2.0; }; class FlareLauncherMag { weight = 2.0; }; class 29Rnd_30mm_AGS30 { weight = 16; }; class 29Rnd_30mm_AGS30_heli { weight = 16; }; class 400Rnd_30mm_AGS17 { weight = 50; }; class 48Rnd_40mm_MK19 { weight = 25; }; class 2000Rnd_762x51_M134 { weight = 50; }; class 4000Rnd_762x51_M134 { weight = 100; }; class 100Rnd_127x99_M2 { weight = 30; }; class 250Rnd_127x99_M3P { weight = 70; }; class 50Rnd_127x107_DSHKM { weight = 15; }; class 150Rnd_127x107_DSHKM { weight = 45; }; class 50Rnd_127x108_KORD { weight = 15; }; class 150Rnd_127x108_KORD { weight = 45; }; class pook_1300Rnd_762x51_M60 { weight = 40; }; class pook_250Rnd_762x51 { weight = 8; }; class 6Rnd_Grenade_Camel { weight = 6; }; class pook_12Rnd_Grenade_Camel { weight = 12; }; class 3Rnd_GyroGrenade { weight = 3; }; class 500Rnd_TwinVickers { weight = 10; }; class 200Rnd_762x51_M240 { weight = 5; }; class 2000Rnd_762x51_L94A1 { weight = 20; }; class 32Rnd_40mm_GMG { weight = 10; }; class 6Rnd_HE_M203_heli { weight = 3; }; class 460Rnd_762x51_M240_ACR { weight = 6; }; class 220Rnd_25mm_GAU22 { weight = 5; }; class 22Rnd_125mmSABOT_IMI { weight = 3; }; class 15Rnd_125mmHE_T72CZ { weight = 2.5; }; class 1470Rnd_127x108_YakB { weight = 70; }; class 500Rnd_145x115_KPVT { weight = 25; }; class 750Rnd_M197_AH1 { weight = 40; }; class 2100Rnd_20mm_M168 { weight = 110; }; class 2000Rnd_23mm_AZP85 { weight = 100; }; class 40Rnd_23mm_AZP85 { weight = 5; }; class 1000Rnd_23mm_2A14_HE { weight = 6; }; class 1000Rnd_23mm_2A14_AP { weight = 6; }; class 520Rnd_23mm_GSh23L { weight = 26; }; class 300Rnd_25mm_GAU12 { weight = 22; }; class 210Rnd_25mm_M242_HEI { weight = 20; }; class 210Rnd_25mm_M242_APDS { weight = 20; }; class 230Rnd_30mmHE_2A42 { weight = 21; }; class 250Rnd_30mmHE_2A72 { weight = 25; }; class 250Rnd_30mmAP_2A72 { weight = 25; }; class 250Rnd_30mmHE_2A42 { weight = 25; }; class 250Rnd_30mmAP_2A42 { weight = 25; }; class 230Rnd_30mmAP_2A42 { weight = 21; }; class 150Rnd_30mmHE_2A42 { weight = 15; }; class 150Rnd_30mmAP_2A42 { weight = 15; }; class 1904Rnd_30mmAA_2A38M { weight = 90; }; class 1350Rnd_30mmAP_A10 { weight = 60; }; class 180Rnd_30mm_GSh301 { weight = 5; }; class 750Rnd_30mm_GSh301 { weight = 75; }; class 30Rnd_105mmHE_M119 { weight = 4; }; class 20Rnd_120mmHE_M1A2 { weight = 4; }; class 20Rnd_120mmSABOT_M1A2 { weight = 13; }; class 30Rnd_122mmHE_D30 { weight = 5; }; class 22Rnd_125mmHE_T72 { weight = 5; }; class 22Rnd_100mm_HE_2A70 { weight = 4; }; class 23Rnd_125mmSABOT_T72 { weight = 5; }; class 33Rnd_85mmHE { weight = 3.5; }; class 10Rnd_85mmAP { weight = 2; }; class 8Rnd_AT5_BMP2 { weight = 8; }; class 5Rnd_AT5_BRDM2 { weight = 5; }; class 8Rnd_AT10_BMP3 { weight = 8; }; class 5Rnd_AT11_T90 { weight = 5; }; class BAF_L109A1_HE { weight = 6; }; class 6RND_105mm_APDS { weight = 6; }; class 12RND_105mm_HESH { weight = 12; }; class 60Rnd_CMFlareMagazine { weight = 12; }; class 120Rnd_CMFlareMagazine { weight = 24; }; class 240Rnd_CMFlareMagazine { weight = 48; }; class 60Rnd_CMFlare_Chaff_Magazine { weight = 12; }; class 120Rnd_CMFlare_Chaff_Magazine { weight = 24; }; class 240Rnd_CMFlare_Chaff_Magazine { weight = 48; }; class 30Rnd_122mmWP_D30 { weight = 8; }; class 30Rnd_122mmSADARM_D30 { weight = 8; }; class 30Rnd_122mmLASER_D30 { weight = 8; }; class 30Rnd_122mmSMOKE_D30 { weight = 8; }; class 30Rnd_122mmILLUM_D30 { weight = 8; }; class 30Rnd_105mmWP_M119 { weight = 8; }; class 30Rnd_105mmSADARM_M119 { weight = 8; }; class 30Rnd_105mmLASER_M119 { weight = 8; }; class 30Rnd_105mmSMOKE_M119 { weight = 8; }; class 30Rnd_105mmILLUM_M119 { weight = 8; }; class 100Rnd_127x99_L2A1 { weight = 5; }; class 150Rnd_23mm_GSh23L { weight = 5; }; class 14Rnd_FFAR { weight = 2; }; class 12Rnd_FFAR { weight = 2; }; class 8Rnd_Stinger { weight = 8; }; class 2Rnd_Stinger { weight = 2; }; class 1200Rnd_762x51_M240 { weight = 60; }; class 1500Rnd_762x54_PKT { weight = 75; }; class 2000Rnd_762x54_PKT { weight = 50; }; class 200Rnd_762x54_PKT { weight = 5; }; class 250Rnd_762x54_PKT_T90 { weight = 5.4; }; class 4Rnd_AT9_Mi24P { weight = 4; }; class 4Rnd_AT6_Mi24V { weight = 4; }; class 4Rnd_AT2_Mi24D { weight = 4; }; class 6Rnd_AT13 { weight = 6; }; class 6Rnd_TOW_HMMWV { weight = 6; }; class 2Rnd_TOW { weight = 2; }; class 6Rnd_TOW2 { weight = 6; }; class 2Rnd_TOW2 { weight = 2; }; class 8Rnd_Hellfire { weight = 8; }; class 12Rnd_Vikhr_KA50 { weight = 12; }; class 4Rnd_Sidewinder_AV8B { weight = 4; }; class 2Rnd_Sidewinder_F35 { weight = 2; }; class 2Rnd_Sidewinder_AH1Z { weight = 2; }; class 28Rnd_FFAR { weight = 6; }; class 38Rnd_FFAR { weight = 8; }; class 40Rnd_80mm { weight = 8; }; class 80Rnd_80mm { weight = 16; }; class 40Rnd_GRAD { weight = 5; }; class 12Rnd_MLRS { weight = 12; }; class 40Rnd_S8T { weight = 7; }; class 80Rnd_S8T { weight = 14; }; class 64Rnd_57mm { weight = 9; }; class 128Rnd_57mm { weight = 12; }; class 192Rnd_57mm { weight = 14; }; class 6Rnd_GBU12_AV8B { weight = 6; }; class 2Rnd_GBU12 { weight = 2; }; class 4Rnd_GBU12 { weight = 4; }; class 2Rnd_FAB_250 { weight = 2; }; class 4Rnd_FAB_250 { weight = 4; }; class 6Rnd_Mk82 { weight = 6; }; class 3Rnd_Mk82 { weight = 3; }; class 4Rnd_R73 { weight = 4; }; class 2Rnd_R73 { weight = 2; }; class 4Rnd_Ch29 { weight = 4; }; class 6Rnd_Ch29 { weight = 6; }; class 2Rnd_Maverick_A10 { weight = 2; }; class 8Rnd_9M311 { weight = 8; }; class 1200Rnd_30x113mm_M789_HEDP { weight = 50; }; class 8Rnd_Sidewinder_AH64 { weight = 8; }; class 200Rnd_762x54_GPMG { weight = 8; }; class 12Rnd_CRV7 { weight = 12; }; class 38Rnd_CRV7 { weight = 38; }; class 6Rnd_CRV7_HEPD { weight = 6; }; class 6Rnd_CRV7_FAT { weight = 6; }; class 1200Rnd_20mm_M621 { weight = 70; }; class 21Rnd_100mmHEAT_D10 { weight = 21; }; class 4Rnd_Hellfire { weight = 4; }; class 4Rnd_Stinger { weight = 4; }; class 24Rnd_120mmHE_M120 { weight = 24; }; class 24Rnd_120mmHE_M120_02 { weight = 24; }; class 8Rnd_81mmHE_M252 { weight = 8; }; class 8Rnd_81mmWP_M252 { weight = 8; }; class 8Rnd_81mmILLUM_M252 { weight = 8; }; class 8Rnd_82mmHE_2B14 { weight = 8; }; class 8Rnd_82mmWP_2B14 { weight = 8; }; class 8Rnd_82mmILLUM_2B14 { weight = 8; }; class 14Rnd_57mm { weight = 14; }; class 1Rnd_Bolide { weight = 1; }; class 210Rnd_20mm_ZPL_20 { weight = 4; }; class 8Rnd_AT9_Mi24V { weight = 8; }; class 4Rnd_Maverick_L159 { weight = 4; }; class 140Rnd_30mm_ATKMK44_HE_ACR { weight = 10; }; class 60Rnd_30mm_ATKMK44_AP_ACR { weight = 4; }; class 2Rnd_Spike_ACR { weight = 2; }; class 40Rnd_GRAD_ACR { weight = 4; }; class 2Rnd_Mk82 { weight = 2; }; class 4Rnd_Mk82 { weight = 4; }; class 2Rnd_GBU12_AV8B { weight = 2; }; class 4Rnd_GBU12_AV8B { weight = 4; }; class 400Rnd_20mm_M621 { weight = 6; }; class 8Rnd_Ch29 { weight = 8; }; class PG15V { weight = 2; }; class 40rnd_PG15V { weight = 20; }; class AT3 { weight = 2; }; class 4rnd_AT3 { weight = 8; }; class 1Rnd_AT3 { weight = 2; }; class IR_Strobe_Marker { weight = 1; }; class IRStrobe { weight = 2; };
/* * @lc app=leetcode id=26 lang=cpp * * [26] Remove Duplicates from Sorted Array * * https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ * * algorithms * Easy (41.30%) * Likes: 1634 * Dislikes: 3496 * Total Accepted: 638.6K * Total Submissions: 1.5M * Testcase Example: '[1,1,2]' * * Given a sorted array nums, remove the duplicates in-place such that each * element appear only once and return the new length. * * Do not allocate extra space for another array, you must do this by modifying * the input array in-place with O(1) extra memory. * * Example 1: * * * Given nums = [1,1,2], * * Your function should return length = 2, with the first two elements of nums * being 1 and 2 respectively. * * It doesn't matter what you leave beyond the returned length. * * Example 2: * * * Given nums = [0,0,1,1,1,2,2,3,3,4], * * Your function should return length = 5, with the first five elements of nums * being modified to 0, 1, 2, 3, and 4 respectively. * * It doesn't matter what values are set beyond the returned length. * * * Clarification: * * Confused why the returned value is an integer but your answer is an array? * * Note that the input array is passed in by reference, which means * modification to the input array will be known to the caller as well. * * Internally you can think of this: * * * // nums is passed in by reference. (i.e., without making a copy) * int len = removeDuplicates(nums); * * // any modification to nums in your function would be known by the caller. * // using the length returned by your function, it prints the first len * elements. * for (int i = 0; i < len; i++) { * print(nums[i]); * } * */ #include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: int removeDuplicates(vector<int>& nums) { if (nums.size() == 0) return 0; int i = 0; for (int j = 1; j < nums.size(); ++j) { if (nums[j] != nums[i]) nums[++i] = nums[j]; } return ++i; } int wrong_answer(vector<int>& nums) { if (nums.size() == 0) return 0; int last = nums[0]; int cnt = 1; for (int i = 1; i < nums.size() - 1; ++i) { if (last == nums[i]) { nums[i] = nums[i + 1]; } else { last = nums[i]; ++cnt; } } return cnt; } }; // void test_single(vector<int>& arr) { // cout << "========= Tesing ========= " << endl; // cout <<"before = ["; // for_each(arr.begin(), arr.end(), [](int i) {cout << i <<",";}); // cout << "]" << endl; // int ans = Solution().removeDuplicates(arr); // cout <<"after = ["; // for_each(arr.begin(), arr.end(), [](int i) {cout << i <<",";}); // cout << "]" << endl; // cout << "ans = " << ans << endl; // } // int main() { // vector<vector<int>> test_cases = { // {1, 1, 2}, // {0, 0, 1, 1, 2, 2, 3, 3, 4}, // {1, 1, 1, 1, 1}, // {1, 1, 1, 2, 2} // }; // for (auto& i : test_cases) { // test_single(i); // } // return 0; // }
#ifndef USE_H #define USE_H #include <iostream> #include <string> class User { std::string status = "gold"; static int user_count; public: std::string fname; std::string lname; static int get_user_count(); std::string get_status(); void set_status(std::string status); User(); User(std::string frame, std::string lname, std::string status); ~User(); void output(); //virtual void output(); friend std::ostream &operator<<(std::ostream &output, User user); friend std::istream &operator>>(std::istream &input, User &user); friend void get_status_friendly(User user); }; #endif
#include <bits/stdc++.h> using namespace std; class Node { public: int key; int value; Node *next, *prev; Node(int key, int value) { this->key = key; this->value = value; this->prev = this->next = NULL; } }; class LRUCache { private: int size, capacity; unordered_map<int, Node*> lookup; Node *head, *tail; void insertNew(int key, int value) { Node *temp = new Node(key, value); if(head==NULL && tail==NULL) { head = tail = temp; } else { temp->next = head; head->prev = temp; head = temp; } // Now making entry in lookup table lookup[key] = temp; return; } void updateOld(Node *addr, int value) { // Update value for the key addr->value = value; // Move to first position // 1. Link Previous and Next of our target node if(addr == head) return; if(addr == tail) { tail = addr->prev; tail->next = NULL; } else { addr->prev->next = addr->next; addr->next->prev = addr->prev; } // 2. Insert target node at head addr->next = head; head->prev = addr; head = addr; head->prev = NULL; return; } public: LRUCache(int capacity) { this->capacity = capacity; size = 0; head = tail = NULL; } int get(int key) { auto it = lookup.find(key); if(it == lookup.end()) return -1; Node *temp = it->second; // Moving the node to first position and keeping same value; updateOld(temp, temp->value); return temp->value; } void put(int key, int value) { auto it = lookup.find(key); // Check if key exists in lookup table if(it != lookup.end()) { updateOld(it->second, value); } else { // Check if List is full if(size == capacity) { // Remove from lookup table lookup.erase(tail->key); // Remove from tail Node *temp = tail; // If the capacity of LRU Cache is 1 if(head == tail) { head = tail = NULL; } else { tail = tail->prev; tail->next = NULL; } delete temp; // Insert the new node insertNew(key, value); } else { insertNew(key, value); size += 1; } } } }; int main() { LRUCache cache(2); cache.put(1, 1); cache.put(2, 2); cout << cache.get(1) << endl; // returns 1 cache.put(3, 3); // evicts key 2 cout << cache.get(2) << endl; // returns -1 (not found) cache.put(4, 4); // evicts key 1 cout << cache.get(1) << endl; // returns -1 (not found) cout << cache.get(3) << endl; // returns 3 cout << cache.get(4) << endl; // returns 4 return 0; }
void calcSum();
#include <stdint.h> #include <avr/io.h> #include <util/twi.h> #include <util/delay.h> #include <avr/pgmspace.h> #include "ov7670.h" void setColor(void) { wrSensorRegs8_8(yuv422_ov7670); } void setRes(void) { wrReg(REG_COM3, 4); // REG_COM3 enable scaling wrSensorRegs8_8(qvga_ov7670); wrReg(0x11, 11); // PCLK prescaler } void camInit(void) { wrReg(0x12, 0x80); _delay_ms(100); wrSensorRegs8_8(ov7670_default_regs); wrReg(REG_COM10, 32);//PCLK does not toggle on HBLANK. } void arduinoUnoInit(void) { cli();//disable interrupts /* Setup the 8mhz PWM clock This will be on pin 11*/ DDRB |= (1 << 3);//pin 11 ASSR &= ~(_BV(EXCLK) | _BV(AS2)); TCCR2A = (1 << COM2A0) | (1 << WGM21) | (1 << WGM20); TCCR2B = (1 << WGM22) | (1 << CS20); OCR2A = 0;//(F_CPU)/(2*(X+1)) DDRC &= ~15;//low d0-d3 camera DDRD &= ~252;//d7-d4 and interrupt pins _delay_ms(3000); //set up twi for 100khz TWSR &= ~3;//disable prescaler for TWI TWBR = 72;//set to 100khz //enable serial UBRR0H = 0; UBRR0L = 1;//0 = 2M baud rate. 1 = 1M baud. 3 = 0.5M. 7 = 250k 207 is 9600 baud rate. UCSR0A |= 2;//double speed aysnc UCSR0B = (1 << RXEN0) | (1 << TXEN0);//Enable receiver and transmitter UCSR0C = 6;//async 1 stop bit 8bit char no parity bits } void StringPgm(const char * str) { do { while (!(UCSR0A & (1 << UDRE0)));//wait for byte to transmit UDR0 = pgm_read_byte_near(str); while (!(UCSR0A & (1 << UDRE0)));//wait for byte to transmit } while (pgm_read_byte_near(++str)); } static void captureImg(){ uint16_t y, x; StringPgm(PSTR("*RDY*")); while (!(PIND & 8));//wait for high while ((PIND & 8));//wait for low y = 240; while (y--){ x = 320; //while (!(PIND & 256));//wait for high while (x--){ while ((PIND & 4));//wait for low if( (y >= 60) && ( y < 180 ) && (x >= 80) && ( x < 240 ) ){ UDR0 = (PINC & 15) | (PIND & 240); while (!(UCSR0A & (1 << UDRE0)));//wait for byte to transmit } while (!(PIND & 4));//wait for high while ((PIND & 4));//wait for low while (!(PIND & 4));//wait for high } // while ((PIND & 256));//wait for low } _delay_ms(100); } void setup(){ arduinoUnoInit(); camInit(); setRes(); setColor(); pinMode(13, OUTPUT); // led for visual debugging pinMode(12, INPUT); // simulate the door phone button // a small flash after which the interphone can be played digitalWrite(13, HIGH); _delay_ms(200); digitalWrite(13, LOW); } int lettura = 0, old_lettura = 0; void loop(){ lettura = digitalRead(12); // read button status // capture the image only if the button come pressed and not if it was remained pressed if (old_lettura != lettura && old_lettura == 0) { digitalWrite(13, HIGH); // high when the button come pressed, wait 3 seconds _delay_ms(3000); digitalWrite(13, LOW); // little blink when the photo starts _delay_ms(200); digitalWrite(13, HIGH); // led high while capturing captureImg(); digitalWrite(13, LOW); // led low when finished _delay_ms(4000); // wait 4 seconds before strat a new capturing digitalWrite(13, HIGH); // little blink to signal that it is possible to start a new capturing _delay_ms(200); digitalWrite(13, LOW); } old_lettura = lettura; // old_lettura remains high until the next time that lettura come back high, double read avoided if the button didn't come released delay(200); }
#include <iostream> #include <string> #include <vector> using namespace std; template <class T> void array_sort(T *a, int n) { int flag; for (int i = n - 1; i > 1; i--) { flag = 0; for (int j = 0; j < i; j++) { if (a[j] < a[j + 1]) { T temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; flag = 1; } } if (flag == 0) { return; } } } template <class T> void print_array(T *p, int n) { for (int i = 0; i < n; i++) { cout << p[i] << " "; } cout << endl; } void test01() { int a[] = {1, 5, 7, 3, 9, 6}; array_sort(a, sizeof(a) / sizeof(a[0])); print_array(a, sizeof(a) / sizeof(a[0])); } void test02() { double b[] = {3.1, 2.5, 6.4, 9.1, 8.7}; array_sort(b, sizeof(b) / sizeof(b[0])); print_array(b, sizeof(b) / sizeof(b[0])); } int main(int argc, char **argv) { test01(); test02(); return 0; }
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define rep1(i, n) for(int i = 1; i <= (int)(n); i++) #define show(x) for(auto i: x){cout << i << " ";} #define showm(m) for(auto i: m){cout << m.x << " ";} typedef long long ll; typedef pair<string, int> P; ll gcd(int x, int y){ return y?gcd(y, x%y):x;} ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);} int main() { int n; cin >> n; vector<string> s; rep(i, n){ string tmp; cin >> tmp; s.push_back(tmp);} //O(nlogn) sort(s.begin(), s.end()); // show(s); // cout << endl << endl; //O(n) int maxcnt = 0; int cnt = 1; vector<P> ans; rep(i, n-1){ if (s[i] == s[i+1]){ cnt++; } else { ans.emplace_back(s[i], cnt); cnt = 1; } maxcnt = max(maxcnt, cnt); } ans.emplace_back(s[n-1], cnt); rep(i, ans.size()){ if (ans[i].second == maxcnt){ cout << ans[i].first << endl; } } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2012 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Cezary Kulakowski (ckulakowski) */ #include "core/pch.h" #include "adjunct/quick/controller/PermissionPopupController.h" #include "adjunct/quick/windows/DocumentDesktopWindow.h" #include "adjunct/quick_toolkit/widgets/CalloutDialogPlacer.h" #include "adjunct/quick_toolkit/widgets/QuickLabel.h" #include "adjunct/quick_toolkit/widgets/QuickDropDown.h" #include "adjunct/quick_toolkit/widgets/QuickIcon.h" #include "adjunct/quick_toolkit/widgets/QuickButton.h" #include "adjunct/quick_toolkit/widgets/NullWidget.h" #include "adjunct/quick_toolkit/widgets/QuickPagingLayout.h" #include "adjunct/quick_toolkit/widgets/QuickSeparator.h" #include "adjunct/quick_toolkit/widgets/QuickRichTextLabel.h" #include "adjunct/quick_toolkit/widgets/QuickGrid/QuickDynamicGrid.h" #include "adjunct/quick_toolkit/widgets/QuickGrid/QuickStackLayout.h" #include "adjunct/desktop_util/string/i18n.h" #include "modules/locale/oplanguagemanager.h" void PermissionPopupController::InitL() { QuickOverlayDialog* dialog = OP_NEW_L(QuickOverlayDialog, ()); LEAVE_IF_ERROR(SetDialog("Permission Popup", dialog)); m_widgets = dialog->GetWidgetCollection(); if (m_anchor_widget) { CalloutDialogPlacer* placer = OP_NEW_L(CalloutDialogPlacer, (*m_anchor_widget, CalloutDialogPlacer::LEFT, "Permission Popup Skin")); dialog->SetDialogPlacer(placer); } dialog->SetBoundingWidget(m_bounding_widget); dialog->SetAnimationType(QuickOverlayDialog::DIALOG_ANIMATION_CALLOUT); const char* device_icon_image = NULL; ANCHORD(OpString, device_label_str); ANCHORD(OpString, permission_label_str); ANCHORD(OpString, highlighted_hostname); highlighted_hostname.SetL("<b>"); highlighted_hostname.AppendL(m_hostname); highlighted_hostname.AppendL("</b>"); switch (m_type) { case OpPermissionListener::PermissionCallback::PERMISSION_TYPE_GEOLOCATION_REQUEST: { device_icon_image = "Geolocation Indicator Icon"; g_languageManager->GetStringL(Str::D_PERMISSION_TYPE_GEOLOCATION, device_label_str); LEAVE_IF_ERROR(I18n::Format(permission_label_str, Str::D_GEOLOCATION_ACCESS_REQUEST_LABEL, highlighted_hostname)); break; } case OpPermissionListener::PermissionCallback::PERMISSION_TYPE_CAMERA_REQUEST: { device_icon_image = "Camera Indicator Icon"; g_languageManager->GetStringL(Str::D_PERMISSION_TYPE_CAMERA, device_label_str); LEAVE_IF_ERROR(I18n::Format(permission_label_str, Str::D_CAMERA_ACCESS_REQUEST_LABEL, highlighted_hostname)); break; } default: { OP_ASSERT(!"Unknown permission type"); LEAVE(OpStatus::ERR); } } LEAVE_IF_ERROR(m_widgets->GetL<QuickRichTextLabel>("Permission_label")->SetText(permission_label_str)); m_widgets->GetL<QuickIcon>("Device_icon")->SetImage(device_icon_image); LEAVE_IF_ERROR(m_widgets->GetL<QuickLabel>("Device_label")->SetText(device_label_str)); if (m_toplevel_domain != m_hostname) { LEAVE_IF_ERROR(m_widgets->GetL<QuickLabel>("Accessing_host_label")->SetText(m_hostname)); m_widgets->GetL<QuickStackLayout>("Iframe_host_stack")->Show(); m_widgets->GetL<QuickStackLayout>("Toplevel_host_stack")->Show(); LEAVE_IF_ERROR(m_widgets->GetL<QuickLabel>("Toplevel_host_label")->SetText(m_toplevel_domain)); m_widgets->GetL<QuickIcon>("Addressbar_vertical_separator")->Show(); } m_deny_permission_on_closing = true; } void PermissionPopupController::OnKeyboardInputGained(OpInputContext* new_context, OpInputContext* old_context, FOCUS_REASON reason) { if (new_context == this) { QuickButton* ok_button = m_widgets->Get<QuickButton>("button_OK"); if (ok_button->IsVisible()) { ok_button->GetOpWidget()->SetFocus(reason); } } } void PermissionPopupController::OnCancel() { if (m_deny_permission_on_closing) { m_desktop_window->HandleCurrentPermission(false, OpPermissionListener::PermissionCallback::PERSISTENCE_TYPE_NONE); } } void PermissionPopupController::OnOk() { QuickDropDown* dropdown = m_widgets->Get<QuickDropDown>("Domain_dropdown"); switch (dropdown->GetOpWidget()->GetValue()) { case ALWAYS_ALLOW: { m_desktop_window->HandleCurrentPermission(true, OpPermissionListener::PermissionCallback::PERSISTENCE_TYPE_ALWAYS); break; } case ALLOW_ONCE: { m_desktop_window->HandleCurrentPermission(true, OpPermissionListener::PermissionCallback::PERSISTENCE_TYPE_RUNTIME); break; } case DENY: { m_desktop_window->HandleCurrentPermission(false, OpPermissionListener::PermissionCallback::PERSISTENCE_TYPE_ALWAYS); break; } default: { OP_ASSERT(!"Unknown dropdown value"); break; } } } void PermissionPopupController::SetIsOnBottom() { m_dialog->GetDesktopWindow()->GetSkinImage()->SetType(SKINTYPE_BOTTOM); }
// Created on: 1996-08-30 // Created by: Yves FRICAUD // Copyright (c) 1996-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 _BRepOffset_Inter3d_HeaderFile #define _BRepOffset_Inter3d_HeaderFile #include <Message_ProgressRange.hxx> #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <TopTools_IndexedMapOfShape.hxx> #include <TopTools_DataMapOfShapeListOfShape.hxx> #include <TopAbs_State.hxx> #include <TopTools_ListOfShape.hxx> #include <BRepOffset_DataMapOfShapeOffset.hxx> #include <TopTools_DataMapOfShapeShape.hxx> class BRepAlgo_AsDes; class BRepAlgo_Image; class TopoDS_Face; class TopoDS_Shape; class BRepOffset_Analyse; //! Computes the connection of the offset and not offset faces //! according to the connection type required. //! Store the result in AsDes tool. class BRepOffset_Inter3d { public: DEFINE_STANDARD_ALLOC public: //! Constructor Standard_EXPORT BRepOffset_Inter3d (const Handle (BRepAlgo_AsDes)& AsDes, const TopAbs_State Side, const Standard_Real Tol); // Computes intersection of the given faces among each other Standard_EXPORT void CompletInt (const TopTools_ListOfShape& SetOfFaces, const BRepAlgo_Image& InitOffsetFace, const Message_ProgressRange& theRange); //! Computes intersection of pair of faces Standard_EXPORT void FaceInter (const TopoDS_Face& F1, const TopoDS_Face& F2, const BRepAlgo_Image& InitOffsetFace); //! Computes connections of the offset faces that have to be connected by arcs. Standard_EXPORT void ConnexIntByArc (const TopTools_ListOfShape& SetOfFaces, const TopoDS_Shape& ShapeInit, const BRepOffset_Analyse& Analyse, const BRepAlgo_Image& InitOffsetFace, const Message_ProgressRange& theRange); //! Computes intersection of the offset faces that have to be connected by //! sharp edges, i.e. it computes intersection between extended offset faces. Standard_EXPORT void ConnexIntByInt (const TopoDS_Shape& SI, const BRepOffset_DataMapOfShapeOffset& MapSF, const BRepOffset_Analyse& A, TopTools_DataMapOfShapeShape& MES, TopTools_DataMapOfShapeShape& Build, TopTools_ListOfShape& Failed, const Message_ProgressRange& theRange, const Standard_Boolean bIsPlanar = Standard_False); //! Computes intersection with not offset faces . Standard_EXPORT void ContextIntByInt (const TopTools_IndexedMapOfShape& ContextFaces, const Standard_Boolean ExtentContext, const BRepOffset_DataMapOfShapeOffset& MapSF, const BRepOffset_Analyse& A, TopTools_DataMapOfShapeShape& MES, TopTools_DataMapOfShapeShape& Build, TopTools_ListOfShape& Failed, const Message_ProgressRange& theRange, const Standard_Boolean bIsPlanar = Standard_False); //! Computes connections of the not offset faces that have to be connected by arcs Standard_EXPORT void ContextIntByArc (const TopTools_IndexedMapOfShape& ContextFaces, const Standard_Boolean ExtentContext, const BRepOffset_Analyse& Analyse, const BRepAlgo_Image& InitOffsetFace, BRepAlgo_Image& InitOffsetEdge, const Message_ProgressRange& theRange); //! Marks the pair of faces as already intersected Standard_EXPORT void SetDone (const TopoDS_Face& F1, const TopoDS_Face& F2); //! Checks if the pair of faces has already been treated. Standard_EXPORT Standard_Boolean IsDone (const TopoDS_Face& F1, const TopoDS_Face& F2) const; //! Returns touched faces TopTools_IndexedMapOfShape& TouchedFaces() { return myTouched; }; //! Returns AsDes tool Handle (BRepAlgo_AsDes) AsDes() const { return myAsDes; } //! Returns new edges TopTools_IndexedMapOfShape& NewEdges() { return myNewEdges; } private: //! Stores the intersection results into AsDes Standard_EXPORT void Store (const TopoDS_Face& F1, const TopoDS_Face& F2, const TopTools_ListOfShape& LInt1, const TopTools_ListOfShape& LInt2); private: Handle (BRepAlgo_AsDes) myAsDes; TopTools_IndexedMapOfShape myTouched; TopTools_DataMapOfShapeListOfShape myDone; TopTools_IndexedMapOfShape myNewEdges; TopAbs_State mySide; Standard_Real myTol; }; #endif // _BRepOffset_Inter3d_HeaderFile
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2007-2012 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef _VIEWERS_ #define _VIEWERS_ /** * Design decisions and short explanation of the viewer API: * * When redesigning the old API, the following problems in the old API were identified: * 1 - Inefficient querying (Viewers were stored in OpVector, and queried by string comparing each and every content-type for a match (O(n))) * 2 - Lots of converting from uni_char to char (or char to uni_char) * 3 - Extensive use of 'id' as a unique thing, which, in case of adding or deleting viewers run-time, would not be unique at all.. (id was position in array) * 4 - Extensive parsing (extensions were stored in one string, which was parsed every time it was queried) * 5 - Platform code in core module * 6 - UI code in core module * 7 - Only support for one plugin per viewer * * The problems were solved by: * 1 - Viewers are now stored in hashed tables (two tables, one hashed using 16-bit content type string, and one hashed using 8-bit content-type string). * Querying by content-type is now reduced to O(1). The Viewers class now contains functions for querying by extension or url, but these are not * hashed, and thus not as efficient. * 2 - Most converting was caused by mixing 16- and 8-bit content types. Viewer now contains both 16- and 8-bit version of content-type, and hashed list * for both of them. For a small increase in footprint, a lot of converting is now removed. * 3 - id is now completely removed. Find viewer by content-type, extension or url, or use CreateIterator * and GetNextViewer to iterate linear without the need for id * 4 - Extensions are kept in one string, but also in a parsed list of strings. It is now easy to add or remove support for a single extension run-time * 5 - The Quick-based BroadcastItemChanged etc, are now replaced by cross-platform functions OnViewerChanged etc * 6 - A lot of UI code is simply removed (watch out for regressions!). In particular, the viewer classes are no longer possible to embed directly into * OpTreeViews as they don'y implement OpTreeModel anymore * 7 - Viewer now has a list of pointers to supported plugins. These lists are updated automatically, as long as the Viewer object is added to the * one and only Viewer manager 'g_viewers'. The first enabled plugin with the lowest index is considered the default plugin (the order for other * plugins is not stored, yet) * * * Other relevant changes: Most functions are changed to return OP_STATUS, not to Leave, take OpString parameters, and have meaningful and * self-explaining names. Viewer code is still split in two, one class for the Viewer itself, and one class for managing Viewer objects, which will be * available as one and only one instance, 'g_viewers'. Adding, deleting, querying and other viewer managment tasks is to be performed on this instance. */ #ifdef _PLUGIN_SUPPORT_ # include "modules/viewers/plugins.h" #endif #include "modules/hardcore/mh/mh.h" #include "modules/util/OpHashTable.h" #include "modules/util/adt/opvector.h" #include "modules/viewers/src/generated_viewers_enum.h" #define defaultOperaViewerTypes_SIZE VIEWER_LAST /** Action associated with a viewer type. Must all be positive and fit * in eight bits (checked by selftest). */ typedef enum { VIEWER_ASK_USER = 0, VIEWER_SAVE = 1, VIEWER_OPERA = 2, VIEWER_APPLICATION = 3, VIEWER_REG_APPLICATION = 4, VIEWER_RUN = 5, VIEWER_PLUGIN = 6, VIEWER_PASS_URL = 7, VIEWER_IGNORE_URL = 8, VIEWER_SAVE_AND_NOTIFY = 10, VIEWER_SAVE_AND_SET_READONLY = 11, VIEWER_SAVE_AND_NOTIFY_AND_SET_READONLY = 12, VIEWER_REDIRECT = 13, // This is now obsolete. Please use VIEWER_WEB_APPLICATION instead VIEWER_WEB_APPLICATION = 14, // These should be last: VIEWER_WAIT_FOR_DATA = 98, VIEWER_NOT_DEFINED = 99 } ViewAction; class ViewActionFlag { public: enum ViewActionFlagType { NO_FLAGS = 0x0, OPEN_WHEN_COMPLETE = 0x1, SAVE_DIRECTLY = 0x2, // SAVE_DIRECTLY and SAVE_AS are mutually exclusive SAVE_AS = 0x4, USERDEFINED_VALUE = 0x80 // To separate between a default value (set by Opera) and the same value set by user. }; private: ViewActionFlagType flags; public: ViewActionFlag() : flags(NO_FLAGS) {} void SetFlags(short f) { flags = static_cast<ViewActionFlagType>(f); } void Set(ViewActionFlagType f) { flags = static_cast<ViewActionFlagType>(flags | f); } void Unset(ViewActionFlagType f) { flags = static_cast<ViewActionFlagType>(flags & ~f); } void Reset() { flags = NO_FLAGS; } ViewActionFlagType Get(ViewActionFlagType f = NO_FLAGS) const { return f == NO_FLAGS ? flags : static_cast<ViewActionFlagType>(f & flags); } BOOL IsSet(ViewActionFlagType f) const { return f == static_cast<ViewActionFlagType>(f & flags); } unsigned short operator&(short a) { return flags & a; } }; struct ViewerTypes { const char *type; const char *ext; ViewAction action: 8; unsigned int ctype: 8; ViewersEnum container: 15; /**< Type can be inside this container. */ bool web_handler_allowed: 1; /**< Type can be overridden by web handler. */ bool allow_any_extension: 1; /**< Type bypasses strict file extension check. */ }; class Viewer { friend class Viewers; #ifdef _PLUGIN_SUPPORT_ friend class PluginViewer; #endif // _PLUGIN_SUPPORT_ public: Viewer(); virtual ~Viewer(); /** Initializes a Viewer object. This object maps a content-type and(/or) file extension to an action and, if applicable, * external application or plugin. * * @param action Action for this Viewer * @param content_type Content-type from the URLContentType enum. At startup, this can be set to URL_UNDETERMINED_CONTENT, and * will be changed to the content-type mathing content_type_string in Viewers::ImportGeneratedViewersArray * @param content_type_string Content-type as a string (in case content-type isn't in the enum, or is currently unknown) * @param extensions_string Comma-separated list of extensions * @param flags Flags to tweak Viewer behaviour. See each and every flag for more info * @param application_to_open_with Full path to external application, if action is set to use external application * @param save_to_folder Full path to folder, if action is set to save to folder * @param web_handler_to_open_with Url to web handler that will dealt with * @param preferred_plugin_path Full path to preferred plugin. Note that the plugin might not be available yet (but will be * matched to Viewer automatically when it is detected by the platform), and note that the paths are compared case sensitive * if not API_PI_OPSYSTEMINFO_PATHSEQUAL is imported * @param description The description of the viewer * @return OpStatus::OK or ERR_NO_MEMORY. */ OP_STATUS Construct(ViewAction action, URLContentType content_type/*=URL_UNDETERMINED_CONTENT*/, const OpStringC& content_type_string, const OpStringC& extensions_string, ViewActionFlag::ViewActionFlagType flags=ViewActionFlag::NO_FLAGS, const OpStringC& application_to_open_with=UNI_L(""), const OpStringC& save_to_folder=UNI_L("") #ifdef WEB_HANDLERS_SUPPORT , const OpStringC& web_handler_to_open_with=UNI_L("") #endif // WEB_HANDLERS_SUPPORT #ifdef _PLUGIN_SUPPORT_ , const OpStringC& preferred_plugin_path=UNI_L("") #endif // _PLUGIN_SUPPORT_ , const OpStringC& description=UNI_L("") ); #ifndef PREFS_NO_WRITE void WriteL(); #endif // !PREFS_NO_WRITE /** Get action for this viewer * * @return Action for this viewer */ ViewAction GetAction() const {return m_action;} /** Get flags for this viewer * * @return Flags for this viewer */ ViewActionFlag GetFlags() const {return m_flags;} /** Get content-type for this viewer * * @return Content-type for this viewer */ URLContentType GetContentType() const {return GET_RANGED_ENUM(URLContentType, m_content_type); } /** Get content-type for this viewer, as string * * @return Content-type string, either as uni_char* or char* */ const uni_char* GetContentTypeString() const {return m_content_type_string.CStr();} const char* GetContentTypeString8() const {return m_content_type_string8.CStr();} /** Get one of the supported extensions * * @param index Zero-based index into the extension array * @return The extension or NULL if none exist at 'index'. */ const uni_char* GetExtension(int index) const; /** Get number of supported extensions * * @return Number of supported extensions */ UINT GetExtensionsCount() const {return m_extension_list.GetCount();} /** Get the comma-separated list of extensions * * @return The list of extensions */ const uni_char* GetExtensions() const {return m_extensions_string.CStr();} /** Check if this Viewer supports the given extension * * @return TRUE if this Viewer supports the extension, FALSE if not. OpString8-version may Leave */ BOOL HasExtension(const OpStringC& extension) const; BOOL HasExtensionL(const OpStringC8& extension) const; /** Get the external application registered for this Viewer * * @return The external application */ const uni_char* GetApplicationToOpenWith() const {return m_application_to_open_with.CStr();} #ifdef WEB_HANDLERS_SUPPORT /** Get the web handler registered for this Viewer * * @param web_handler Used to return the web handler * @return OpStatus::OK or ERR_NO_MEMORY */ OP_STATUS GetWebHandlerToOpenWith(OpString& web_handler) const {return web_handler.Set(m_web_handler_to_open_with);} /** Get the web handler registered for this Viewer * * @return The external web handler */ const uni_char* GetWebHandlerToOpenWith() const {return m_web_handler_to_open_with.CStr();} #endif // WEB_HANDLERS_SUPPORT /** Get the SaveTo folder registered for this Viewer * * @return The SaveTo folder */ const uni_char* GetSaveToFolder() const {return m_save_to_folder.CStr();} void SetAction(ViewAction action, BOOL set_userdefined_flag=FALSE) {m_action=action; if (set_userdefined_flag) SetFlag(ViewActionFlag::USERDEFINED_VALUE);} void SetFlag(ViewActionFlag::ViewActionFlagType new_flag) {m_flags.Set(new_flag);} void SetFlags(short f) {m_flags.SetFlags(f);} OP_STATUS SetContentType(URLContentType content_type, const OpStringC& content_type_string); OP_STATUS SetContentType(URLContentType content_type, const OpStringC8& content_type_string8); OP_STATUS SetContentType(const OpStringC& content_type_string); //Will look up content_type in list of known content types OP_STATUS SetContentType(const OpStringC8& content_type_string); //Will look up content_type in list of known content types OP_STATUS SetExtensions(const OpStringC& extensions); OP_STATUS AddExtension(const OpStringC& extension); OP_STATUS ResetToDefaultExtensions(); OP_STATUS SetApplicationToOpenWith(const OpStringC& application) {return m_application_to_open_with.Set(application);} #ifdef WEB_HANDLERS_SUPPORT OP_STATUS SetWebHandlerToOpenWith(const OpStringC& web_handler) {return m_web_handler_to_open_with.Set(web_handler);} #endif OP_STATUS SetSaveToFolder(const OpStringC& save_to_folder) {return m_save_to_folder.Set(save_to_folder);} #ifdef _PLUGIN_SUPPORT_ /** Find the first plugin with the given name (case-sensitive), connected to this Viewer * * @param plugin_name Name of plugin to search for * @param enabled_only Returns only enabled plugins * @return First plugin with given name, or NULL if not found */ PluginViewer* FindPluginViewerByName(const OpStringC& plugin_name, BOOL enabled_only = FALSE) const; /** Find the first plugin with the given path (case-sensitive if not API_PI_OPSYSTEMINFO_PATHSEQUAL is imported), connected to this Viewer * * @param plugin_path Full path of plugin to search for * @return First plugin with given path, or NULL if not found */ PluginViewer* FindPluginViewerByPath(const OpStringC& plugin_path) const; /** Find the default plugin (that is, the plugin at index 0 in the plugin array), connected to this Viewer * * @param skip_disabled_plugins If FALSE, plugin at index 0 is always returned. If TRUE, only enabled plugins are considered * (if plugin at index 0 is disabled, plugin at index 1 will be returned (unless it, too, is disabled)) * @return Pointer to the plugin considered default plugin for this Viewer */ PluginViewer* GetDefaultPluginViewer(BOOL skip_disabled_plugins=TRUE) const; /** Find the full path of the default plugin connected to this Viewer * * @param plugin_path Used to return the full path of the default plugin for this Viewer (empty if not found) * @param component_type Used to return the component type of the default plugin for this Viewer * @param skip_disabled_plugins If FALSE, plugin at index 0 is always returned. If TRUE, only enabled plugins are considered * (if plugin at index 0 is disabled, plugin at index 1 will be returned (unless it, too, is disabled)) * @return OpStatus::OK or ERR_NO_MEMORY */ OP_STATUS GetDefaultPluginViewerPath(OpString& plugin_path, OpComponentType& component_type, BOOL skip_disabled_plugins=TRUE) const; /** Find the full path of the default plugin connected to this Viewer * * @param skip_disabled_plugins If FALSE, plugin at index 0 is always returned. If TRUE, only enabled plugins are considered * (if plugin at index 0 is disabled, plugin at index 1 will be returned (unless it, too, is disabled)) * @return The full path of the default plugin for this Viewer */ const uni_char* GetDefaultPluginViewerPath(BOOL skip_disabled_plugins=TRUE) const; UINT GetPluginViewerCount() const {OpStatus::Ignore(g_plugin_viewers->MakeSurePluginsAreDetected()); return m_plugins.GetCount();} PluginViewer* GetPluginViewer(unsigned int index) const {OpStatus::Ignore(g_plugin_viewers->MakeSurePluginsAreDetected()); return m_plugins.Get(index);} OP_STATUS SetDefaultPluginViewer(PluginViewer* plugin); OP_STATUS SetDefaultPluginViewer(unsigned int index); //PluginViewer backward compatibility functions const uni_char* PluginName() const; const uni_char* PluginFileOpenText() const; /** Connect a given plugin to this Viewer (that is, register that the given plugin can be used to view this Viewer content-type * and/or extension) * * @param plugin_viewer Pointer to a PluginViewer object (where PluginViewer::Construct(...) is called) * @return OpStatus::OK, ERR_NO_MEMORY or ERR_NULL_POINTER */ OP_STATUS ConnectToPlugin(PluginViewer* plugin_viewer); /** Disconnect a given plugin from this Viewer (that is, prevent the given plugin from viewing this Viewer content-type * and/or extension) * * @param plugin_viewer Pointer to a PluginViewer object (where PluginViewer::Construct(...) is called) * @return OpStatus::OK, ERR_NO_MEMORY or ERR_NULL_POINTER */ OP_STATUS DisconnectFromPlugin(PluginViewer* plugin_viewer); #endif // _PLUGIN_SUPPORT_ OP_STATUS CopyFrom(Viewer* source); OP_STATUS Empty(void); /** Resets the viewer to its defaults */ void ResetAction(BOOL user_def = FALSE); BOOL IsUserDefined() { return m_flags.IsSet(ViewActionFlag::USERDEFINED_VALUE); } OP_STATUS SetDescription(const uni_char* desc) { return m_description.Set(desc, 256); } const uni_char* GetDescription() { return m_description; } #ifdef WEB_HANDLERS_SUPPORT void SetWebHandlerAllowed(BOOL allowed) { m_web_handler_allowed = allowed != FALSE; } BOOL GetWebHandlerAllowed() { return m_web_handler_allowed; } #endif // WEB_HANDLERS_SUPPORT void SetAllowAnyExtension(BOOL allowed) { m_allow_any_extension = allowed != FALSE; } BOOL GetAllowAnyExtension() { return m_allow_any_extension; } /** Container format allowed for this media type. */ inline const char *AllowedContainer(); void SetAllowedContainer(ViewersEnum container) { OP_ASSERT(container < VIEWER_LAST); m_container = static_cast<unsigned int>(container); } private: OP_STATUS SetExtensions(const char* extensions); void SetAllowedContainer(unsigned int container) { SetAllowedContainer(static_cast<ViewersEnum>(container)); } public: static OP_STATUS ParseExtensions(const OpStringC& extensions, const OpStringC& separator_chars/*=UNI_L(",. ")*/, OpVector<OpString>* result_array); private: Viewers* m_owner; ViewActionFlag m_flags; OpString m_content_type_string; OpString8 m_content_type_string8; /* Optimization.. */ OpString m_extensions_string; #ifdef WEB_HANDLERS_SUPPORT OpString m_web_handler_to_open_with; #endif // WEB_HANDLERS_SUPPORT OpString m_application_to_open_with; /** In case 'Open with other application' */ OpString m_save_to_folder; /** In case 'Save to disk' */ #ifdef _PLUGIN_SUPPORT_ OpString m_preferred_plugin_path; /** Used to store plugin info from prefs, before plugins are detected and available */ #endif // _PLUGIN_SUPPORT_ OpString m_description; OpAutoVector<OpString> m_extension_list; #ifdef _PLUGIN_SUPPORT_ OpVector<PluginViewer> m_plugins; #endif // _PLUGIN_SUPPORT_ ViewAction m_action: 8; unsigned int m_content_type: 8; unsigned int m_container: 15; /**< Type can be inside this container. See ViewersEnum for values. */ #ifdef WEB_HANDLERS_SUPPORT bool m_web_handler_allowed: 1; /**< Type can be overridden by web handler. */ #endif // WEB_HANDLERS_SUPPORT bool m_allow_any_extension: 1; /**< Type bypasses strict file extension check. */ }; /** Reply structure for GetViewAction. * * The string references are only valid as long as the relevant * Viewer(s) are, so any modification to the list of Viewers will * invalidate the contents of this structure. * * The mime_type field may also have the same lifetime as the queried * MIME-type string, and should thus remain in scope for at least the * same duration as the ViewActionReply structure. */ struct ViewActionReply { /** The actual MIME-type of the Viewer. * * Will only differ from the queried MIME-type if a possible * (filename) extension was used to find a Viewer. */ OpStringC mime_type; /** The path to the plugin viewer. * * Valid if the action is VIEWER_PLUGIN or if plugin information * was explicitly requested. */ OpStringC app; /** Action to perform for the queried content type. */ ViewAction action; /** The component type required to start a plugin viewer. * * Valid if the action is VIEWER_PLUGIN or if plugin information * was explicitly requested. Defaults to COMPONENT_SINGLETON. */ OpComponentType component_type; }; class Viewers { friend class Viewer; #ifdef _PLUGIN_SUPPORT_ friend class PluginViewer; friend class PluginViewers; #endif // _PLUGIN_SUPPORT_ public: Viewers(); virtual ~Viewers(); OP_STATUS ConstructL(); OP_STATUS ReadViewersL(); #if defined PREFS_HAS_PREFSFILE && defined PREFS_WRITE void WriteViewersL(); #endif // defined PREFS_HAS_PREFSFILE && defined PREFS_WRITE OP_STATUS AddViewer(ViewAction action, URLContentType content_type/*=URL_UNDETERMINED_CONTENT*/, const OpStringC& content_type_string, const OpStringC& extensions_string, ViewActionFlag::ViewActionFlagType flags=ViewActionFlag::NO_FLAGS, const OpStringC& application_to_open_with=UNI_L(""), const OpStringC& save_to_folder=UNI_L("") #ifdef _PLUGIN_SUPPORT_ , const OpStringC& preferred_plugin_path=UNI_L("") #endif // _PLUGIN_SUPPORT_ , const OpStringC& description=UNI_L("") ); /** Add a viewer to the list of known viewers, and takes ownership of it. The viewer will also be connected to * matching plugins. * * @param viewer Pointer to Viewer object to add to the list of known viewers * @return OpStatus::OK, ERR_NO_MEMORY or ERR (in case a different viewer object with the same content-type * already exists in the list. The new viewer will not be added to the list, and ownership will not be claimed) */ OP_STATUS AddViewer(Viewer* viewer); void DeleteViewer(Viewer* viewer); Viewer* FindViewerByMimeType(const OpStringC mimetype); Viewer* FindViewerByMimeType(const OpStringC8 mimetype); OP_STATUS FindViewerByExtension(const OpStringC& extension, Viewer*& ret_viewer); Viewer* FindViewerByExtension(const OpStringC& extension) {Viewer* v; if (FindViewerByExtension(extension, v)!=OpStatus::OK) v=NULL; return v;} OP_STATUS FindViewerByExtension(const OpStringC8& extension, Viewer*& ret_viewer); Viewer* FindViewerByExtension(const OpStringC8& extension) {Viewer* v; if (FindViewerByExtension(extension, v)!=OpStatus::OK) v=NULL; return v;} OP_STATUS FindAllViewersByExtension(const OpStringC& extension, OpVector<Viewer>* result_array); OP_STATUS FindViewerByFilename(const OpStringC& filename, Viewer*& ret_viewer); Viewer* FindViewerByFilename(const OpStringC& filename) {Viewer* v; if (FindViewerByFilename(filename, v)!=OpStatus::OK) v=NULL; return v;} OP_STATUS FindViewerByFilename(const OpStringC8& filename, Viewer*& ret_viewer); Viewer* FindViewerByFilename(const OpStringC8& filename) {Viewer* v; if (FindViewerByFilename(filename, v)!=OpStatus::OK) v=NULL; return v;} OP_STATUS FindViewerByURL(URL& url, Viewer*& ret_viewer, BOOL update_url_contenttype=TRUE); OP_STATUS GetAppAndAction(URL& url, ViewAction& action, const uni_char*& app, BOOL update_url_contenttype=TRUE); BOOL IsNativeViewerType(const OpStringC8& content_type); /** Create an iterator for retrieving Viewers. The created iterator is assigned to the given argument * * IMPORTANT: The caller is responsible for delete-ing the resulting iterator. * If any error is encountered, the given argument is set to NULL. * If OOM is encountered, ERR_NO_MEMORY is returned. * If the viewers list is empty, ERR is returned. * * @param iterator The created iterator (or NULL, on error) is assigned to this argument * @return OpStatus::OK, ERR_NO_MEMORY, ERR. */ OP_STATUS CreateIterator(ChainedHashIterator*& iterator); /** Return the next Viewer object from the given iterator (originally retrieved from CreateIterator()) * * @param iterator The iterator from which to retrieve Viewer object. * @return The next Viewer object from the given iterator, (NULL if no more Viewer objects) */ Viewer* GetNextViewer(ChainedHashIterator* iterator); UINT GetViewerCount() {return m_viewer_list.GetCount();} void OnViewerChanged(const Viewer* v) {g_main_message_handler->PostMessage(MSG_VIEWERS_CHANGED, MH_PARAM_1(v), 0);} /** Core will not notify about viewer changes. This function is here to make platform code notify other platform code about changes */ #ifdef WEB_HANDLERS_SUPPORT /** * Finds web application viewer by url if there's one. * * @param url to find a web application viewer by * @param ret_viewer returned viewer if found or NULL * * @return OpStatus::ERR_NO_MEMORY in case of OOM. OpStatus::OK otherwise. */ OP_STATUS FindViewerByWebApplication(const OpStringC& url, Viewer*& ret_viewer); #endif // WEB_HANDLERS_SUPPORT public: static const char* GetContentTypeString(URLContentType content_type); static const char* GetDefaultContentTypeStringFromExt(const OpStringC& ext); static const char* GetDefaultContentTypeStringFromExt(const OpStringC8& ext); /** Get the configured action for a URL and/or MIME-type. * * Queries the Viewers database for a Viewer configured to handle * content with a specified MIME-type, or a Viewer configured to * handle content with a specified file extension. * * @param url URL used to determine file extension. * @param mime_type MIME-type to query. Can be empty - in which * case a file extension will be used instead. * @param reply Reply structure - @see ViewActionReply. * @param want_plugin TRUE if the reply should contain plugin * information regardless of action type. * @param check_octetstream TRUE if MIME-types typically used for * binary data should be ignored and used * the file extension instead. * * @return OpStatus::ERR_NO_MEMORY in case of OOM. OpStatus::OK otherwise. */ static OP_STATUS GetViewAction(URL& url, const OpStringC mime_type, ViewActionReply& reply, BOOL want_plugin, BOOL check_octetstream=FALSE); static ViewAction GetDefaultAction(URLContentType content_type); static ViewAction GetDefaultAction(const char* type); private: void DeleteAllViewers(); OP_STATUS ReadViewers(); OP_STATUS ImportGeneratedViewersArray(); #ifdef _PLUGIN_SUPPORT_ void RemovePluginViewerReferences(); #endif void OnViewerAdded(const Viewer* v) {g_main_message_handler->PostMessage(MSG_VIEWERS_ADDED, MH_PARAM_1(v), 0);} void OnViewerDeleted(const Viewer* v) {g_main_message_handler->PostMessage(MSG_VIEWERS_DELETED, MH_PARAM_1(v), 0);} public: class Viewer8HashFunctions : public OpHashFunctions { public: // Inherited interfaces -- virtual UINT32 Hash(const void* k); virtual BOOL KeysAreEqual(const void *key1, const void *key2); }; private: OpAutoStringHashTable<Viewer> m_viewer_list; //Hashed by 16-bit string OpHashTable m_viewer_list8; //Hashed by 8-bit string Viewer8HashFunctions viewer8_hash_func; #ifndef HAS_COMPLEX_GLOBALS void init_defaultOperaViewerTypes(); #else static const #endif // HAS_COMPLEX_GLOBALS ViewerTypes defaultOperaViewerTypes[defaultOperaViewerTypes_SIZE]; }; inline const char *Viewer::AllowedContainer() { return g_viewers->defaultOperaViewerTypes[m_container].type; } #endif // _VIEWERS_
#pragma once #include "Rect.h" namespace cvfn { /* ref class Size2D; interface class IFrameProcessor; public interface class IVideoProcessor { public: Size2D^ getFrameSize(); IFrameProcessor^ getFrameProcessor(); void setFrameProcessor( IFrameProcessor^ fp ); System::String^ getDisplayOutput(); }; */ }
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmLinkLibrariesCommand.h" #include "cmExecutionStatus.h" #include "cmMakefile.h" bool cmLinkLibrariesCommand(std::vector<std::string> const& args, cmExecutionStatus& status) { if (args.empty()) { return true; } cmMakefile& mf = status.GetMakefile(); // add libraries, note that there is an optional prefix // of debug and optimized than can be used for (auto i = args.begin(); i != args.end(); ++i) { if (*i == "debug") { ++i; if (i == args.end()) { status.SetError("The \"debug\" argument must be followed by " "a library"); return false; } mf.AppendProperty("LINK_LIBRARIES", "debug"); } else if (*i == "optimized") { ++i; if (i == args.end()) { status.SetError("The \"optimized\" argument must be followed by " "a library"); return false; } mf.AppendProperty("LINK_LIBRARIES", "optimized"); } mf.AppendProperty("LINK_LIBRARIES", *i); } return true; }
#include <iostream> #include <vector> #include <algorithm> int main() { int numberTolook = 0; std::cin >> numberTolook; unsigned long row = 0; std::cin >> row; unsigned long col = 0; std::cin >> col; int number = 0; std::vector<std::vector<int>> arr; //arr.resize(row, std::vector<int>(col, number)); for ( int i = 0; i < row; ++i ) { std::vector<int> vt; for ( int j = 0; j < col; ++j ) { std::cin >> number; vt.push_back(number); } arr.push_back(vt); } int countFindNumber = 0; for ( int i = 0; i < row; ++i ) { for ( int l = 0; l < col; ++l ) { if (arr[i][l] == numberTolook) { { std::cout << i << l << std::endl; countFindNumber++; } } } } if (countFindNumber == 0) { std::cout << "Number not found" << std::endl; } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** $Id$ ** ** Copyright (C) 1995-2007 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #include "MacOpPlatformViewers.h" #include "adjunct/quick/Application.h" #include "adjunct/quick/data_types/OpenURLSetting.h" OP_STATUS OpPlatformViewers::Create(OpPlatformViewers** new_platformviewers) { OP_ASSERT(new_platformviewers != NULL); *new_platformviewers = new MacOpPlatformViewers(); if(*new_platformviewers == NULL) return OpStatus::ERR_NO_MEMORY; return OpStatus::OK; } OP_STATUS MacOpPlatformViewers::OpenInDefaultBrowser(const uni_char* url) { return OpStatus::ERR; } OP_STATUS MacOpPlatformViewers::OpenInOpera(const uni_char* url) { return OpStatus::ERR_NOT_SUPPORTED; }
#include<stdio.h> #include<conio.h> int main() { int count,c; for(count=1;count<=3;count++) { for(c=1;c<=count;c++) { printf("*"); } printf("\n"); } getch(); return 0; }
// // Created by Israel on 1/18/2019. // #include <jni.h> #include "Box2D/Box2D.h" extern "C" JNIEXPORT jlong JNICALL Java_KittyEngine_Engine_Physics_KFixture_getNext(JNIEnv *env, jobject /* this */, jlong fixturePtr) { b2Fixture* fixture = reinterpret_cast<b2Fixture*>(fixturePtr); return reinterpret_cast<jlong>(fixture->GetNext()); }
#include <iostream> #include <vector> #include <algorithm> #include <fstream> #include <queue> #include <unordered_set> #define INT_MIN (1<<31) #define INT_MAX (~INT_MIN) #define UNREACHABLE (INT_MAX>>2) using namespace std; ifstream fin("280_input.txt"); #define cin fin int main() { int n, m; cin >> n; while (n) { vector<vector<int>> f(n + 1, vector<int>(n + 1, UNREACHABLE)); int start = 0; cin >> start; while (start) { int end; cin >> end; while (end) { f[start][end] = 1; cin >> end; } cin >> start; } for (int k = 1; k <= n; k++) for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) f[i][j] = min(f[i][j], f[i][k] + f[k][j]); int num_test; cin >> num_test; for (int i = 0; i < num_test; i++) { int cur_test, total_unreachable = 0; cin >> cur_test; for (int i = 1; i <= n; i++) if (f[cur_test][i] == UNREACHABLE) total_unreachable++; cout << total_unreachable; for (int i = 1; i <= n; i++) if (f[cur_test][i] == UNREACHABLE) cout << ' ' << i; cout << endl; } cin >> n; } }
#include<stdio.h> int a,b,c,d; main() { scanf("%d %d %d",&a,&b,&c); d=a*b-c; printf("%d",d); }
#include "SmartPlayer.h" void SmartPlayer::Update() { if (!inGame) return; field->Update(); if (moveLeft > 0) { field->MoveLeft(); if (--moveLeft == 0) moveLeft = -1; } if (moveRight > 0) { field->MoveRight(); if (--moveRight == 0) moveRight = -1; } if (!field->IsMoving()) { for (int j = 0; j < field->FIELD_WIDTH; j++) { for (int i = 0; i < field->FIELD_HEIGHT; i++) { if (GetSymbol(i, j) == 0) { if (i > max_depth) { max_depth = i; column = j; } } else { break; } } } if (column <= 4) { moveLeft = 5 - column; moveRight = 0; } else { moveLeft = 0; moveRight = column - 5; } max_depth = 0; column = 0; } }
#ifndef CHATY_NONCOPYABLE_H #define CHATY_NONCOPYABLE_H namespace CHATY_NONCOPYABLE_H { class noncopyable { public: noncopyable() = default; ~noncopyable() = default; private: noncopyable(const noncopyable &) = delete; void operator=(const noncopyable &) = delete; }; } #endif // CHATY_NONCOPYABLE_H
#include <iostream> #include <SDL/SDL_opengl.h> #include "draw.h" using namespace std; void drawRect(float x, float y, float w, float h){ glBegin(GL_TRIANGLES); glVertex2f(x - w, y - h); glVertex2f(x - w, y + h); glVertex2f(x + w, y + h); glVertex2f(x + w, y + h); glVertex2f(x + w, y - h); glVertex2f(x - w, y - h); glEnd(); }
#include "GetChatRoomCmd.h" GetChatRoomCmd::GetChatRoomCmd(int numRequest, const std::optional<std::string>& error, const std::string& body) : BaseCmd(numRequest, error, body) {} void GetChatRoomCmd::execute(std::shared_ptr<CallbacksHolder> holder) { std::shared_ptr<BaseObject> chatRoom = std::make_shared<ChatRoom>(); chatRoom->decode(body); auto func = holder->getCallback(Commands::GetSelectChatRoom, numRequest).get(); (*func)(chatRoom, error); }
#ifndef AFX_SCENE_H_ #define AFX_SCENE_H_ #include <stdio.h> #include <vector> #include <string> using namespace std; class Textures; class Model { class Vec3 { public: double ptr[3]; void set(double *v) { for (size_t i = 0; i<3; i++) ptr[i] = v[i]; } inline double& operator[](size_t index) { return ptr[index]; } }; public: string objFile_; double angle_; Vec3 scale_; Vec3 rotate_; Vec3 translate_; size_t texIndex_; //record the index in texList_ }; class TexImage { public: size_t texID_; //use for texObject when generating texture in main.cpp (not cube map) string imageFile; //name of image file TexImage() {} TexImage(const char* s) { imageFile = s; } }; class Textures { public: size_t texID_; //use for texObject when generating texture in main.cpp (cube map) int technique_; size_t imageTotal_; vector<TexImage> imageList_; //list of image file names }; class Scene { public: size_t texTotal_; vector<Textures> texList_; size_t modelTotal_; vector<Model> modelList_; //list of models Scene(); Scene(const char* sceneFile); ~Scene(); void loadScene(const char* sceneFile); Model& searchModel(const string modelName); }; #endif
/* * File: Enemey.cpp * Author: mohammedheader * * Created on November 24, 2014, 4:32 PM */ #include "HelloWorldScene.h" #include "Enemy.h" USING_NS_CC; Enemy* Enemy::create(HelloWorld* game) { Enemy *enemy = new (std::nothrow) Enemy(); if (enemy && enemy->init(game)) { enemy->autorelease(); return enemy; } CC_SAFE_DELETE(enemy); return nullptr; } Enemy* Enemy::init(HelloWorld* game) { maxHp = 40; currentHp = maxHp; active = false; walkingSpeed = 0.5; mySprite = Sprite::create("enemy.png"); addChild(mySprite); theGame = game; Waypoint* waypoint = game->getWaypoints().back(); destinationWaypoint = waypoint->getNextWayPoint(); myPosition = waypoint->getMyPosition(); mySprite->setPosition(myPosition); game->addChild(this); scheduleUpdate(); return this; } void Enemy::update(float dt) { if(!active) return; if(theGame->isCirclesCollide(Circle{myPosition, 1}, Circle{destinationWaypoint->getMyPosition(), 1})){ if(destinationWaypoint->getNextWayPoint()){ destinationWaypoint = destinationWaypoint->getNextWayPoint(); }else{ // theGame->getHpDamage(); remove(); } } Vec2 targetPoint = destinationWaypoint->getMyPosition(); Vec2 normalized = (targetPoint - myPosition).getNormalized(); //Vec2(targetPoint.x-myPosition.x,targetPoint.y-myPosition.y).getNormalized(); normalized *= walkingSpeed; myPosition = myPosition + normalized; mySprite->setRotation(CC_RADIANS_TO_DEGREES(atan2(normalized.y,-normalized.x))); mySprite->setPosition(myPosition); } void Enemy::doActivate(float dt) { active = true; } void Enemy::remove() { theGame->getEnemies().eraseObject(this,false); removeFromParentAndCleanup(true); theGame->enemyGotKilled(); }
#include <Poco/Exception.h> #include <Poco/NumberParser.h> #include <Poco/StringTokenizer.h> #include "util/TimespanParser.h" using namespace std; using namespace Poco; using namespace BeeeOn; bool TimespanParser::tryParseUnit(const string &input, Timespan::TimeDiff &multiplier) { if (input == "d") multiplier = Timespan::DAYS; else if (input == "h") multiplier = Timespan::HOURS; else if (input == "m") multiplier = Timespan::MINUTES; else if (input == "s") multiplier = Timespan::SECONDS; else if (input == "ms") multiplier = Timespan::MILLISECONDS; else if (input == "us" || input.empty()) multiplier = 1; else return false; return true; } bool TimespanParser::tryParse(const string &input, Timespan &timespan) { StringTokenizer toks(input, " \t", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); if (toks.count() != 1 && toks.count() != 2) return false; int64_t span; if (!NumberParser::tryParse64(toks[0], span)) return false; if (toks.count() == 1) { timespan = span; return true; } Timespan::TimeDiff multiplier = 0; if (!tryParseUnit(toks[1], multiplier)) return false; timespan = span * multiplier; return true; } Timespan TimespanParser::parse(const string &input) { StringTokenizer toks(input, " \t", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); if (toks.count() == 1) return NumberParser::parse64(toks[0]); if (toks.count() == 2) { Timespan::TimeDiff multiplier = 0; if (!tryParseUnit(toks[1], multiplier)) throw SyntaxException("invalid timespan unit: " + toks[1].substr(0, 5)); return NumberParser::parse64(toks[0]) * multiplier; } throw SyntaxException("unexpected timespan input"); }
#ifndef UPDATE_RAY_HPP_ #define UPDATE_RAY_HPP_ #include <Eigen/Core> #include "affine_hull.hpp" namespace FC { enum class RAY_DIR {FROM_DRIVER, TO_DRIVER}; template <RAY_DIR ray_dir> struct compute_ray; /** @param lambda vector of at least ah.size() elements */ template <RAY_DIR ray_dir, typename PointCloud, typename Float> void update_ray(affine_hull<PointCloud> const& ah, Eigen::Matrix<Float, Eigen::Dynamic, 1> const& x, Eigen::Matrix<Float, Eigen::Dynamic, 1> & lambda, Eigen::Matrix<Float, Eigen::Dynamic, 1> & driver, Eigen::Matrix<Float, Eigen::Dynamic, 1> & ray) { using size_type = typename affine_hull<PointCloud>::size_type; ah.project(x, lambda.head(ah.size())); driver.setZero(); auto m_it = ah.begin(); for (size_type i = 0; i < ah.size(); ++i) driver += lambda[i] * ah.pc()[*m_it++]; compute_ray<ray_dir>::exec(x, driver, ray); } template <> struct compute_ray<RAY_DIR::FROM_DRIVER> { template <typename Float> static void exec(Eigen::Matrix<Float, Eigen::Dynamic, 1> const& x, Eigen::Matrix<Float, Eigen::Dynamic, 1> const& driver, Eigen::Matrix<Float, Eigen::Dynamic, 1> & ray) { ray = x - driver; } }; template <> struct compute_ray<RAY_DIR::TO_DRIVER> { template <typename Float> static void exec(Eigen::Matrix<Float, Eigen::Dynamic, 1> const& x, Eigen::Matrix<Float, Eigen::Dynamic, 1> const& driver, Eigen::Matrix<Float, Eigen::Dynamic, 1> & ray) { ray = driver - x; } }; } // namespace FC #endif // UPDATE_RAY_HPP_
#include "List.h" #include <cstdlib> #include <iostream> #include <assert.h> #include "List.h" //to make sure header file got copied over using namespace std; #define NDEBUG //to enabled usage of assert List::List() { //default constructor setting all data members to null head = NULL; current = NULL; temp = NULL; } void List::AddNode(int addData) { //adding new nodes to make a linked list nodePointer n = new node; //making new node to allocate to node pointer n n->next = NULL; //the next in new node is pointed to null n->data = addData; //data in the new node is set to integer addData if (head != NULL) { //if list is already created current = head; //advance current pointer to the last node while (current->next != NULL) { //if next node isnt the end current = current->next; //point current to next node } current->next = n; //connect last node to new node we created } else { head = n; //make new node be the front } } void List::DeleteNode(int delData) { //function to delete nodes we dont want nodePointer delPtr = NULL; //making new node pointer delPtr have nothing inside temp = head; //temporary node points to head/first node current = head; //current node points to head/first node while (current != NULL && current->data != delData) { //will go to the end or find the node we want to delete temp = current; //temporary node is assigned to current node current = current->next; //current node is pointed to next node } if (current == NULL) { //id current is null then we did not find what we were looking for cout << delData << " was not in the list" << endl; delete delPtr; //will not take up more memory } else { //if deleted one was found delPtr = current; current = current->next; //patching up list to keep list going temp->next = current; //patching up list to keep list going if (delPtr == head) { //if the node we want to delete is the first node head = head->next; //point first node to the next node temp = NULL; } delete delPtr; //deletes memory of delPtr cout << "The value " << delData << " was deleted" << endl; } } int List::GetNth(int index) { //takes a linked list and an integer index and returns the data value stored in the node at that index position current = head; //sets current node to first node int currIndex = 0; //integer current index is 0 so starting at the beginning while (current != NULL) { //if there is something in current meaning if the list hasnt ended yet if (currIndex == index) { //if the current index number is equal to the number I put when setting parameter return (current->data); //store the current value in the current node into its data } else { currIndex++; //increase current index by 1 current = current->next; //set current node to the next node } } assert(0); //If it is not, GetNth() should assert() fail (or you could implement some other error case strategy). } void List::Split() { //which given a list, splits it into two sublists — one for the front half, and one for the back half. //first have to count how mny elements are in linked list int paul = 0; //sets integer paul to 0 current = head; //sets current node to head the beginning of list while (current != NULL) { //if there is something in the list meaning its not at its end paul++; //paul will improve by 1 current = current->next; //current node will be pointed to the next node } cout << "the number of elements in the list are " << paul << endl; //print out pauls value node* us; //hint from class node* sl; us = head; int splitat; if (paul % 2 == 0) { splitat = paul/2; int count = count - splitat; } else { splitat = paul/2 + 1; } int nc = 1; while (nc != splitat) { us = us ->next; nc++; sl = us->next; } } void List::PrintList() { //to print out the list current = head; //current is the assigned to the front of the list while (current != NULL) { //makes sure theres something in the list cout << current->data << endl; current = current->next; } }
#ifndef __ZATOMIC_HPP__ #define __ZATOMIC_HPP__ #include <stdint.h> namespace atomic_impl { typedef enum memory_order { memory_order_relaxed, memory_order_consume, memory_order_acquire, memory_order_release, memory_order_acq_rel, memory_order_seq_cst } memory_order; #if defined( _MSC_VER ) namespace detail { template<int param> struct msvc_fetch_add { }; template<> struct msvc_fetch_add<4> { template<typename T, typename V> static T call(T* storage, V v) { return _InterlockedAdd((volatile long*)storage, (long)v); } }; template<> struct msvc_fetch_add<8> { template<typename T, typename V> static T call(T* storage, V v) { return InterlockedAdd64((volatile LONGLONG*)storage, (LONGLONG)v); } }; template<int param> struct msvc_cas { }; template<> struct msvc_cas<4> { template<typename T, typename V> static bool call(T* storage, T* exp, V v) { unsigned long rc=InterlockedCompareExchange((volatile unsigned long *)storage, v, *exp); if (rc == *exp) return true; *exp = rc; return false; } }; template<> struct msvc_cas<8> { template<typename T, typename V> static bool call(T* storage, T* exp, V v) { __int64 rc = InterlockedCompareExchange64((__int64 volatile *)storage, v, *exp); if (rc == *exp) return true; *exp = rc; return false; } }; } template<typename T,typename V> static T fetch_add(T* storage, V v) { return atomic_impl::detail::msvc_fetch_add<sizeof(T)>::call(storage,v); } template<typename T, typename V> static bool cas(T* storage, T* exp, V v) { return atomic_impl::detail::msvc_cas<sizeof(T)>::call(storage, exp, v); } #elif defined( __IBMCPP__ ) && defined( __powerpc ) #include<stdint.h> extern "builtin" void __lwsync(void); extern "builtin" void __isync(void); extern "builtin" int __fetch_and_add(volatile int32_t* addr, int val); extern "builtin" int64_t __fetch_and_addlp(volatile int64_t* addr, int64_t val); struct local_sync { local_sync() { __lwsync(); } ~local_sync() { __isync(); } }; template<int param> struct xlc_fetch_add { }; template<> struct xlc_fetch_add<4> { template<typename T,typename V> static T call(T* storage, V v) { local_sync _1; return __fetch_and_add (storage, v); } }; template<> struct xlc_fetch_add<8> { template<typename T,typename V> static T call(T* storage, V v) { local_sync _1; return __fetch_and_addlp (storage, v); } }; template<typename T,typename V> static T fetch_add(T* storage, V v) { return atomic_impl::xlc_fetch_add<sizeof(T)>::call(storage,v); } #elif defined( __GNUC__ ) template<typename T,typename V> static void store(T* storage,V v) { __atomic_store_n(storage,v,memory_order_release); } template<typename T> static T load(T* storage) { return __atomic_load_n(storage, memory_order_acquire); } template<typename T,typename V> static T fetch_add(T* storage, V v) { return __sync_fetch_and_add (storage, v); } template<typename T,typename V> static bool cas(T* storage, T* exp, V v) { T ov=__sync_val_compare_and_swap(storage, *exp, v); if(ov==*exp) return true; *exp=ov; return false; } #else #error No ztomic operations implemented for this platform, sorry! #endif template<typename T> struct type_map {}; template<> struct type_map<uint32_t> { typedef int32_t type; }; template<> struct type_map<int32_t> { typedef int32_t type; }; template<> struct type_map<uint64_t> { typedef int64_t type;}; template<> struct type_map<int64_t> { typedef int64_t type;}; } struct ztomic { template<typename V> static typename atomic_impl::type_map<V>::type cast(V v) { return static_cast<typename atomic_impl::type_map<V>::type>(v); } template<typename T,typename V> static T fetch_add(T *storage, V v) { return atomic_impl::fetch_add (storage, cast(v)); } template<typename T,typename V> static T fetch_sub(T* storage, V v) { return ztomic::fetch_add(storage,-v); } template<typename T,typename V> static T add_fetch(T* storage, V v) { return ztomic::fetch_add(storage,v)+cast(v); } template<typename T,typename V> static T sub_fetch(T* storage, V v) { return ztomic::fetch_add(storage,-v)-cast(v); } template<typename T,typename V> static void store(T* storage,V v) { return atomic_impl::store(storage,v); } template<typename T> static T load(T* storage) { return atomic_impl::load(storage); } template<typename T,typename V> static bool cas(T* storage, T* exp, V v) { return atomic_impl::cas(storage,exp,v); } }; #endif
#include <wire.h> void Wire::set(bool value) { if (signal != value) { signal = value; for_each(listers.begin(), listers.end(), [](WireListner *elm) { elm->stateChanged(); }); } }
//=====-- OR1KSubtarget.h - Define Subtarget for the OR1K -----*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares the OR1K specific subclass of TargetSubtarget. // //===----------------------------------------------------------------------===// #ifndef OR1KSUBTARGET_H #define OR1KSUBTARGET_H #include "llvm/Target/TargetSubtargetInfo.h" #include "llvm/Target/TargetMachine.h" #include <string> #define GET_SUBTARGETINFO_HEADER #include "OR1KGenSubtargetInfo.inc" namespace llvm { class OR1KSubtarget : public OR1KGenSubtargetInfo { virtual void anchor(); bool HasMul; bool HasDiv; bool HasRor; bool HasCmov; public: /// This constructor initializes the data members to match that /// of the specified triple. /// OR1KSubtarget(const std::string &TT, const std::string &CPU, const std::string &FS); /// ParseSubtargetFeatures - Parses features string setting specified /// subtarget options. Definition of function is auto generated by tblgen. void ParseSubtargetFeatures(StringRef CPU, StringRef FS); bool hasMul() const { return HasMul; } bool hasDiv() const { return HasDiv; } bool hasRor() const { return HasRor; } bool hasCmov() const { return HasCmov; } }; } // End llvm namespace #endif
#include <stdio.h> #include <octomap/octomap.h> #include <octomap/math/Utils.h> #include "testing.h" using namespace std; using namespace octomap; using namespace octomath; int main(int /*argc*/, char** /*argv*/) { OcTree tree (0.05); // point3d origin (10.01, 10.01, 10.02); point3d origin (0.01f, 0.01f, 0.02f); point3d point_on_surface (2.01f, 0.01f, 0.01f); cout << "Generating sphere at " << origin << " ..." << endl; unsigned sphere_beams = 500; double angle = 2.0*M_PI/double(sphere_beams); Pointcloud p; for (unsigned i=0; i<sphere_beams; i++) { for (unsigned j=0; j<sphere_beams; j++) { p.push_back(origin+point_on_surface); point_on_surface.rotate_IP (0,0,angle); } point_on_surface.rotate_IP (0,angle,0); } tree.insertPointCloud(p, origin); cout << "Writing to sphere.bt..." << endl; EXPECT_TRUE(tree.writeBinary("sphere.bt")); // ----------------------------------------------- cout << "Casting rays in sphere ..." << endl; OcTree sampled_surface (0.05); point3d direction = point3d (1.0,0.0,0.0); point3d obstacle(0,0,0); unsigned int hit (0); unsigned int miss (0); unsigned int unknown (0); double mean_dist(0); for (unsigned i=0; i<sphere_beams; i++) { for (unsigned j=0; j<sphere_beams; j++) { if (!tree.castRay(origin, direction, obstacle, false, 3.)) { // hit unknown if (!tree.search(obstacle)) unknown++; else miss++; } else { hit++; mean_dist += (obstacle - origin).norm(); sampled_surface.updateNode(obstacle, true); } direction.rotate_IP (0,0,angle); } direction.rotate_IP (0,angle,0); } cout << "Writing sampled_surface.bt" << endl; EXPECT_TRUE(sampled_surface.writeBinary("sampled_surface.bt")); mean_dist /= (double) hit; std::cout << " hits / misses / unknown: " << hit << " / " << miss << " / " << unknown << std::endl; std::cout << " mean obstacle dist: " << mean_dist << std::endl; EXPECT_NEAR(mean_dist, 2., 0.05); EXPECT_EQ(hit, (sphere_beams*sphere_beams)); EXPECT_EQ(miss, 0); EXPECT_EQ(unknown, 0); // ----------------------------------------------- cout << "generating single rays..." << endl; OcTree single_beams(0.03333); int num_beams = 17; float beamLength = 10.0f; point3d single_origin (1.0f, 0.45f, 0.45f); point3d single_origin_top (1.0f, 0.45f, 1.0); point3d single_endpoint(beamLength, 0.0f, 0.0f); for (int i=0; i<num_beams; i++) { for (int j=0; j<num_beams; j++) { if (!single_beams.insertRay(single_origin, single_origin+single_endpoint)) { cout << "ERROR while inserting ray from " << single_origin << " to " << single_endpoint << endl; } single_endpoint.rotate_IP (0,0,DEG2RAD(360.0/num_beams)); } single_endpoint.rotate_IP (0,DEG2RAD(360.0/num_beams),0); } cout << "done." << endl; cout << "writing to beams.bt..." << endl; EXPECT_TRUE(single_beams.writeBinary("beams.bt")); ////// more tests from unit_tests.cpp: double res = 0.1; double res_2 = res/2.0; OcTree cubeTree(res); // fill a cube with "free", end is "occupied": for (float x=-0.95f; x <= 1.0f; x+=float(res)){ for (float y=-0.95f; y <= 1.0f; y+= float(res)){ for (float z=-0.95f; z <= 1.0f; z+= float(res)){ if (x < 0.9){ EXPECT_TRUE(cubeTree.updateNode(point3d(x,y,z), false)); } else{ EXPECT_TRUE(cubeTree.updateNode(point3d(x,y,z), true)); } } } } // fill some "floor": EXPECT_TRUE(cubeTree.updateNode(res_2,res_2,-res_2, true)); EXPECT_TRUE(cubeTree.updateNode(3*res_2,res_2,-res_2, true)); EXPECT_TRUE(cubeTree.updateNode(-res_2,res_2,-res_2, true)); EXPECT_TRUE(cubeTree.updateNode(-3*res_2,res_2,-res_2, true)); cubeTree.writeBinary("raycasting_cube.bt"); origin = point3d(0.0f, 0.0f, 0.0f); point3d end; // hit the corner: direction = point3d(0.95f, 0.95f, 0.95f); EXPECT_TRUE(cubeTree.castRay(origin, direction, end, false)); EXPECT_TRUE(cubeTree.isNodeOccupied(cubeTree.search(end))); std::cout << "Hit occupied voxel: " << end << std::endl; direction = point3d(1.0, 0.0, 0.0); EXPECT_TRUE(cubeTree.castRay(origin, direction, end, false)); EXPECT_TRUE(cubeTree.isNodeOccupied(cubeTree.search(end))); std::cout << "Hit occupied voxel: " << end << std::endl; EXPECT_NEAR(1.0, (origin - end).norm(), res_2); // hit bottom: origin = point3d(float(res_2), float(res_2), 0.5f); direction = point3d(0.0, 0.0, -1.0f); EXPECT_TRUE(cubeTree.castRay(origin, direction, end, false)); EXPECT_TRUE(cubeTree.isNodeOccupied(cubeTree.search(end))); std::cout << "Hit voxel: " << end << std::endl; EXPECT_FLOAT_EQ(origin(0), end(0)); EXPECT_FLOAT_EQ(origin(1), end(1)); EXPECT_FLOAT_EQ(-res_2, end(2)); // hit boundary of unknown: origin = point3d(0.0f, 0.0f, 0.0f); direction = point3d(0.0f, 1.0f, 0.0f); EXPECT_FALSE(cubeTree.castRay(origin, direction, end, false)); EXPECT_FALSE(cubeTree.search(end)); std::cout << "Boundary unknown hit: " << end << std::endl; // hit boundary of octree: EXPECT_FALSE(cubeTree.castRay(origin, direction, end, true)); EXPECT_FALSE(cubeTree.search(end)); EXPECT_FLOAT_EQ(end.x(), res_2); EXPECT_FLOAT_EQ(end.y(), float(32768*res-res_2)); EXPECT_FLOAT_EQ(end.z(), res_2); direction = point3d(-1.0f, 0.0f, 0.0f); EXPECT_FALSE(cubeTree.castRay(origin, direction, end, true)); EXPECT_FALSE(cubeTree.search(end)); EXPECT_FLOAT_EQ(end.x(), float(-32767*res-res_2)); EXPECT_FLOAT_EQ(end.y(), res_2); EXPECT_FLOAT_EQ(end.z(), res_2); // test maxrange: EXPECT_FALSE(cubeTree.castRay(origin, direction, end, true, 0.9)); std::cout << "Max range endpoint: " << end << std::endl; OcTreeNode* endPt = cubeTree.search(end); EXPECT_TRUE(endPt); EXPECT_FALSE(cubeTree.isNodeOccupied(endPt)); double dist = (origin - end).norm(); EXPECT_NEAR(0.9, dist, res); std::cout << "Test successful\n"; return 0; }
#ifndef VECTOR_H #define VECTOR_H #include <cassert> #include <cstring> template<typename T> struct vector { using value_type = T; vector(); vector(value_type); vector(const vector&); ~vector(); vector& operator=(const vector& other); value_type& operator[](size_t n) { return array[n]; } value_type& ref_counter() { return array[-2]; } value_type& size() { return array[-1]; } const value_type& operator[](size_t n) const { return array[n]; } const value_type& ref_counter() const { return array[-2]; } const value_type& size() const { return array[-1]; } void shrink_to_fit(); void ensure_capacity(size_t new_size); void detach(); void out() const; // debugging template <typename U> friend void swap(vector<U>& a, vector<U>& b); private: value_type* array; static constexpr size_t OFFSET { 2 }; void allocate(size_t new_size); void quick_allocate(size_t new_size); void quick_copy(const vector& other); }; template <typename T> vector<T>::vector() { allocate(0); // This will also zero-initialize size and sign ref_counter() = 1; } template <typename T> vector<T>::vector(value_type e) { allocate(1); // This will also zero-initialize sign size() = 1; ref_counter() = 1; array[0] = e; } template <typename T> void vector<T>::quick_copy(const vector& other) { array = other.array; ++ref_counter(); } template <typename T> vector<T>::vector(const vector& other) { quick_copy(other); } template <typename T> vector<T>& vector<T>::operator=(const vector& other) { quick_copy(other); return *this; } template <typename T> vector<T>::~vector() { if (--ref_counter() == 0) { // std::cout << "delete at " << array << "\n"; delete[](array - OFFSET); } } template <typename T> void vector<T>::allocate(size_t new_size) { array = new value_type[new_size + OFFSET] { } + OFFSET; // std::cout << "allocate at " << array << "\n"; } template <typename T> void vector<T>::quick_allocate(size_t new_size) { array = new value_type[new_size + OFFSET] + OFFSET; // std::cout << "quick allocate at " << array << "\n"; } template <typename T> void vector<T>::detach() { if (ref_counter() == 1) return; --ref_counter(); value_type* old_array { array }; size_t size_ { size() }; quick_allocate(size_); memcpy(array - 1, old_array - 1, sizeof(value_type) * (size_ + 1)); ref_counter() = 1; } template <typename T> void vector<T>::shrink_to_fit() { assert(ref_counter() == 1); size_t size_ { size() }; while (size_ > 1 && array[size_ - 1] == 0u) --size_; if (size_ == size()) return; value_type* old_array { array }; quick_allocate(size_); memcpy(array - OFFSET, old_array - OFFSET, sizeof(value_type) * (size_ + OFFSET)); // std::cout << "delete[s] at " << old_array << "\n"; delete[](old_array - OFFSET); size() = size_; } template <typename T> void vector<T>::ensure_capacity(size_t new_size) { assert(ref_counter() == 1); if (size() >= new_size) return; size_t size_ { size() }; value_type* old_array { array }; allocate(new_size); memcpy(array - OFFSET, old_array - OFFSET, sizeof(value_type) * (size_ + OFFSET)); // std::cout << "delete[e] at " << old_array << "\n"; delete[](old_array - OFFSET); size() = new_size; } template <typename T> void vector<T>::out() const { std::cout << "out\n"; std::cout << array << "\n"; std::cout << '[' << ref_counter() << ", " << size() << "]: "; for (size_t i = 0; i < size(); ++i) { std::cout << " " << array[i]; } std::cout << "\n"; } template <typename T> inline void swap(vector<T>& a, vector<T>& b) { std::swap(a.array, b.array); } #endif // VECTOR_H
#include "Calculator.h" #include <exception> Calculator::Calculator() {} Calculator::~Calculator() {} double Calculator::plus(double left, double right) { return left + right; } double Calculator::minus(double left, double right) { return left - right; } double Calculator::divide(double left, double right) { if (right == 0) { throw std::exception(); } return left / right; } double Calculator::multiply(double left, double right) { return left * right; }
/*** Table header in file system. ***/ /** Version 1. **/ /* FIXME: Ignore malloc() failure. */ /** Redundance check. **/ #ifndef TABLE_HEADER #define TABLE_HEADER /** Included files. **/ #include <stdint.h> /* Standard integers. E.g. uint16_t */ #include <stdlib.h> /* Standard library. E.g. exit() */ #include <string.h> /* String operations. E.g. memcmp() */ #include <stdio.h> /* Standard I/O. */ #include <mutex> /* Mutex operations. */ #include "bitmap.hpp" /* Bitmap class. */ #include "debug.hpp" /* Debug class. */ /** Design. **/ /* +------------+---------------------------+ | Bitmap | Items | +------------+---------------------------+ - Memory overview of buffer - Use bitmap to check if a position is occupied. +---+---+---+---+---+---+------+---+---+---+---+ | 0 | 0 | 0 | 1 | 0 | 1 | .... | 0 | 0 | 0 | 0 | +---+---+---+---+---+---+------+---+---+---+---+ - Structure of bitmap - Use free bit chain to allocate a new item. (The free bit chain is generated from bitmap.) +--------------+-------------------------+ +--------------+----------+ | Position | Next free bit pointer -|--> .... --->| Position | NULL | +--------------+-------------------------+ +--------------+----------+ - Free bit chain - index +--------------+ 0 | Item 0 | +--------------+ 1 | Item 1 | +--------------+ - item array - 2 | Item 2 | +--------------+ | .... | +--------------+ n | Item n | +--------------+ */ /** Structures. **/ typedef struct { /* Free bit structure. */ uint64_t position; /* Position of bit. */ void *nextFreeBit; /* Next free bit. */ } FreeBit; /** Classes. **/ template<typename T> class Table { private: Bitmap *bitmapItems; /* Bitmap for items. */ std::mutex mutexBitmapItems; /* Mutex for bitmap for items. */ T *items; /* Items of table. */ FreeBit *headFreeBit; /* Head free bit in the chain. */ FreeBit *tailFreeBit; /* Tail free bit in the chain. */ public: uint64_t sizeBufferUsed; /* Size of used bytes in buffer. */ bool create(uint64_t *index, T *item); /* Create an item. */ bool create(uint64_t *index); /* Create an item. No item will be assigned. */ bool get(uint64_t index, T *item); /* Get an item. */ bool get(uint64_t index, T *item, uint64_t *address); bool put(uint64_t index, T *item); /* Put an item. */ bool put(uint64_t index, T *item, uint64_t *address); bool remove(uint64_t index); /* Remove an item. */ uint64_t countSavedItems(); /* Saved items count. */ uint64_t countTotalItems(); /* Total items count. */ Table(char *buffer, uint64_t count); /* Constructor of table. */ ~Table(); /* Destructor of table. */ }; /* Create an item in table. (no item will be assigned) @param index Index of created item in table. @return If creation failed return false. Otherwise return true. */ template<typename T> bool Table<T>::create(uint64_t *index) { if (index == NULL) { return false; /* Fail due to null index. */ } else { bool result; mutexBitmapItems.lock(); /* Lock table bitmap. */ { if (headFreeBit == NULL) { /* If there is no free bit in bitmap. */ return false; /* Fail due to out of free bit. */ } else { *index = headFreeBit->position; /* Get index from free bit. */ FreeBit *currentFreeBit = headFreeBit; /* Get current free bit. */ headFreeBit = (FreeBit *)(headFreeBit->nextFreeBit); /* Move current free bit out of free bit chain. */ free(currentFreeBit); /* Release current free bit as used. */ if (bitmapItems->set(*index) == false) { /* Occupy the position first. Need not to roll back. */ result = false; /* Fail due to bitmap set error. No recovery here. */ } else { result = true; /* Succeed. */ } } } mutexBitmapItems.unlock(); /* Unlock table bitmap. */ //printf("Table::create (block): *index = %lu, &(items[*index]) = %lx\n", *index, &(items[*index])); return result; /* Return specific result. */ } } /* Create an item in table. @param index Index of created item in table. @param item Item to put in table. @return If creation failed return false. Otherwise return true. */ template<typename T> bool Table<T>::create(uint64_t *index, T *item) { if ((index == NULL) || (item == NULL)) { return false; /* Fail due to null index or null item. */ } else { bool result; mutexBitmapItems.lock(); /* Lock table bitmap. */ { if (headFreeBit == NULL) { /* If there is no free bit in bitmap. */ return false; /* Fail due to out of free bit. */ } else { *index = headFreeBit->position; /* Get index from free bit. */ FreeBit *currentFreeBit = headFreeBit; /* Get current free bit. */ headFreeBit = (FreeBit *)(headFreeBit->nextFreeBit); /* Move current free bit out of free bit chain. */ free(currentFreeBit); /* Release current free bit as used. */ if (bitmapItems->set(*index) == false) { /* Occupy the position first. Need not to roll back. */ result = false; /* Fail due to bitmap set error. No recovery here. */ } else { items[*index] = *item; /* Save item in items. */ result = true; /* Succeed. */ } } } mutexBitmapItems.unlock(); /* Unlock table bitmap. */ return result; /* Return specific result. */ } } /* Get an item from table. @param index Index of item. @param item Buffer of item. @return If item does not exist or other errors occur return false. Otherwise return true. */ template<typename T> bool Table<T>::get(uint64_t index, T *item) { //printf("Table::get: index = %lu\n", index); if (item == NULL) { return false; /* Fail due to null item buffer. */ } else { bool result; mutexBitmapItems.lock(); /* Though currently there is no bitmap reading or writing, other operations such as delete might affect item reading. */ { bool status; /* Status of existence of item. */ if (bitmapItems->get(index, &status) == false) { result = false; /* Fail due to item get error. */ } else { if (status == false) { result = false; /* Fail due to no item. */ } else { *item = items[index]; /* Get item and put it into buffer. */ result = true; /* Succeed. */ } } } mutexBitmapItems.unlock(); /* Unlock table bitmap. */ return result; /* Return specific result. */ } } template<typename T> bool Table<T>::get(uint64_t index, T *item, uint64_t *address) { //printf("Table::get: index = %lu\n", index); if (item == NULL) { return false; /* Fail due to null item buffer. */ } else { bool result; mutexBitmapItems.lock(); /* Though currently there is no bitmap reading or writing, other operations such as delete might affect item reading. */ { bool status; /* Status of existence of item. */ if (bitmapItems->get(index, &status) == false) { result = false; /* Fail due to item get error. */ } else { if (status == false) { result = false; /* Fail due to no item. */ } else { *item = items[index]; /* Get item and put it into buffer. */ *address = (uint64_t)(&items[index]); Debug::debugItem("get, address = %lx", *address); result = true; /* Succeed. */ } } } mutexBitmapItems.unlock(); /* Unlock table bitmap. */ return result; /* Return specific result. */ } } /* Put an item. If item has not been created then return false. @param index Index of item. @param item Item to put in. @return If index has not been created or other errors occur return false, otherwise return true. */ template<typename T> bool Table<T>::put(uint64_t index, T *item) { //printf("Table::put: index = %lu\n", index); if (item == NULL) { return false; /* Fail due to null item. */ } else { bool result; mutexBitmapItems.lock(); /* Lock table bitmap. */ { bool status; /* Status of existence of item. */ if (bitmapItems->get(index, &status) == false) { result = false; /* Fail due to item get error. */ } else { if (status == false) { result = false; /* Fail due to no item. */ } else { items[index] = *item; /* Save item into table. */ result = true; /* Succeed. */ } } } mutexBitmapItems.unlock(); /* Unlock table bitmap. */ return result; /* Return specific result. */ } } /* Get address of item. @param index Index of item. @param item Item to put in. @return If index has not been created or other errors occur return false, otherwise return true. */ template<typename T> bool Table<T>::put(uint64_t index, T *item, uint64_t *address) { bool result; mutexBitmapItems.lock(); /* Lock table bitmap. */ { bool status; /* Status of existence of item. */ if (bitmapItems->get(index, &status) == false) { result = false; /* Fail due to item get error. */ } else { if (status == false) { result = false; /* Fail due to no item. */ } else { *address = (uint64_t)&items[index]; /* Save item into table. */ Debug::debugItem("put, address = %lx", *address); //items[index] = *item; result = true; /* Succeed. */ } } } mutexBitmapItems.unlock(); /* Unlock table bitmap. */ return result; /* Return specific result. */ } /* Remove an item. @param index Index of item to remove. @return If error occurs return false, otherwise return true. */ template<typename T> bool Table<T>::remove(uint64_t index) { bool result; //printf("Table::remove: index = %lu\n", index); mutexBitmapItems.lock(); /* Lock table bitmap. */ { bool status; /* Status of existence of item. */ if (bitmapItems->get(index, &status) == false) { result = false; /* Fail due to bitmap get error. */ } else { if (status == false) { result = false; /* Fail due to no item. */ } else { if (bitmapItems->clear(index) == false) { result = false; /* Fail due to bitmap clear error. */ } else { FreeBit *currentFreeBit = (FreeBit *)malloc(sizeof(FreeBit)); /* New free bit. */ currentFreeBit->nextFreeBit = headFreeBit; /* Add current free bit to free bit chain. */ currentFreeBit->position = index; /* Index of newly released item. */ headFreeBit = currentFreeBit; /* Update head free bit. */ result = true; /* Succeed. */ } } } } mutexBitmapItems.unlock(); /* Unlock table bitmap. */ return result; /* Return specific result. */ } /* Get saved items count. @return Return count of saved items. */ template<typename T> uint64_t Table<T>::countSavedItems() { return (bitmapItems->countTotal() - bitmapItems->countFree()); /* Return count of saved items. */ } /* Get total items count. @return Return count of total items. */ template<typename T> uint64_t Table<T>::countTotalItems() { return (bitmapItems->countTotal()); /* Return count of total items. */ } /* Constructor of table. Initialize bitmap, items array and free bit chain. @param buffer Buffer of whole table (including bitmap and items). @param count Count of items in table (can be divided by 8 due to bitmap requirement). */ template<typename T> Table<T>::Table(char *buffer, uint64_t count) { if (buffer == NULL) { fprintf(stderr, "Table: buffer is null.\n"); exit(EXIT_FAILURE); /* Fail due to null buffer pointer. */ } else { if (count % 8 != 0) { fprintf(stderr, "Table: count should be times of eight.\n"); exit(EXIT_FAILURE); /* Fail due to count alignment. */ } else { bitmapItems = new Bitmap(count, buffer + count * sizeof(T)); /* Initialize item bitmap. */ items = (T *)(buffer); /* Initialize items array. */ sizeBufferUsed = count / 8 + count * sizeof(T); /* Size of used bytes in buffer. */ /* Initialize free bit chain. */ headFreeBit = NULL; /* Initialize head free bit pointer. */ FreeBit *currentFreeBit; // for (uint64_t index = 0; index < count / 8; index++) { /* Search in all bytes in array. */ // for (uint64_t offset = 0; offset <= 7; offset++) { /* Search in all offsets in byte. */ // if ((buffer[index] & (1 << (7 - offset))) == 0) { /* Judge if bit is cleared. */ // currentFreeBit = (FreeBit *)malloc(sizeof(FreeBit)); /* Create a new free bit. */ // currentFreeBit->position = index * 8 + offset; /* Assign position. */ // currentFreeBit->nextFreeBit = headFreeBit; /* Push current free bit before head. */ // headFreeBit = currentFreeBit; /* Update head free bit. */ // } // } // } for (int index = count / 8 - 1; index >= 0; index--) { /* Search in all bytes in array. */ for (int offset = 7; offset >= 0; offset--) { /* Search in all offsets in byte. */ if ((buffer[index] & (1 << (7 - offset))) == 0) { /* Judge if bit is cleared. */ currentFreeBit = (FreeBit *)malloc(sizeof(FreeBit)); /* Create a new free bit. */ currentFreeBit->position = index * 8 + offset; /* Assign position. */ currentFreeBit->nextFreeBit = headFreeBit; /* Push current free bit before head. */ headFreeBit = currentFreeBit; /* Update head free bit. */ } } } } } } /* Destructor of table. */ template<typename T> Table<T>::~Table() { FreeBit *currentFreeBit; while (headFreeBit != NULL) { currentFreeBit = headFreeBit; headFreeBit = (FreeBit *)(headFreeBit->nextFreeBit); /* Move to next. */ free(currentFreeBit); /* Release free bit. */ } delete bitmapItems; /* Release table bitmap. */ } /** Redundance check. **/ #endif
/********************************************************************************************* cfglp : A CFG Language Processor -------------------------------- About: Implemented by Tanu Kanvar (tanu@cse.iitb.ac.in) and Uday Khedker (http://www.cse.iitb.ac.in/~uday) for the courses cs302+cs306: Language Processors (theory and lab) at IIT Bombay. Release date Jan 15, 2013. Copyrights reserved by Uday Khedker. This implemenation has been made available purely for academic purposes without any warranty of any kind. Documentation (functionality, manual, and design) and related tools are available at http://www.cse.iitb.ac.in/~uday/cfglp ***********************************************************************************************/ #include<iostream> #include<fstream> #include<typeinfo> using namespace std; #include"common-classes.hh" #include"error-display.hh" #include"user-options.hh" #include"local-environment.hh" #include"icode.hh" #include"reg-alloc.hh" #include"symbol-table.hh" #include"ast.hh" #include"basic-block.hh" #include"procedure.hh" #include"program.hh" Ast::Ast() {} Ast::~Ast() {} bool Ast::check_ast() { stringstream msg; msg << "No check_ast() function for " << typeid(*this).name(); CHECK_INVARIANT(CONTROL_SHOULD_NOT_REACH, msg.str()); } Data_Type Ast::get_data_type() { stringstream msg; msg << "No get_data_type() function for " << typeid(*this).name(); CHECK_INVARIANT(CONTROL_SHOULD_NOT_REACH, msg.str()); } Symbol_Table_Entry & Ast::get_symbol_entry() { stringstream msg; msg << "No get_symbol_entry() function for " << typeid(*this).name(); CHECK_INVARIANT(CONTROL_SHOULD_NOT_REACH, msg.str()); } void Ast::print_value(Local_Environment & eval_env, ostream & file_buffer) { stringstream msg; msg << "No print_value() function for " << typeid(*this).name(); CHECK_INVARIANT(CONTROL_SHOULD_NOT_REACH, msg.str()); } int Ast::get_successor() { stringstream msg; msg << "No get_successor() function for " << typeid(*this).name(); CHECK_INVARIANT(CONTROL_SHOULD_NOT_REACH, msg.str()); } Eval_Result & Ast::get_value_of_evaluation(Local_Environment & eval_env) { stringstream msg; msg << "No get_value_of_evaluation() function for " << typeid(*this).name(); CHECK_INVARIANT(CONTROL_SHOULD_NOT_REACH, msg.str()); } void Ast::set_value_of_evaluation(Local_Environment & eval_env, Eval_Result & result) { stringstream msg; msg << "No set_value_of_evaluation() function for " << typeid(*this).name(); CHECK_INVARIANT(CONTROL_SHOULD_NOT_REACH, msg.str()); } Code_For_Ast & Ast::create_store_stmt(Register_Descriptor * store_register) { stringstream msg; msg << "No create_store_stmt() function for " << typeid(*this).name(); CHECK_INVARIANT(CONTROL_SHOULD_NOT_REACH, msg.str()); } ///////////////////////////////////////////////////////////////// Relational_Expr_Ast::Relational_Expr_Ast(Ast * temp_lhs, relational_operators temp_oper, Ast * temp_rhs, int line) { lhs = temp_lhs; rhs = temp_rhs; oper = temp_oper; node_data_type = int_data_type; successor = -1; ast_num_child = binary_arity; lineno = line; } Relational_Expr_Ast::~Relational_Expr_Ast() { delete lhs; delete rhs; } Data_Type Relational_Expr_Ast::get_data_type() { return node_data_type; } bool Relational_Expr_Ast::check_ast() { if (lhs->get_data_type() == rhs->get_data_type()) { node_data_type = int_data_type; return true; } CHECK_INVARIANT(CONTROL_SHOULD_NOT_REACH,"Relational expression statement data type not compatible"); } void Relational_Expr_Ast::print(ostream & file_buffer) { file_buffer << "\n"; file_buffer << AST_NODE_SPACE << "Condition: "; if (oper == LT) { file_buffer << "LT\n"; } else if (oper == LE) { file_buffer << "LE\n"; } else if (oper == GT) { file_buffer << "GT\n"; } else if (oper == GE){ file_buffer << "GE\n"; } else if (oper == EQ){ file_buffer << "EQ\n"; } else if (oper == NE){ file_buffer << "NE\n"; } file_buffer << AST_SUB_NODE_SPACE << "LHS ("; lhs->print(file_buffer); file_buffer << ")\n"; file_buffer << AST_SUB_NODE_SPACE << "RHS ("; rhs->print(file_buffer); file_buffer << ")"; } int Relational_Expr_Ast::get_successor(){ return successor; } Eval_Result & Relational_Expr_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer) { CHECK_INVARIANT((rhs != NULL), "Rhs of Relational_Expr_Ast cannot be null"); CHECK_INVARIANT((lhs != NULL), "Lhs of Relational_Expr_Ast cannot be null"); Eval_Result & lhsResult = lhs->evaluate(eval_env, file_buffer); Eval_Result & rhsResult = rhs->evaluate(eval_env, file_buffer); CHECK_INPUT_AND_ABORT(lhsResult.is_variable_defined(), "Variable should be defined to be on lhs of Relational_Expr_Ast", lineno); CHECK_INPUT_AND_ABORT(rhsResult.is_variable_defined(), "Variable should be defined to be on rhs of Relational_Expr_Ast", lineno); Eval_Result & result = *new Eval_Result_Value_Int(); if(oper == GT){ if(lhsResult.get_int_value() > rhsResult.get_int_value()){ result.set_value(1); } else{ result.set_value(0); } return result; } else if(oper == LT){ if(lhsResult.get_int_value() < rhsResult.get_int_value()){ result.set_value(1); } else{ result.set_value(0); } return result; } else if(oper == GE){ if(lhsResult.get_int_value() >= rhsResult.get_int_value()){ result.set_value(1); } else{ result.set_value(0); } return result; } else if(oper == LE){ if(lhsResult.get_int_value() <= rhsResult.get_int_value()){ result.set_value(1); } else{ result.set_value(0); } return result; } else if(oper == EQ){ if(lhsResult.get_int_value() == rhsResult.get_int_value()){ result.set_value(1); } else{ result.set_value(0); } return result; } else if(oper == NE){ if(lhsResult.get_int_value() != rhsResult.get_int_value()){ result.set_value(1); } else{ result.set_value(0); } return result; } } Code_For_Ast & Relational_Expr_Ast::compile() { CHECK_INVARIANT((rhs != NULL), "Rhs of Relational_Expr_Ast cannot be null"); CHECK_INVARIANT((lhs != NULL), "Lhs of Relational_Expr_Ast cannot be null"); Code_For_Ast & lhs_stmt = lhs->compile(); Register_Descriptor * lhs_register = lhs_stmt.get_reg(); lhs_register->used_for_expr_result = true; Code_For_Ast & rhs_stmt = rhs->compile(); Register_Descriptor * rhs_register = rhs_stmt.get_reg(); rhs_register->used_for_expr_result = true; Register_Descriptor * result_register = machine_dscr_object.get_new_register(); Ics_Opd * lhs_opd = new Register_Addr_Opd(lhs_register); Ics_Opd * rhs_opd = new Register_Addr_Opd(rhs_register); Ics_Opd * register_opd = new Register_Addr_Opd(result_register); Compute_IC_Stmt *compute_stmt; if(oper == GT){ compute_stmt = new Compute_IC_Stmt(sgt, lhs_opd, rhs_opd, register_opd); } else if(oper == LT){ compute_stmt = new Compute_IC_Stmt(slt, lhs_opd, rhs_opd, register_opd); } else if(oper == GE){ compute_stmt = new Compute_IC_Stmt(sge, lhs_opd, rhs_opd, register_opd); } else if(oper == LE){ compute_stmt = new Compute_IC_Stmt(sle, lhs_opd, rhs_opd, register_opd); } else if(oper == EQ){ compute_stmt = new Compute_IC_Stmt(seq, lhs_opd, rhs_opd, register_opd); } else if(oper == NE){ compute_stmt = new Compute_IC_Stmt(sne, lhs_opd, rhs_opd, register_opd); } // Store the statement in ic_list list<Icode_Stmt *> & ic_list = *new list<Icode_Stmt *>; if (lhs_stmt.get_icode_list().empty() == false) ic_list = lhs_stmt.get_icode_list(); if (rhs_stmt.get_icode_list().empty() == false) ic_list.splice(ic_list.end(), rhs_stmt.get_icode_list()); ic_list.push_back(compute_stmt); Code_For_Ast * relational_stmt; if (ic_list.empty() == false) relational_stmt = new Code_For_Ast(ic_list, result_register); lhs_register->used_for_expr_result = false; rhs_register->used_for_expr_result = false; return *relational_stmt; } Code_For_Ast & Relational_Expr_Ast::compile_and_optimize_ast(Lra_Outcome & lra) { CHECK_INVARIANT((rhs != NULL), "Rhs of Relational_Expr_Ast cannot be null"); CHECK_INVARIANT((lhs != NULL), "Lhs of Relational_Expr_Ast cannot be null"); if(typeid(*lhs) != typeid(Relational_Expr_Ast)){ lra.optimize_lra(mc_2r, NULL, lhs); } Code_For_Ast & lhs_stmt = lhs->compile_and_optimize_ast(lra); Register_Descriptor * lhs_register = lhs_stmt.get_reg(); lhs_register->used_for_expr_result = true; if(typeid(*rhs) != typeid(Relational_Expr_Ast)){ lra.optimize_lra(mc_2r, NULL, rhs); } Code_For_Ast & rhs_stmt = rhs->compile_and_optimize_ast(lra); Register_Descriptor * rhs_register = rhs_stmt.get_reg(); rhs_register->used_for_expr_result = true; Register_Descriptor * result_register = machine_dscr_object.get_new_register(); Ics_Opd * lhs_opd = new Register_Addr_Opd(lhs_register); Ics_Opd * rhs_opd = new Register_Addr_Opd(rhs_register); Ics_Opd * register_opd = new Register_Addr_Opd(result_register); Compute_IC_Stmt *compute_stmt; if(oper == GT){ compute_stmt = new Compute_IC_Stmt(sgt, lhs_opd, rhs_opd, register_opd); } else if(oper == LT){ compute_stmt = new Compute_IC_Stmt(slt, lhs_opd, rhs_opd, register_opd); } else if(oper == GE){ compute_stmt = new Compute_IC_Stmt(sge, lhs_opd, rhs_opd, register_opd); } else if(oper == LE){ compute_stmt = new Compute_IC_Stmt(sle, lhs_opd, rhs_opd, register_opd); } else if(oper == EQ){ compute_stmt = new Compute_IC_Stmt(seq, lhs_opd, rhs_opd, register_opd); } else if(oper == NE){ compute_stmt = new Compute_IC_Stmt(sne, lhs_opd, rhs_opd, register_opd); } // Store the statement in ic_list list<Icode_Stmt *> & ic_list = *new list<Icode_Stmt *>; if (lhs_stmt.get_icode_list().empty() == false) ic_list = lhs_stmt.get_icode_list(); if (rhs_stmt.get_icode_list().empty() == false) ic_list.splice(ic_list.end(), rhs_stmt.get_icode_list()); ic_list.push_back(compute_stmt); Code_For_Ast * relational_stmt; if (ic_list.empty() == false) relational_stmt = new Code_For_Ast(ic_list, result_register); lhs_register->used_for_expr_result = false; rhs_register->used_for_expr_result = false; return *relational_stmt; } //////////////////////////////////////////////////////////////// Assignment_Ast::Assignment_Ast(Ast * temp_lhs, Ast * temp_rhs, int line) { lhs = temp_lhs; rhs = temp_rhs; ast_num_child = binary_arity; node_data_type = void_data_type; successor = -1; lineno = line; } Assignment_Ast::~Assignment_Ast() { delete lhs; delete rhs; } int Assignment_Ast::get_successor(){ return successor; } bool Assignment_Ast::check_ast() { CHECK_INVARIANT((rhs != NULL), "Rhs of Assignment_Ast cannot be null"); CHECK_INVARIANT((lhs != NULL), "Lhs of Assignment_Ast cannot be null"); if (lhs->get_data_type() == rhs->get_data_type()) { node_data_type = lhs->get_data_type(); return true; } CHECK_INVARIANT(CONTROL_SHOULD_NOT_REACH, "Assignment statement data type not compatible"); } void Assignment_Ast::print(ostream & file_buffer) { file_buffer << "\n" << AST_SPACE << "Asgn:"; file_buffer << "\n" << AST_NODE_SPACE << "LHS ("; lhs->print(file_buffer); file_buffer << ")"; file_buffer << "\n" << AST_NODE_SPACE << "RHS ("; rhs->print(file_buffer); file_buffer << ")"; } Eval_Result & Assignment_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer) { CHECK_INVARIANT((rhs != NULL), "Rhs of Assignment_Ast cannot be null"); Eval_Result & result = rhs->evaluate(eval_env, file_buffer); CHECK_INPUT_AND_ABORT(result.is_variable_defined(), "Variable should be defined to be on rhs of Assignment_Ast", lineno); CHECK_INVARIANT((lhs != NULL), "Lhs of Assignment_Ast cannot be null"); lhs->set_value_of_evaluation(eval_env, result); // Print the result print(file_buffer); lhs->print_value(eval_env, file_buffer); return result; } Code_For_Ast & Assignment_Ast::compile() { /* An assignment x = y where y is a variable is compiled as a combination of load and store statements: (load) R <- y (store) x <- R If y is a constant, the statement is compiled as: (imm_Load) R <- y (store) x <- R where imm_Load denotes the load immediate operation. */ CHECK_INVARIANT((lhs != NULL), "Lhs cannot be null"); CHECK_INVARIANT((rhs != NULL), "Rhs cannot be null"); Code_For_Ast & load_stmt = rhs->compile(); Register_Descriptor * load_register = load_stmt.get_reg(); Code_For_Ast store_stmt = lhs->create_store_stmt(load_register); // Store the statement in ic_list list<Icode_Stmt *> & ic_list = *new list<Icode_Stmt *>; if (load_stmt.get_icode_list().empty() == false) ic_list = load_stmt.get_icode_list(); if (store_stmt.get_icode_list().empty() == false) ic_list.splice(ic_list.end(), store_stmt.get_icode_list()); Code_For_Ast * assign_stmt; if (ic_list.empty() == false) assign_stmt = new Code_For_Ast(ic_list, load_register); return *assign_stmt; } Code_For_Ast & Assignment_Ast::compile_and_optimize_ast(Lra_Outcome & lra) { CHECK_INVARIANT((lhs != NULL), "Lhs cannot be null"); CHECK_INVARIANT((rhs != NULL), "Rhs cannot be null"); if(typeid(*rhs) != typeid(Relational_Expr_Ast)){ lra.optimize_lra(mc_2m, lhs, rhs); } Code_For_Ast load_stmt = rhs->compile_and_optimize_ast(lra); Register_Descriptor * result_register = load_stmt.get_reg(); Symbol_Table_Entry *new_entry = &(lhs->get_symbol_entry()); Register_Descriptor * curr_register = new_entry->get_register(); if(curr_register != NULL){ new_entry->free_register(curr_register); } new_entry->update_register(result_register); Code_For_Ast store_stmt = lhs->create_store_stmt(result_register); list<Icode_Stmt *> ic_list; if (load_stmt.get_icode_list().empty() == false) ic_list = load_stmt.get_icode_list(); if (store_stmt.get_icode_list().empty() == false) ic_list.splice(ic_list.end(), store_stmt.get_icode_list()); Code_For_Ast * assign_stmt; if (ic_list.empty() == false) assign_stmt = new Code_For_Ast(ic_list, result_register); return *assign_stmt; } ///////////////////////////////////////////////////////////////// If_Else_Ast::If_Else_Ast(Ast * temp_gotoTrue, Ast * temp_condition, Ast * temp_gotoFalse, int line) { gotoTrue = temp_gotoTrue; condition = temp_condition; gotoFalse = temp_gotoFalse; ast_num_child = binary_arity; successor = -3; lineno = line; } If_Else_Ast::~If_Else_Ast() { delete gotoTrue; delete gotoFalse; delete condition; } int If_Else_Ast::get_successor(){ return successor; } bool If_Else_Ast::check_ast() { CHECK_INVARIANT((condition != NULL), "Condition of If_Else_Ast cannot be null"); CHECK_INVARIANT((gotoTrue != NULL), "True Successor of If_Else_Ast cannot be null"); CHECK_INVARIANT((gotoFalse != NULL), "False Successor of If_Else_Ast cannot be null"); } void If_Else_Ast::print(ostream & file_buffer) { file_buffer << "\n"; file_buffer << AST_SPACE << "If_Else statement:"; condition->print(file_buffer); file_buffer << "\n"; file_buffer << AST_NODE_SPACE << "True Successor: " << gotoTrue->get_successor(); file_buffer << "\n"; file_buffer << AST_NODE_SPACE << "False Successor: " << gotoFalse ->get_successor(); } Eval_Result & If_Else_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer) { // Print the result file_buffer << "\n"; file_buffer << AST_SPACE << "If_Else statement:"; CHECK_INVARIANT((condition != NULL), "Condition of If_Else_Ast cannot be null"); condition->print(file_buffer); Eval_Result & conditionResult = condition->evaluate(eval_env, file_buffer); int value = conditionResult.get_int_value(); Eval_Result & result = *new Eval_Result_Value_Int(); file_buffer << "\n"; file_buffer << AST_NODE_SPACE << "True Successor: " << gotoTrue->get_successor(); file_buffer << "\n"; file_buffer << AST_NODE_SPACE << "False Successor: " << gotoFalse ->get_successor(); file_buffer << "\n"; if(value == 1){ CHECK_INVARIANT((gotoTrue != NULL), "True Successor of If_Else_Ast cannot be null"); file_buffer << AST_SPACE << "Condition True : Goto (BB " << gotoTrue->get_successor() << ")\n"; successor = gotoTrue->get_successor(); } else{ file_buffer << AST_SPACE << "Condition False : Goto (BB " << gotoFalse->get_successor() << ")\n"; CHECK_INVARIANT((gotoFalse != NULL), "False Successor of If_Else_Ast cannot be null"); successor = gotoFalse->get_successor(); } result.set_value(successor); return result; } Code_For_Ast & If_Else_Ast::compile() { CHECK_INVARIANT((condition != NULL), "Condition of If_Else_Ast cannot be null"); CHECK_INVARIANT((gotoTrue != NULL), "True Successor of If_Else_Ast cannot be null"); CHECK_INVARIANT((gotoFalse != NULL), "False Successor of If_Else_Ast cannot be null"); Code_For_Ast & condition_code = condition->compile(); Register_Descriptor * condition_result_register = condition_code.get_reg(); condition_result_register->used_for_expr_result = true; Register_Descriptor * result_register = machine_dscr_object.get_new_register(); Ics_Opd * condition_opd = new Register_Addr_Opd(condition_result_register); Ics_Opd * zero_opd = new Register_Addr_Opd(machine_dscr_object.spim_register_table[zero]); Const_Opd<int> * goto_false_opd = new Const_Opd<int>(gotoFalse->get_successor()); Const_Opd<int> * goto_true_opd = new Const_Opd<int>(gotoTrue->get_successor()); Icode_Stmt * bne_stmt = new Control_Flow_IC_Stmt(bne, condition_opd, zero_opd, goto_true_opd); Icode_Stmt * goto_stmt = new Control_Flow_IC_Stmt(goto_op, goto_false_opd); list<Icode_Stmt *> & ic_list = *new list<Icode_Stmt *>; if (condition_code.get_icode_list().empty() == false) ic_list = condition_code.get_icode_list(); ic_list.push_back(bne_stmt); ic_list.push_back(goto_stmt); Code_For_Ast * if_else_stmt; if (ic_list.empty() == false) if_else_stmt = new Code_For_Ast(ic_list, result_register); condition_result_register->used_for_expr_result = false; return *if_else_stmt; } Code_For_Ast & If_Else_Ast::compile_and_optimize_ast(Lra_Outcome & lra) { CHECK_INVARIANT((condition != NULL), "Condition of If_Else_Ast cannot be null"); CHECK_INVARIANT((gotoTrue != NULL), "True Successor of If_Else_Ast cannot be null"); CHECK_INVARIANT((gotoFalse != NULL), "False Successor of If_Else_Ast cannot be null"); Code_For_Ast & condition_code = condition->compile_and_optimize_ast(lra); Register_Descriptor * condition_result_register = condition_code.get_reg(); condition_result_register->used_for_expr_result = true; Register_Descriptor * result_register = machine_dscr_object.get_new_register(); Ics_Opd * condition_opd = new Register_Addr_Opd(condition_result_register); Ics_Opd * zero_opd = new Register_Addr_Opd(machine_dscr_object.spim_register_table[zero]); Const_Opd<int> * goto_false_opd = new Const_Opd<int>(gotoFalse->get_successor()); Const_Opd<int> * goto_true_opd = new Const_Opd<int>(gotoTrue->get_successor()); Icode_Stmt * bne_stmt = new Control_Flow_IC_Stmt(bne, condition_opd, zero_opd, goto_true_opd); Icode_Stmt * goto_stmt = new Control_Flow_IC_Stmt(goto_op, goto_false_opd); list<Icode_Stmt *> & ic_list = *new list<Icode_Stmt *>; if (condition_code.get_icode_list().empty() == false) ic_list = condition_code.get_icode_list(); ic_list.push_back(bne_stmt); ic_list.push_back(goto_stmt); Code_For_Ast * if_else_stmt; if (ic_list.empty() == false) if_else_stmt = new Code_For_Ast(ic_list, result_register); condition_result_register->used_for_expr_result = false; return *if_else_stmt; } ///////////////////////////////////////////////////////////////// Goto_Ast::Goto_Ast(int temp_bb, int line) { bb = temp_bb; successor = temp_bb; ast_num_child = binary_arity; lineno = line; } Goto_Ast::~Goto_Ast() { } int Goto_Ast::get_successor(){ return successor; } bool Goto_Ast::check_ast() { CHECK_INVARIANT((bb >= 2), "Basic block lable should be greater than 1"); } void Goto_Ast::print(ostream & file_buffer) { file_buffer << "\n"; file_buffer << AST_SPACE << "Goto statement:\n"; file_buffer << AST_NODE_SPACE << "Successor: " << bb; } Eval_Result & Goto_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer) { // Print the result print(file_buffer); Eval_Result & result = *new Eval_Result_Value_Int(); result.set_value(bb); file_buffer << "\n"; file_buffer << AST_SPACE << "GOTO (BB " << successor << ")\n"; successor = bb; return result; } Code_For_Ast & Goto_Ast::compile() { CHECK_INVARIANT((bb >= 2), "Basic block lable should be greater than 1"); Register_Descriptor * result_register = machine_dscr_object.get_new_register(); Const_Opd<int> * bb_id = new Const_Opd<int>(bb); Icode_Stmt * goto_stmt = new Control_Flow_IC_Stmt(goto_op, bb_id); list<Icode_Stmt *> & ic_list = *new list<Icode_Stmt *>; ic_list.push_back(goto_stmt); Code_For_Ast * goto_code_stmt; if (ic_list.empty() == false) goto_code_stmt = new Code_For_Ast(ic_list, result_register); return *goto_code_stmt; } Code_For_Ast & Goto_Ast::compile_and_optimize_ast(Lra_Outcome & lra) { CHECK_INVARIANT((bb >= 2), "Basic block lable should be greater than 1"); Register_Descriptor * result_register = machine_dscr_object.get_new_register(); Const_Opd<int> * bb_id = new Const_Opd<int>(bb); Icode_Stmt * goto_stmt = new Control_Flow_IC_Stmt(goto_op, bb_id); list<Icode_Stmt *> & ic_list = *new list<Icode_Stmt *>; ic_list.push_back(goto_stmt); Code_For_Ast * goto_code_stmt; if (ic_list.empty() == false) goto_code_stmt = new Code_For_Ast(ic_list, result_register); return *goto_code_stmt; } ///////////////////////////////////////////////////////////////// Name_Ast::Name_Ast(string & name, Symbol_Table_Entry & var_entry, int line) { variable_symbol_entry = &var_entry; CHECK_INVARIANT((variable_symbol_entry->get_variable_name() == name), "Variable's symbol entry is not matching its name"); ast_num_child = zero_arity; node_data_type = variable_symbol_entry->get_data_type(); lineno = line; } Name_Ast::~Name_Ast() {} Data_Type Name_Ast::get_data_type() { return variable_symbol_entry->get_data_type(); } Symbol_Table_Entry & Name_Ast::get_symbol_entry() { return *variable_symbol_entry; } void Name_Ast::print(ostream & file_buffer) { file_buffer << "Name : " << variable_symbol_entry->get_variable_name(); } void Name_Ast::print_value(Local_Environment & eval_env, ostream & file_buffer) { string variable_name = variable_symbol_entry->get_variable_name(); Eval_Result * loc_var_val = eval_env.get_variable_value(variable_name); Eval_Result * glob_var_val = interpreter_global_table.get_variable_value(variable_name); file_buffer << "\n" << AST_SPACE << variable_name << " : "; if (!eval_env.is_variable_defined(variable_name) && !interpreter_global_table.is_variable_defined(variable_name)) file_buffer << "undefined"; else if (eval_env.is_variable_defined(variable_name) && loc_var_val != NULL) { CHECK_INVARIANT(loc_var_val->get_result_enum() == int_result, "Result type can only be int"); file_buffer << loc_var_val->get_int_value() << "\n"; } else { CHECK_INVARIANT(glob_var_val->get_result_enum() == int_result, "Result type can only be int and float"); if (glob_var_val == NULL) file_buffer << "0\n"; else file_buffer << glob_var_val->get_int_value() << "\n"; } file_buffer << "\n"; } Eval_Result & Name_Ast::get_value_of_evaluation(Local_Environment & eval_env) { string variable_name = variable_symbol_entry->get_variable_name(); if (eval_env.does_variable_exist(variable_name)) { CHECK_INPUT_AND_ABORT((eval_env.is_variable_defined(variable_name) == true), "Variable should be defined before its use", lineno); Eval_Result * result = eval_env.get_variable_value(variable_name); return *result; } CHECK_INPUT_AND_ABORT((interpreter_global_table.is_variable_defined(variable_name) == true), "Variable should be defined before its use", lineno); Eval_Result * result = interpreter_global_table.get_variable_value(variable_name); return *result; } void Name_Ast::set_value_of_evaluation(Local_Environment & eval_env, Eval_Result & result) { Eval_Result * i; string variable_name = variable_symbol_entry->get_variable_name(); if (variable_symbol_entry->get_data_type() == int_data_type) i = new Eval_Result_Value_Int(); else CHECK_INPUT_AND_ABORT(CONTROL_SHOULD_NOT_REACH, "Type of a name can be int/float only", lineno); if (result.get_result_enum() == int_result) i->set_value(result.get_int_value()); else CHECK_INPUT_AND_ABORT(CONTROL_SHOULD_NOT_REACH, "Type of a name can be int/float only", lineno); if (eval_env.does_variable_exist(variable_name)) eval_env.put_variable_value(*i, variable_name); else interpreter_global_table.put_variable_value(*i, variable_name); } Eval_Result & Name_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer) { return get_value_of_evaluation(eval_env); } Code_For_Ast & Name_Ast::compile() { Ics_Opd * opd = new Mem_Addr_Opd(*variable_symbol_entry); Register_Descriptor * result_register = machine_dscr_object.get_new_register(); Ics_Opd * register_opd = new Register_Addr_Opd(result_register); Icode_Stmt * load_stmt = new Move_IC_Stmt(load, opd, register_opd); list<Icode_Stmt *> ic_list; ic_list.push_back(load_stmt); Code_For_Ast & load_code = *new Code_For_Ast(ic_list, result_register); return load_code; } Code_For_Ast & Name_Ast::create_store_stmt(Register_Descriptor * store_register) { CHECK_INVARIANT((store_register != NULL), "Store register cannot be null"); Ics_Opd * register_opd = new Register_Addr_Opd(store_register); Ics_Opd * opd = new Mem_Addr_Opd(*variable_symbol_entry); Icode_Stmt * store_stmt = new Move_IC_Stmt(store, register_opd, opd); if (command_options.is_do_lra_selected() == false) variable_symbol_entry->free_register(store_register); list<Icode_Stmt *> & ic_list = *new list<Icode_Stmt *>; ic_list.push_back(store_stmt); Code_For_Ast & name_code = *new Code_For_Ast(ic_list, store_register); return name_code; } Code_For_Ast & Name_Ast::compile_and_optimize_ast(Lra_Outcome & lra) { list<Icode_Stmt *> & ic_list = *new list<Icode_Stmt *>;; bool load_needed = lra.is_load_needed(); Register_Descriptor * result_register = lra.get_register(); CHECK_INVARIANT((result_register != NULL), "Register cannot be null"); Ics_Opd * register_opd = new Register_Addr_Opd(result_register); Icode_Stmt * load_stmt = NULL; if (load_needed) { Ics_Opd * opd = new Mem_Addr_Opd(*variable_symbol_entry); load_stmt = new Move_IC_Stmt(load, opd, register_opd); ic_list.push_back(load_stmt); } Code_For_Ast & load_code = *new Code_For_Ast(ic_list, result_register); return load_code; } /////////////////////////////////////////////////////////////////////////////// template <class DATA_TYPE> Number_Ast<DATA_TYPE>::Number_Ast(DATA_TYPE number, Data_Type constant_data_type, int line) { constant = number; node_data_type = constant_data_type; ast_num_child = zero_arity; lineno = line; } template <class DATA_TYPE> Number_Ast<DATA_TYPE>::~Number_Ast() {} template <class DATA_TYPE> Data_Type Number_Ast<DATA_TYPE>::get_data_type() { return node_data_type; } template <class DATA_TYPE> void Number_Ast<DATA_TYPE>::print(ostream & file_buffer) { file_buffer << std::fixed; file_buffer << std::setprecision(2); file_buffer << "Num : " << constant; } template <class DATA_TYPE> Eval_Result & Number_Ast<DATA_TYPE>::evaluate(Local_Environment & eval_env, ostream & file_buffer) { if (node_data_type == int_data_type) { Eval_Result & result = *new Eval_Result_Value_Int(); result.set_value(constant); return result; } } template <class DATA_TYPE> Code_For_Ast & Number_Ast<DATA_TYPE>::compile() { Register_Descriptor * result_register = machine_dscr_object.get_new_register(); CHECK_INVARIANT((result_register != NULL), "Result register cannot be null"); Ics_Opd * load_register = new Register_Addr_Opd(result_register); Ics_Opd * opd = new Const_Opd<int>(constant); Icode_Stmt * load_stmt = new Move_IC_Stmt(imm_load, opd, load_register); list<Icode_Stmt *> & ic_list = *new list<Icode_Stmt *>; ic_list.push_back(load_stmt); Code_For_Ast & num_code = *new Code_For_Ast(ic_list, result_register); return num_code; } template <class DATA_TYPE> Code_For_Ast & Number_Ast<DATA_TYPE>::compile_and_optimize_ast(Lra_Outcome & lra) { CHECK_INVARIANT((lra.get_register() != NULL), "Register assigned through optimize_lra cannot be null"); Ics_Opd * load_register = new Register_Addr_Opd(lra.get_register()); Ics_Opd * opd = new Const_Opd<int>(constant); Icode_Stmt * load_stmt = new Move_IC_Stmt(imm_load, opd, load_register); list<Icode_Stmt *> ic_list; ic_list.push_back(load_stmt); Code_For_Ast & num_code = *new Code_For_Ast(ic_list, lra.get_register()); return num_code; } /////////////////////////////////////////////////////////////////////////////// Return_Ast::Return_Ast(int line) { lineno = line; node_data_type = void_data_type; ast_num_child = zero_arity; successor = -2; } Return_Ast::~Return_Ast() {} void Return_Ast::print(ostream & file_buffer) { file_buffer << "\n" << AST_SPACE << "Return <NOTHING>\n"; } int Return_Ast::get_successor(){ return successor; } Eval_Result & Return_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer) { print(file_buffer); Eval_Result & result = *new Eval_Result_Value_Int(); return result; } Code_For_Ast & Return_Ast::compile() { Code_For_Ast & ret_code = *new Code_For_Ast(); return ret_code; } Code_For_Ast & Return_Ast::compile_and_optimize_ast(Lra_Outcome & lra) { Code_For_Ast & ret_code = *new Code_For_Ast(); return ret_code; } template class Number_Ast<int>;
#include "physics.h" #include "vector.h" #include "sphere.h" namespace phys { Physics::Physics(){} void Physics::updateAcceleration(Sphere *sphere) { this->updateDragForce(sphere); sphere->setAcceleration(Vector{m_gravity+(sphere->getDragForce()/sphere->getMass())}); } void Physics::updateVelocity(Sphere *sphere) { this->updateAcceleration(sphere); sphere->setVelocity(Vector{sphere->getVelocity()+(sphere->getAcceleration()*m_dt)}); } void Physics::updatePosition(Sphere *sphere) { this->updateVelocity(sphere); sphere->setPosition(Vector{sphere->getPosition() + sphere->getVelocity()*m_dt}); } void Physics::updateDragForce(Sphere *sphere) { Vector force{(sphere->getVelocity()*sphere->getVelocity())*0.5*m_density*sphere->getCoeffDrag()*sphere->getArea()}; force = sphere->getVelocity().sign()*force*-1; force = force.saturate(-m_max_drag_force,m_max_drag_force); sphere->setDragForce(force); } void Physics::bounceOffWall(Sphere *sphere, Vector box_top_right, Vector box_bottom_left) { unsigned char collision_detection{this->checkForBoxCollission(sphere->getPosition(), box_top_right, box_bottom_left, sphere->getRadius())}; const unsigned char x_wall_pos = 1 << 0; const unsigned char x_wall_neg = 1 << 1; const unsigned char y_wall_pos = 1 << 2; const unsigned char y_wall_neg = 1 << 3; const unsigned char z_wall_pos = 1 << 4; const unsigned char z_wall_neg = 1 << 5; const unsigned char none = 0; double overshoot{0.0}; Vector bounce{1,1,1}; if (collision_detection & ~none) { if (collision_detection & x_wall_pos) { overshoot = box_top_right.getX()-(sphere->getPosition().getX()+sphere->getRadius()); bounce = bounce*Vector{-sphere->getCoeffRestitution(),1,1}; sphere->setPosition(Vector{sphere->getPosition().getX()+overshoot,sphere->getPosition().getY(),sphere->getPosition().getZ()}); } if (collision_detection & y_wall_pos) { overshoot = box_top_right.getY()-(sphere->getPosition().getY()+sphere->getRadius()); bounce = bounce*Vector{1,-sphere->getCoeffRestitution(),1}; sphere->setPosition(Vector{sphere->getPosition().getX(),sphere->getPosition().getY()+overshoot,sphere->getPosition().getZ()}); } if (collision_detection & z_wall_pos) { overshoot = box_top_right.getZ()-(sphere->getPosition().getZ()+sphere->getRadius()); bounce = bounce*Vector{1,1,-sphere->getCoeffRestitution()}; sphere->setPosition(Vector{sphere->getPosition().getX(),sphere->getPosition().getY(),sphere->getPosition().getZ()+overshoot}); } if (collision_detection & x_wall_neg) { overshoot = box_bottom_left.getX()-(sphere->getPosition().getX()-sphere->getRadius()); bounce = bounce*Vector{-sphere->getCoeffRestitution(),1,1}; sphere->setPosition(Vector{sphere->getPosition().getX()+overshoot,sphere->getPosition().getY(),sphere->getPosition().getZ()}); } if (collision_detection & y_wall_neg) { overshoot = box_bottom_left.getY()-(sphere->getPosition().getY()-sphere->getRadius()); bounce = bounce*Vector{1,-sphere->getCoeffRestitution(),1}; sphere->setPosition(Vector{sphere->getPosition().getX(),sphere->getPosition().getY()+overshoot,sphere->getPosition().getZ()}); } if (collision_detection & z_wall_neg) { overshoot = box_bottom_left.getZ()-(sphere->getPosition().getZ()-sphere->getRadius()); bounce = bounce*Vector{1,1,-sphere->getCoeffRestitution()}; sphere->setPosition(Vector{sphere->getPosition().getX(),sphere->getPosition().getY(),sphere->getPosition().getZ()+overshoot}); } Vector new_vel{sphere->getVelocity()}; new_vel = new_vel*bounce; sphere->setVelocity(new_vel); } } unsigned char Physics::checkForBoxCollission(Vector position, Vector box_top_right, Vector box_bottom_left, double radius) { const unsigned char x_wall_pos = 1 << 0; const unsigned char x_wall_neg = 1 << 1; const unsigned char y_wall_pos = 1 << 2; const unsigned char y_wall_neg = 1 << 3; const unsigned char z_wall_pos = 1 << 4; const unsigned char z_wall_neg = 1 << 5; unsigned char output{0}; if (position.getX()+radius >= box_top_right.getX()) output |= x_wall_pos; if (position.getX()-radius <= box_bottom_left.getX()) output |= x_wall_neg; if (position.getY()+radius >= box_top_right.getY()) output |= y_wall_pos; if (position.getY()-radius <= box_bottom_left.getY()) output |= y_wall_neg; if (position.getZ()+radius >= box_top_right.getZ()) output |= z_wall_pos; if (position.getZ()-radius <= box_bottom_left.getZ()) output |= z_wall_neg; return output; } void Physics::setGravity(Vector gravity) { m_gravity = gravity; } Vector Physics::getGravity() { return m_gravity; } void Physics::setDensity(double density) { m_density = density; } double Physics::getDensity() { return m_density; } void Physics::checkForSphereCollision(std::vector<Sphere *> &spheres) { for (int i{0}; i<spheres.size(); i++) { for (int j{i+1}; j<spheres.size(); j++) { Vector pos_d{spheres[i]->getPosition()-spheres[j]->getPosition()}; if (pos_d.norm()+m_collision_buffer < (spheres[i]->getRadius()+spheres[j]->getRadius())) { bounceOffSphere(spheres[i],spheres[j]); adjustPositionAfterBounce(spheres[i],spheres[j]); } } } } void Physics::bounceOffSphere(Sphere *sphere1, Sphere *sphere2) { double mass1_term{2*sphere2->getMass()/(sphere1->getMass()+sphere2->getMass())}; Vector vel1_diff{sphere1->getVelocity()-sphere2->getVelocity()}; Vector pos1_diff{sphere1->getPosition()-sphere2->getPosition()}; double vel1_diff_dotted{vel1_diff.dot(pos1_diff)}; double pos1_norm_squared{pos1_diff.norm()*pos1_diff.norm()}; Vector new_vel1{sphere1->getVelocity()-(sphere1->getCoeffRestitution()*mass1_term*vel1_diff_dotted/pos1_norm_squared*pos1_diff)}; double mass2_term{2*sphere1->getMass()/(sphere1->getMass()+sphere2->getMass())}; Vector vel2_diff{sphere2->getVelocity()-sphere1->getVelocity()}; Vector pos2_diff{sphere2->getPosition()-sphere1->getPosition()}; double vel2_diff_dotted{vel2_diff.dot(pos2_diff)}; double pos2_norm_squared{pos2_diff.norm()*pos2_diff.norm()}; Vector new_vel2{sphere2->getVelocity()-(sphere2->getCoeffRestitution()*mass2_term*vel2_diff_dotted/pos2_norm_squared*pos2_diff)}; sphere1->setVelocity(new_vel1); sphere2->setVelocity(new_vel2); } void Physics::adjustPositionAfterBounce(Sphere *sphere1, Sphere *sphere2) { Vector pos1_diff{sphere1->getPosition()-sphere2->getPosition()}; Vector pos2_diff{sphere2->getPosition()-sphere1->getPosition()}; double overlap = (sphere1->getRadius()+sphere2->getRadius()) - pos1_diff.norm(); Vector new_pos1{sphere1->getPosition()+(overlap/2)*(pos1_diff/pos1_diff.norm())}; Vector new_pos2{sphere2->getPosition()+(overlap/2)*(pos2_diff/pos2_diff.norm())}; sphere1->setPosition(new_pos1); sphere2->setPosition(new_pos2); } }
// // EnemyLayer.cpp // Aircraft // // Created by lc on 11/27/14. // // #include "EnemyLayer.h" EnemyLayer::EnemyLayer(void) { m_allEnemy1 = __Array::create(); m_allEnemy2 = __Array::create(); m_allEnemy3 = __Array::create(); m_allEnemy1->retain(); m_allEnemy2->retain(); m_allEnemy3->retain(); } EnemyLayer::~EnemyLayer(void) { m_allEnemy1->release(); m_allEnemy1 = NULL; m_allEnemy2->release(); m_allEnemy2 = NULL; m_allEnemy3->release(); m_allEnemy3 = NULL; } EnemyLayer* EnemyLayer::create() { EnemyLayer* pRet = new EnemyLayer(); if (pRet && pRet->init()) { pRet->autorelease(); return pRet; } else { CC_SAFE_DELETE(pRet); return NULL; } } bool EnemyLayer::init() { if (!Layer::init()) { return false; } this->schedule(schedule_selector(EnemyLayer::addEnemy1), 1.5f, kRepeatForever, 2); this->schedule(schedule_selector(EnemyLayer::addEnemy2), 3.0f, kRepeatForever, 4); this->schedule(schedule_selector(EnemyLayer::addEnemy3), 10.0f, kRepeatForever, 8); return true; } void EnemyLayer::addEnemy1(float dt) { Enemy* enemy = Enemy::create(); enemy->bindSprite(Sprite::createWithSpriteFrame(PlistHandler::getInstance()->getFrameByName("enemy1.png")), ENEMY1_LIFE); srand((uint) time(NULL)); Size enemySize = enemy->getSprite()->getContentSize(); Size winSize = Director::getInstance()->getWinSize(); int minX = enemySize.width/2; int maxX = winSize.width-enemySize.width/2; int rangeX = maxX - minX; int actualX = (rand() % rangeX) + minX; enemy->setPosition(Point(actualX,winSize.height + enemySize.height/2)); this->addChild(enemy); this->m_allEnemy1->addObject(enemy); //随机飞行速度 float minDuration = 4.0f, maxDuration = 8.0f; int rangeDuration = maxDuration - minDuration; int actualDuration = (rand() % rangeDuration) + minDuration; FiniteTimeAction* actionMove = MoveTo::create(actualDuration, Point(actualX, 0 - enemy->getSprite()->getContentSize().height/2)); FiniteTimeAction* actionDone = CallFuncN::create(CC_CALLBACK_1(EnemyLayer::enemy1MoveFinished, this)); Sequence* sequence = Sequence::createWithTwoActions(actionMove, actionDone); enemy->runAction(sequence); } void EnemyLayer::enemy1MoveFinished(Node* pNode) { //log("enemy1 Move finished\n"); m_allEnemy1->removeObject(pNode); this->removeChild(pNode); } void EnemyLayer::addEnemy2(float dt) { Enemy* enemy = Enemy::create(); enemy->bindSprite(Sprite::createWithSpriteFrame(PlistHandler::getInstance()->getFrameByName("enemy2.png")), ENEMY2_LIFE); srand((uint) time(NULL)); Size enemySize = enemy->getSprite()->getContentSize(); Size winSize = Director::getInstance()->getWinSize(); int minX = enemySize.width / 2; int maxX = winSize.width - enemySize.width / 2; int rangeX = maxX - minX; int actualX = (rand()%rangeX) + minX; enemy->setPosition(Point(actualX,winSize.height + enemySize.height/2)); this->addChild(enemy); this->m_allEnemy2->addObject(enemy); //随机飞行速 float minDuration = 6.0f, maxDuration = 12.0f; int rangeDuration = maxDuration - minDuration; int actualDuration = (rand()%rangeDuration) + minDuration; FiniteTimeAction* actionMove = MoveTo::create(actualDuration,Point(actualX, 0 - enemy->getSprite()->getContentSize().height/2)); FiniteTimeAction* actionDone = CallFuncN::create(CC_CALLBACK_1(EnemyLayer::enemy2MoveFinished, this)); Sequence* sequence = Sequence::createWithTwoActions(actionMove, actionDone); enemy->runAction(sequence); } void EnemyLayer::enemy2MoveFinished(Node* pNode) { //log("enemy2 Move finished\n"); m_allEnemy2->removeObject(pNode); this->removeChild(pNode); } void EnemyLayer::addEnemy3(float dt) { Enemy* enemy = Enemy::create(); Animate* animate = Animate::create(PlistHandler::getInstance()->getAnimationByName("enemy3")); enemy->bindSprite(Sprite::create(), ENEMY3_LIFE); enemy->getSprite()->runAction(RepeatForever::create(animate)); srand((uint) time(NULL)); Size enemySize = PlistHandler::getInstance()->getFrameByName("enemy3_n1.png")->getOriginalSize(); Size winSize = Director::getInstance()->getWinSize(); int minX = enemySize.width / 2; int maxX = winSize.width - enemySize.width / 2; int rangeX = maxX-minX; int actualX = (rand() % rangeX) + minX; enemy->setPosition(Point(actualX, winSize.height + enemySize.height/2)); this->addChild(enemy); this->m_allEnemy3->addObject(enemy); //随机飞行速 float minDuration = 8.0f, maxDuration = 16.0f; int rangeDuration = maxDuration - minDuration; int actualDuration = (rand() % rangeDuration) + minDuration; FiniteTimeAction* actionMove = MoveTo::create(actualDuration, Point(actualX, 0 - enemySize.height/2)); FiniteTimeAction* actionDone = CallFuncN::create(CC_CALLBACK_1(EnemyLayer::enemy3MoveFinished, this)); Sequence* sequence = Sequence::createWithTwoActions(actionMove, actionDone); enemy->runAction(sequence); } void EnemyLayer::enemy3MoveFinished(Node* pNode) { //log("enemy3 Move finished\n"); m_allEnemy3->removeObject(pNode); this->removeChild(pNode); } void EnemyLayer::blowupEnemy1(Enemy *enemy1) { CocosDenshion::SimpleAudioEngine::getInstance()->playEffect("enemy1_down.mp3"); Animation* animation = PlistHandler::getInstance()->getAnimationByName("enemy1Blowup"); Animate* animate = Animate::create(animation); CallFuncN* remove = CallFuncN::create(CC_CALLBACK_1(EnemyLayer::removeEnemy1, this, enemy1)); Sequence* sequence = Sequence::create(animate, remove, NULL); enemy1->getSprite()->runAction(sequence); } void EnemyLayer::blowupEnemy2(Enemy *enemy2) { CocosDenshion::SimpleAudioEngine::getInstance()->playEffect("enemy2_down.mp3"); Animation* animation = PlistHandler::getInstance()->getAnimationByName("enemy2Blowup"); Animate* animate = Animate::create(animation); CallFuncN* remove = CallFuncN::create(CC_CALLBACK_1(EnemyLayer::removeEnemy2, this, enemy2)); Sequence* sequence = Sequence::create(animate, remove, NULL); enemy2->getSprite()->runAction(sequence); } void EnemyLayer::blowupEnemy3(Enemy *enemy3) { CocosDenshion::SimpleAudioEngine::getInstance()->playEffect("enemy3_down.mp3"); Animation* animation = PlistHandler::getInstance()->getAnimationByName("enemy3Blowup"); Animate* animate = Animate::create(animation); CallFuncN* remove = CallFuncN::create(CC_CALLBACK_1(EnemyLayer::removeEnemy3, this, enemy3)); Sequence* sequence = Sequence::create(animate, remove, NULL); enemy3->getSprite()->runAction(sequence); } void EnemyLayer::removeEnemy1(Node* pTarget, void* data) { Enemy* enemy1 = (Enemy*) data; if (enemy1 != NULL) { m_allEnemy1->removeObject(enemy1); this->removeChild(enemy1, true); } } void EnemyLayer::removeEnemy2(Node* pTarget, void* data) { Enemy* enemy2 = (Enemy*) data; if (enemy2 != NULL) { m_allEnemy2->removeObject(enemy2); this->removeChild(enemy2, true); } } void EnemyLayer::removeEnemy3(Node* pTarget, void* data) { Enemy* enemy3 = (Enemy*) data; if (enemy3 != NULL) { m_allEnemy3->removeObject(enemy3); this->removeChild(enemy3, true); } } void EnemyLayer::removeAllEnemy1() { Ref* obj; CCARRAY_FOREACH(m_allEnemy1, obj) { auto enemy1 = (Enemy*) obj; if (enemy1->getLife() > 0) { blowupEnemy1(enemy1); } } } void EnemyLayer::removeAllEnemy2() { Ref* obj; CCARRAY_FOREACH(m_allEnemy2, obj) { auto enemy2 = (Enemy*) obj; if (enemy2->getLife() > 0) { blowupEnemy2(enemy2); } } } void EnemyLayer::removeAllEnemy3() { Ref* obj; CCARRAY_FOREACH(m_allEnemy3, obj) { auto enemy3 = (Enemy*) obj; if (enemy3->getLife() > 0) { blowupEnemy3(enemy3); } } } void EnemyLayer::removeAllEnemy() { removeAllEnemy1(); removeAllEnemy2(); removeAllEnemy3(); }
// Created on: 2014-01-09 // Created by: Denis BOGOLEPOV // Copyright (c) 2013-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 BVH_SweepPlaneBuilder_HeaderFile #define BVH_SweepPlaneBuilder_HeaderFile #include <BVH_QueueBuilder.hxx> #include <BVH_QuickSorter.hxx> #include <NCollection_Array1.hxx> //! Performs building of BVH tree using sweep plane SAH algorithm. template<class T, int N> class BVH_SweepPlaneBuilder : public BVH_QueueBuilder<T, N> { public: //! Creates sweep plane SAH BVH builder. BVH_SweepPlaneBuilder (const Standard_Integer theLeafNodeSize = BVH_Constants_LeafNodeSizeDefault, const Standard_Integer theMaxTreeDepth = BVH_Constants_MaxTreeDepth, const Standard_Integer theNumOfThreads = 1) : BVH_QueueBuilder<T, N> (theLeafNodeSize, theMaxTreeDepth, theNumOfThreads) {} //! Releases resources of sweep plane SAH BVH builder. virtual ~BVH_SweepPlaneBuilder() {} protected: //! Performs splitting of the given BVH node. typename BVH_QueueBuilder<T, N>::BVH_ChildNodes buildNode (BVH_Set<T, N>* theSet, BVH_Tree<T, N>* theBVH, const Standard_Integer theNode) const Standard_OVERRIDE { const Standard_Integer aNodeBegPrimitive = theBVH->BegPrimitive (theNode); const Standard_Integer aNodeEndPrimitive = theBVH->EndPrimitive (theNode); const Standard_Integer aNodeNbPrimitives = theBVH->NbPrimitives (theNode); if (aNodeEndPrimitive - aNodeBegPrimitive < BVH_Builder<T, N>::myLeafNodeSize) { return typename BVH_QueueBuilder<T, N>::BVH_ChildNodes(); // node does not require partitioning } // Parameters for storing best split Standard_Integer aMinSplitAxis = -1; Standard_Integer aMinSplitIndex = 0; NCollection_Array1<Standard_Real> aLftSet (0, aNodeNbPrimitives - 1); NCollection_Array1<Standard_Real> aRghSet (0, aNodeNbPrimitives - 1); Standard_Real aMinSplitCost = std::numeric_limits<Standard_Real>::max(); // Find best split for (Standard_Integer anAxis = 0; anAxis < (N < 4 ? N : 3); ++anAxis) { const T aNodeSize = BVH::VecComp<T, N>::Get (theBVH->MaxPoint (theNode), anAxis) - BVH::VecComp<T, N>::Get (theBVH->MinPoint (theNode), anAxis); if (aNodeSize <= BVH::THE_NODE_MIN_SIZE) { continue; } BVH_QuickSorter<T, N> (anAxis).Perform (theSet, aNodeBegPrimitive, aNodeEndPrimitive); BVH_Box<T, N> aLftBox; BVH_Box<T, N> aRghBox; aLftSet.ChangeFirst() = std::numeric_limits<T>::max(); aRghSet.ChangeFirst() = std::numeric_limits<T>::max(); // Sweep from left for (Standard_Integer anIndex = 1; anIndex < aNodeNbPrimitives; ++anIndex) { aLftBox.Combine (theSet->Box (anIndex + aNodeBegPrimitive - 1)); aLftSet (anIndex) = static_cast<Standard_Real> (aLftBox.Area()); } // Sweep from right for (Standard_Integer anIndex = 1; anIndex < aNodeNbPrimitives; ++anIndex) { aRghBox.Combine (theSet->Box (aNodeEndPrimitive - anIndex + 1)); aRghSet (anIndex) = static_cast<Standard_Real> (aRghBox.Area()); } // Find best split using simplified SAH for (Standard_Integer aNbLft = 1, aNbRgh = aNodeNbPrimitives - 1; aNbLft < aNodeNbPrimitives; ++aNbLft, --aNbRgh) { Standard_Real aCost = (aLftSet (aNbLft) /* / aNodeArea */) * aNbLft + (aRghSet (aNbRgh) /* / aNodeArea */) * aNbRgh; if (aCost < aMinSplitCost) { aMinSplitCost = aCost; aMinSplitAxis = anAxis; aMinSplitIndex = aNbLft; } } } if (aMinSplitAxis == -1) { return typename BVH_QueueBuilder<T, N>::BVH_ChildNodes(); // failed to find split axis } theBVH->SetInner (theNode); if (aMinSplitAxis != (N < 4 ? N - 1 : 2)) { BVH_QuickSorter<T, N> (aMinSplitAxis).Perform (theSet, aNodeBegPrimitive, aNodeEndPrimitive); } BVH_Box<T, N> aMinSplitBoxLft; BVH_Box<T, N> aMinSplitBoxRgh; // Compute bounding boxes for selected split plane for (Standard_Integer anIndex = aNodeBegPrimitive; anIndex < aMinSplitIndex + aNodeBegPrimitive; ++anIndex) { aMinSplitBoxLft.Combine (theSet->Box (anIndex)); } for (Standard_Integer anIndex = aNodeEndPrimitive; anIndex >= aMinSplitIndex + aNodeBegPrimitive; --anIndex) { aMinSplitBoxRgh.Combine (theSet->Box (anIndex)); } const Standard_Integer aMiddle = aNodeBegPrimitive + aMinSplitIndex; typedef typename BVH_QueueBuilder<T, N>::BVH_PrimitiveRange Range; return typename BVH_QueueBuilder<T, N>::BVH_ChildNodes (aMinSplitBoxLft, aMinSplitBoxRgh, Range (aNodeBegPrimitive, aMiddle - 1), Range (aMiddle, aNodeEndPrimitive)); } }; #endif // _BVH_SweepPlaneBuilder_Header
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2012, 2013 Ripple Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #ifndef RIPPLE_RPC_MANAGER_H_INCLUDED #define RIPPLE_RPC_MANAGER_H_INCLUDED #include "../../../beast/beast/utility/Journal.h" #include "Handler.h" #include "Service.h" namespace ripple { using namespace beast; namespace RPC { /** Manages a collection of Service interface objects. */ class Manager { public: static Manager* New (Journal journal); virtual ~Manager() { } /** Add a service. The list of commands that the service handles is enumerated and added to the manager's dispatch table. Thread safety: Safe to call from any thread. May only be called once for a given service. */ virtual void add (Service& service) = 0; /** Add a subclass of Service and return the original pointer. This is provided as a convenient so that RPCService objects may be added from ctor-initializer lists. */ template <class Derived> Derived* add (Derived* derived) { add (*(static_cast <Service*>(derived))); return derived; } /** Execute an RPC command synchronously. On return, if result.first == `true` then result.second will have the Json return value from the call of the handler. */ virtual std::pair <bool, Json::Value> call ( std::string const& method, Json::Value const& args) = 0; /** Returns the Handler for the specified method, or nullptr. Thread safety: Safe to call from any threads. */ virtual Handler const* find (std::string const& method) = 0; }; } } #endif
// Copyright (c) 2022 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 _DE_Provider_HeaderFile #define _DE_Provider_HeaderFile #include <Message_ProgressRange.hxx> class DE_ConfigurationNode; class TopoDS_Shape; class XSControl_WorkSession; class TDocStd_Document; //! Base class to make transfer process. //! Reads or Writes specialized CAD files into/from OCCT. //! Each operation needs the Configuration Node. //! //! Providers are grouped by Vendor's name and Format type. //! The Vendor name is not defined by default. //! The Format type is not defined by default. //! The import process is not supported. //! The export process is not supported. //! //! The algorithm for standalone transfer operation: //! 1) Create new empty Provider object //! 2) Configure the current object by special Configuration Node (::SetNode) //! 3) Initiate the transfer process: //! 3.1) Call the required Read method (if Read methods are implemented) //! 3.2) Call the required Write method (if Write methods are implemented) //! 4) Validate the output values class DE_Provider : public Standard_Transient { public: DEFINE_STANDARD_RTTIEXT(DE_Provider, Standard_Transient) public: //! Default constructor //! Configure translation process with global configuration Standard_EXPORT DE_Provider(); //! Configure translation process //! @param[in] theNode object to copy Standard_EXPORT DE_Provider(const Handle(DE_ConfigurationNode)& theNode); public: //! Reads a CAD file, according internal configuration //! @param[in] thePath path to the import CAD file //! @param[out] theDocument document to save result //! @param[in] theWS current work session //! @param theProgress[in] progress indicator //! @return True if Read was successful Standard_EXPORT virtual Standard_Boolean Read(const TCollection_AsciiString& thePath, const Handle(TDocStd_Document)& theDocument, Handle(XSControl_WorkSession)& theWS, const Message_ProgressRange& theProgress = Message_ProgressRange()); //! Writes a CAD file, according internal configuration //! @param[in] thePath path to the export CAD file //! @param[out] theDocument document to export //! @param[in] theWS current work session //! @param theProgress[in] progress indicator //! @return True if Write was successful Standard_EXPORT virtual Standard_Boolean Write(const TCollection_AsciiString& thePath, const Handle(TDocStd_Document)& theDocument, Handle(XSControl_WorkSession)& theWS, const Message_ProgressRange& theProgress = Message_ProgressRange()); //! Reads a CAD file, according internal configuration //! @param[in] thePath path to the import CAD file //! @param[out] theDocument document to save result //! @param theProgress[in] progress indicator //! @return True if Read was successful Standard_EXPORT virtual Standard_Boolean Read(const TCollection_AsciiString& thePath, const Handle(TDocStd_Document)& theDocument, const Message_ProgressRange& theProgress = Message_ProgressRange()); //! Writes a CAD file, according internal configuration //! @param[in] thePath path to the export CAD file //! @param[out] theDocument document to export //! @param theProgress[in] progress indicator //! @return True if Write was successful Standard_EXPORT virtual Standard_Boolean Write(const TCollection_AsciiString& thePath, const Handle(TDocStd_Document)& theDocument, const Message_ProgressRange& theProgress = Message_ProgressRange()); //! Reads a CAD file, according internal configuration //! @param[in] thePath path to the import CAD file //! @param[out] theShape shape to save result //! @param[in] theWS current work session //! @param theProgress[in] progress indicator //! @return True if Read was successful Standard_EXPORT virtual Standard_Boolean Read(const TCollection_AsciiString& thePath, TopoDS_Shape& theShape, Handle(XSControl_WorkSession)& theWS, const Message_ProgressRange& theProgress = Message_ProgressRange()); //! Writes a CAD file, according internal configuration //! @param[in] thePath path to the export CAD file //! @param[out] theShape shape to export //! @param[in] theWS current work session //! @param theProgress[in] progress indicator //! @return True if Write was successful Standard_EXPORT virtual Standard_Boolean Write(const TCollection_AsciiString& thePath, const TopoDS_Shape& theShape, Handle(XSControl_WorkSession)& theWS, const Message_ProgressRange& theProgress = Message_ProgressRange()); //! Reads a CAD file, according internal configuration //! @param[in] thePath path to the import CAD file //! @param[out] theShape shape to save result //! @param theProgress[in] progress indicator //! @return True if Read was successful Standard_EXPORT virtual Standard_Boolean Read(const TCollection_AsciiString& thePath, TopoDS_Shape& theShape, const Message_ProgressRange& theProgress = Message_ProgressRange()); //! Writes a CAD file, according internal configuration //! @param[in] thePath path to the export CAD file //! @param[out] theShape shape to export //! @param theProgress[in] progress indicator //! @return True if Write was successful Standard_EXPORT virtual Standard_Boolean Write(const TCollection_AsciiString& thePath, const TopoDS_Shape& theShape, const Message_ProgressRange& theProgress = Message_ProgressRange()); public: //! Gets CAD format name of associated provider //! @return provider CAD format Standard_EXPORT virtual TCollection_AsciiString GetFormat() const = 0; //! Gets provider's vendor name of associated provider //! @return provider's vendor name Standard_EXPORT virtual TCollection_AsciiString GetVendor() const = 0; //! Gets internal configuration node //! @return configuration node object Handle(DE_ConfigurationNode) GetNode() const { return myNode; } //! Sets internal configuration node //! @param[in] theNode configuration node to set void SetNode(const Handle(DE_ConfigurationNode)& theNode) { myNode = theNode; } private: Handle(DE_ConfigurationNode) myNode; //!< Internal configuration for the own format }; #endif // _DE_Provider_HeaderFile
// Created on: 2012-03-06 // Created by: Kirill GAVRILOV // Copyright (c) 2012-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 OpenGl_GlCore15_HeaderFile #define OpenGl_GlCore15_HeaderFile #include <OpenGl_GlCore14.hxx> //! OpenGL 1.5 core based on 1.4 version. struct OpenGl_GlCore15 : public OpenGl_GlCore14 { private: typedef OpenGl_GlCore14 theBaseClass_t; public: //! @name OpenGL 1.5 additives to 1.4 #if !defined(GL_ES_VERSION_2_0) using theBaseClass_t::glGenQueries; using theBaseClass_t::glDeleteQueries; using theBaseClass_t::glIsQuery; using theBaseClass_t::glBeginQuery; using theBaseClass_t::glEndQuery; using theBaseClass_t::glGetQueryiv; using theBaseClass_t::glGetQueryObjectiv; using theBaseClass_t::glGetQueryObjectuiv; using theBaseClass_t::glMapBuffer; using theBaseClass_t::glUnmapBuffer; using theBaseClass_t::glGetBufferSubData; using theBaseClass_t::glGetBufferPointerv; #endif using theBaseClass_t::glBindBuffer; using theBaseClass_t::glDeleteBuffers; using theBaseClass_t::glGenBuffers; using theBaseClass_t::glIsBuffer; using theBaseClass_t::glBufferData; using theBaseClass_t::glBufferSubData; using theBaseClass_t::glGetBufferParameteriv; }; #endif // _OpenGl_GlCore15_Header
/* * copyright: 2015 * name : Francis Banyikwa * email: mhogomchungu@gmail.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "benchmark.h" #include "task.h" #include <QDebug> #include <QMetaObject> #include <cstdio> #include <cstring> #include <QProcess> #include <QCoreApplication> #define CRYPTSETUP 0 #include <libcryptsetup.h> benchmark::benchmark() { connect( &m_timer,SIGNAL( timeout() ),this,SLOT( update() ) ) ; } void benchmark::start() { QMetaObject::invokeMethod( this,"run",Qt::QueuedConnection ) ; } void benchmark::update() { if( m_time < 60 ){ printf( "\r%s\telapsed time: %.0f seconds",m_msg.toLatin1().constData(),m_time ) ; }else{ printf( "\r%s\telapsed time: %.2f minutes",m_msg.toLatin1().constData(),m_time / 60 ) ; } fflush( stdout ) ; m_time++ ; } void benchmark::run() { this->benchmarkCryptsetup() ; this->benchmarkVeraCrypt() ; QCoreApplication::quit() ; } void benchmark::startTimer( const char * m ) { printf( "\n" ) ; fflush( stdout ) ; m_msg = m ; m_time = 0 ; m_timer.start( 1000 ) ; } void benchmark::stopTimer() { m_timer.stop() ; printf( "\n" ) ; fflush( stdout ) ; } void benchmark::benchmarkCryptsetup() { #if CRYPTSETUP auto _benchmark = []( const char * key,const char * path ){ Task::await( [ & ](){ struct crypt_device * cd = nullptr ; struct crypt_params_tcrypt params ; if( crypt_init( &cd,path ) == 0 ){ memset( &params,'\0',sizeof( struct crypt_params_tcrypt ) ) ; params.passphrase = key ; params.passphrase_size = strlen( key ) ; params.flags = CRYPT_TCRYPT_VERA_MODES ; if( crypt_load( cd,CRYPT_TCRYPT,&params ) == 0 ){ crypt_free( cd ) ; }else{ params.flags |= CRYPT_TCRYPT_HIDDEN_HEADER ; if( crypt_load( cd,CRYPT_TCRYPT,&params ) == 0 ){ crypt_free( cd ) ; } } } } ) ; } ; puts( "\nbenchmarking cryptsetup" ) ; this->startTimer( "testing sha512(normal) " ) ; _benchmark( "xxx","sha512.img" ) ; this->stopTimer() ; this->startTimer( "testing sha512(hidden) " ) ; _benchmark( "qqq","sha512.img" ) ; this->stopTimer() ; this->startTimer( "testing whirlpool(normal)" ) ; _benchmark( "xxx","whirlpool.img" ) ; this->stopTimer() ; this->startTimer( "testing whirlpool(hidden)" ) ; _benchmark( "qqq","whirlpool.img" ) ; this->stopTimer() ; this->startTimer( "testing sha256(normal) " ) ; _benchmark( "xxx","sha256.img" ) ; this->stopTimer() ; this->startTimer( "testing sha256(hidden) " ) ; _benchmark( "qqq","sha256.img" ) ; this->stopTimer() ; this->startTimer( "testing ripemd160(normal)" ) ; _benchmark( "xxx","ripemd160.img" ) ; this->stopTimer() ; this->startTimer( "testing ripemdi60(hidden)" ) ; _benchmark( "qqq","ripemd160.img" ) ; this->stopTimer() ; this->startTimer( "testing wrong password " ) ; _benchmark( "zzz","ripemd160.img" ) ; this->stopTimer() ; #endif } void benchmark::benchmarkVeraCrypt() { auto _benchmark = []( const char * key,const char * path ){ Task::await( [ & ](){ QProcess exe ; exe.start( QString( "veracrypt -t --non-interactive -p %1 %2" ).arg( key,path ) ) ; exe.waitForFinished( -1 ) ; if( exe.exitCode() == 0 ){ QProcess e ; e.start( "veracrypt -d /media/veracrypt1 " ) ; e.waitForFinished() ; } } ) ; } ; puts( "\nbenchmarking veracrypt" ) ; this->startTimer( "testing sha512(normal) " ) ; _benchmark( "xxx","sha512.img" ) ; this->stopTimer() ; this->startTimer( "testing sha512(hidden) " ) ; _benchmark( "qqq","sha512.img" ) ; this->stopTimer() ; this->startTimer( "testing whirlpool(normal)" ) ; _benchmark( "xxx","whirlpool.img" ) ; this->stopTimer() ; this->startTimer( "testing whirlpool(hidden)" ) ; _benchmark( "qqq","whirlpool.img" ) ; this->stopTimer() ; this->startTimer( "testing sha256(normal) " ) ; _benchmark( "xxx","sha256.img" ) ; this->stopTimer() ; this->startTimer( "testing sha256(hidden) " ) ; _benchmark( "qqq","sha256.img" ) ; this->stopTimer() ; this->startTimer( "testing ripemd160(normal)" ) ; _benchmark( "xxx","ripemd160.img" ) ; this->stopTimer() ; this->startTimer( "testing ripemdi60(hidden)" ) ; _benchmark( "qqq","ripemd160.img" ) ; this->stopTimer() ; this->startTimer( "testing wrong password " ) ; _benchmark( "zzz","ripemd160.img" ) ; this->stopTimer() ; }
// Ceres Solver - A fast non-linear least squares minimizer // Copyright 2015 Google Inc. All rights reserved. // http://ceres-solver.org/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Google Inc. nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Author: sameeragarwal@google.com (Sameer Agarwal) // // Purpose: See .h file. #include "ceres/loss_function.h" #include <algorithm> #include <cmath> #include <cstddef> #include <limits> namespace ceres { void TrivialLoss::Evaluate(double s, double rho[3]) const { rho[0] = s; rho[1] = 1.0; rho[2] = 0.0; } void HuberLoss::Evaluate(double s, double rho[3]) const { if (s > b_) { // Outlier region. // 'r' is always positive. const double r = sqrt(s); rho[0] = 2.0 * a_ * r - b_; rho[1] = std::max(std::numeric_limits<double>::min(), a_ / r); rho[2] = - rho[1] / (2.0 * s); } else { // Inlier region. rho[0] = s; rho[1] = 1.0; rho[2] = 0.0; } } void SoftLOneLoss::Evaluate(double s, double rho[3]) const { const double sum = 1.0 + s * c_; const double tmp = sqrt(sum); // 'sum' and 'tmp' are always positive, assuming that 's' is. rho[0] = 2.0 * b_ * (tmp - 1.0); rho[1] = std::max(std::numeric_limits<double>::min(), 1.0 / tmp); rho[2] = - (c_ * rho[1]) / (2.0 * sum); } void CauchyLoss::Evaluate(double s, double rho[3]) const { const double sum = 1.0 + s * c_; const double inv = 1.0 / sum; // 'sum' and 'inv' are always positive, assuming that 's' is. rho[0] = b_ * log(sum); rho[1] = std::max(std::numeric_limits<double>::min(), inv); rho[2] = - c_ * (inv * inv); } void ArctanLoss::Evaluate(double s, double rho[3]) const { const double sum = 1 + s * s * b_; const double inv = 1 / sum; // 'sum' and 'inv' are always positive. rho[0] = a_ * atan2(s, a_); rho[1] = std::max(std::numeric_limits<double>::min(), inv); rho[2] = -2.0 * s * b_ * (inv * inv); } TolerantLoss::TolerantLoss(double a, double b) : a_(a), b_(b), c_(b * log(1.0 + exp(-a / b))) { CHECK_GE(a, 0.0); CHECK_GT(b, 0.0); } void TolerantLoss::Evaluate(double s, double rho[3]) const { const double x = (s - a_) / b_; // The basic equation is rho[0] = b ln(1 + e^x). However, if e^x is too // large, it will overflow. Since numerically 1 + e^x == e^x when the // x is greater than about ln(2^53) for doubles, beyond this threshold // we substitute x for ln(1 + e^x) as a numerically equivalent approximation. static const double kLog2Pow53 = 36.7; // ln(MathLimits<double>::kEpsilon). if (x > kLog2Pow53) { rho[0] = s - a_ - c_; rho[1] = 1.0; rho[2] = 0.0; } else { const double e_x = exp(x); rho[0] = b_ * log(1.0 + e_x) - c_; rho[1] = std::max(std::numeric_limits<double>::min(), e_x / (1.0 + e_x)); rho[2] = 0.5 / (b_ * (1.0 + cosh(x))); } } void TukeyLoss::Evaluate(double s, double* rho) const { if (s <= a_squared_) { // Inlier region. const double value = 1.0 - s / a_squared_; const double value_sq = value * value; rho[0] = a_squared_ / 6.0 * (1.0 - value_sq * value); rho[1] = 0.5 * value_sq; rho[2] = -1.0 / a_squared_ * value; } else { // Outlier region. rho[0] = a_squared_ / 6.0; rho[1] = 0.0; rho[2] = 0.0; } } ComposedLoss::ComposedLoss(const LossFunction* f, Ownership ownership_f, const LossFunction* g, Ownership ownership_g) : f_(f), g_(g), ownership_f_(ownership_f), ownership_g_(ownership_g) { CHECK(f_ != nullptr); CHECK(g_ != nullptr); } ComposedLoss::~ComposedLoss() { if (ownership_f_ == DO_NOT_TAKE_OWNERSHIP) { f_.release(); } if (ownership_g_ == DO_NOT_TAKE_OWNERSHIP) { g_.release(); } } void ComposedLoss::Evaluate(double s, double rho[3]) const { double rho_f[3], rho_g[3]; g_->Evaluate(s, rho_g); f_->Evaluate(rho_g[0], rho_f); rho[0] = rho_f[0]; // f'(g(s)) * g'(s). rho[1] = rho_f[1] * rho_g[1]; // f''(g(s)) * g'(s) * g'(s) + f'(g(s)) * g''(s). rho[2] = rho_f[2] * rho_g[1] * rho_g[1] + rho_f[1] * rho_g[2]; } void ScaledLoss::Evaluate(double s, double rho[3]) const { if (rho_.get() == NULL) { rho[0] = a_ * s; rho[1] = a_; rho[2] = 0.0; } else { rho_->Evaluate(s, rho); rho[0] *= a_; rho[1] *= a_; rho[2] *= a_; } } } // namespace ceres
#include <iostream> #include <cstdlib> #include <sys/time.h> #include "Cluster_Redis.h" #include "cluster_client.h" #include "cluster_slots.h" #include "log.h" #include "crc16.h" using std::cout; using std::endl; int main(int argc, char** args) { (void)argc; (void)args; ClusterClient cr; cr.Init("127.0.0.1:7000;127.0.0.1:7001;127.0.0.1:7002"); //cr.Init("192.168.5.209:30005;192.168.5.209:36005;192.168.5.213:30004;192.168.5.213:30005;192.168.5.209:30004;192.168.5.216:30005"); //cr.show_clients(); //just show , can be commented cr.startup(); //cr.show_slots(); //just show , can be commented //ClusterSlots *slots = cr.get_one_slots("127.0.0.1", 7000); //cout << "#################" << endl; //if (slots) slots->show_slot(); //cout << "#################" << endl; struct timeval start; struct timeval end; int32_t time_use_usec; int32_t time_use_msec; gettimeofday(&start, NULL); int res = cr.String_Set("aaaa01", "10000000001", 300); gettimeofday(&end, NULL); //std::exit(2); time_use_usec = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec); cout << "return value : " << res << endl; cout << "time use: " << time_use_usec << "usec" << endl; time_use_msec = (end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000; cout << "time use: " << time_use_msec << "msec" << endl; cr.String_Set("aaaa02", "20000000001", 300); cr.String_Set("aaaa03", "30000000001", 300); cr.String_Set("aaaa04", "40000000001", 300); cout << "Get testing ........" << endl; string value1; string value2; string value3; string value4; string value5; res = cr.String_Get("aaaa01", value1); printf("aaaa01 res: %d\n", res); cr.String_Get("aaaa02", value2); cr.String_Get("aaaa03", value3); gettimeofday(&start, NULL); cr.String_Get("aaaa04", value4); gettimeofday(&end, NULL); time_use_usec = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec); cout << "time use: " << time_use_usec << "usec" << endl; res = cr.String_Get("aaaa05", value5); printf("aaaa5 res: %d\n", res); cout << "aaaa01: " << value1 << "\n" << "aaaa02: " << value2 << "\n" << "aaaa03: " << value3 << "\n" << "aaaa04: " << value4 << "\n" << "aaaa05: " << value5 << endl; // -------------- list -------------------// { //--------------set-------------// redisReply *reply = NULL; char *key = "test_k4"; char *val = "test_v4"; int32_t slot_id = keyHashSlot(key, (int)strlen(key)); reply = (redisReply*)cr.redis_command(slot_id, true, "lpush %s %s", key,val); if (reply && reply->type == REDIS_REPLY_INTEGER) { printf("set ok\n"); }else{ printf("set fail\n"); } if(reply) freeReplyObject(reply); //--------------get-------------// reply = (redisReply*)cr.redis_command(slot_id, false, "lrange %s 0 -1", key); if (reply && reply->type == REDIS_REPLY_ARRAY) { for(int i=0; i<reply->elements; ++i){ printf("val:%s\n",reply->element[i]->str); } } if(reply) freeReplyObject(reply); } // -------------- sorted set -------------------// { //--------------set-------------// redisReply *reply = NULL; char *key = "kx"; int32_t slot_id = keyHashSlot(key, (int)strlen(key)); reply = (redisReply*)cr.redis_command(slot_id, true, "zadd %s 3 m1 90 m2 -9 m3",key); if (reply && reply->type == REDIS_REPLY_INTEGER) { printf("set ok\n"); }else{ printf("set fail\n"); } if(reply) freeReplyObject(reply); //--------------get-------------// reply = (redisReply*)cr.redis_command(slot_id, false, "zrange %s 0 -1 withscores",key); if (reply && reply->type == REDIS_REPLY_ARRAY) { for(int i=0; i<reply->elements; ++i){ printf("val:%s\n",reply->element[i]->str); } } if(reply) freeReplyObject(reply); } // -------------- hash -------------------// { //--------------set-------------// redisReply *reply = NULL; char *key = "k5"; int32_t slot_id = keyHashSlot(key, (int)strlen(key)); reply = (redisReply*)cr.redis_command(slot_id, true, "hmset %s f1 v1 f2 v2 f3 v3",key); printf("------reply type:%d\n",reply->type); if (reply && reply->type == REDIS_REPLY_STATUS) { printf("set ok\n"); }else{ printf("set fail\n"); } if(reply) freeReplyObject(reply); //--------------get-------------// reply = (redisReply*)cr.redis_command(slot_id, false, "hgetall %s",key); if (reply && reply->type == REDIS_REPLY_ARRAY) { for(int i=0; i<reply->elements; ++i){ printf("val:%s\n",reply->element[i]->str); } } if(reply) freeReplyObject(reply); } cr.Uninit(); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2009 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #include "core/pch.h" #ifdef _MIME_SUPPORT_ #include "modules/mime/mimedec2.h" #include "modules/mime/mimeutil.h" #include "modules/olddebug/tstdump.h" MIME_Multipart_Related_Decoder::MIME_Multipart_Related_Decoder(HeaderList &hdrs, URLType url_type) : MIME_Multipart_Decoder(hdrs, url_type) { } MIME_Multipart_Related_Decoder::~MIME_Multipart_Related_Decoder() { } void MIME_Multipart_Related_Decoder::HandleHeaderLoadedL() { MIME_Multipart_Decoder::HandleHeaderLoadedL(); if(content_type_header) { ParameterList *parameters = content_type_header->SubParameters(); Parameters *param = parameters->GetParameterByID(HTTP_General_Tag_Start, PARAMETER_ASSIGNED_ONLY); if(param && param->Value()) { URL temp_url = ConstructContentIDURL_L(param->Value() #ifdef URL_SEPARATE_MIME_URL_NAMESPACE , GetContextID() #endif ); related_start_url.SetURL(temp_url); } } if(GetContentLocationBaseURL().IsEmpty() && cloc_url.IsEmpty()) { cloc_url = ConstructAttachmentURL_L(NULL, NULL, NULL,NULL); SetContentLocationBaseURL(cloc_url); info.cloc_base_is_local = TRUE; } } MIME_Decoder *MIME_Multipart_Related_Decoder::GetRootPart() { MIME_Decoder *root = sub_elements.First(); if (!related_start_url->IsEmpty()) { while (root) { if (root->GetAttachmentURL() == related_start_url.GetURL() || root->GetContentIdURL() == related_start_url.GetURL()) break; root = root->Suc(); } if (!root) root = sub_elements.First(); } return root; } URL MIME_Multipart_Related_Decoder::GetRelatedRootPart() { MIME_Decoder *root = GetRootPart(); return root ? root->GetAttachmentURL() : URL(); } void MIME_Multipart_Related_Decoder::WriteDisplayDocumentL(URL &target, DecodedMIME_Storage *attach_target) { if(!info.finished) return; // wait until finished current_display_item = GetRootPart(); if(current_display_item) current_display_item->RetrieveDataL(target, attach_target); info.displayed = TRUE; } void MIME_Multipart_Related_Decoder::WriteDisplayAttachmentsL(URL &target, DecodedMIME_Storage *attach_target, BOOL display_as_links) { display_attachment_list = TRUE; if (current_display_item) { OpAutoVector<SubElementId> subElementIds; BOOL allDisplayableInline = TRUE; for (MIME_Decoder* mdec = sub_elements.First(); mdec; mdec = mdec->Suc()) if (mdec != current_display_item) { if (mdec->IsDisplayableInline()) { SubElementId* subElementId = OP_NEW(SubElementId, (mdec, mdec->headers)); if (subElementId && !OpStatus::IsSuccess(subElementIds.Add(subElementId))) OP_DELETE(subElementId); } else allDisplayableInline = FALSE; } if (current_display_item->ReferenceAll(subElementIds) && allDisplayableInline) display_attachment_list = FALSE; } MIME_Multipart_Decoder::WriteDisplayAttachmentsL(target, attach_target, display_as_links); } SubElementId::SubElementId(MIME_Decoder* decoder, HeaderList& headers) { mdec = decoder; HTTP_Header_Tags headerTags[2] = {HTTP_Header_Content_ID, HTTP_Header_Content_Location}; for (int i=0; i<2; i++) { id[i] = NULL; idLength[i] = 0; HeaderEntry* entry = headers.GetHeaderByID(headerTags[i]); if (entry && entry->Value()) { const char* str = entry->Value(); unsigned long strLen = (unsigned long)op_strlen(str); const char* pos; // Remove enclosing '<' '>' if (str[0] == '<' && str[strLen-1] == '>') str++, strLen-=2; // Remove everything after the first '&' ('&' in urls may be escaped, making the search miss) if ((pos = op_strchr(str,'&')) != NULL) strLen = (unsigned long)(pos-str); // Remove everything up to the last '/' that is not at the end for (pos=str+strLen-2; pos>=str; pos--) if (*pos == '/') { strLen -= (unsigned long)(pos+1-str); str = pos+1; break; } // Remove trailing '/' if (strLen>0 && str[strLen-1] == '/') strLen--; // If the id is too short, the chance of false positive detection // is too high. It is then better to list the attachment if (strLen < 4) strLen = 0; id[i] = strLen ? str : NULL; idLength[i] = strLen; } } found = FALSE; } unsigned long SubElementId::MaxLength(unsigned long maxLength) { for (int i=0; i<2; i++) if (maxLength < idLength[i]) maxLength = idLength[i]; return maxLength; } BOOL SubElementId::FindIn(const uni_char* buffer, unsigned long length) { for (int i=0; i<2 && !found; i++) { const unsigned char* str = (const unsigned char*)id[i]; unsigned long strLen = idLength[i]; if (str && length >= strLen) { uni_char first = (uni_char)str[0]; for (unsigned long pos=0; pos<length-strLen+1; pos++) if (buffer[pos] == first) { unsigned long off; for (off=1; off<strLen; off++) if (buffer[pos+off] != (uni_char)str[off]) break; if (off == strLen) { found = TRUE; break; } } } } if (found) mdec->SetDisplayed(TRUE); return found; } #endif // MIME_SUPPORT
#pragma once #include <SFML/Graphics.hpp> #include <math.h> #include <iostream> using namespace std; class worker { public: worker(sf::Vector2f start, sf::Vector2f position, sf::Vector2i range); ~worker(); void update(float t); void render(sf::RenderWindow& window); bool catchCheck(sf::Vector2f player); sf::FloatRect boundingBox(); sf::Vector2f workerPosition() { return position; } // return current positon sf::Vector2f workerSize() { return size; } bool collisionCheck(sf::FloatRect object); void inTheRoom() { m_inRoom = true; } private: void bounceOff(); bool m_inRoom; float timer; sf::Vector2f size; float speed; float rotation; float radian; float PI; float distanceToPlayer; sf::Vector2f velocity; sf::Vector2f position; sf::Texture m_texture; sf::Sprite m_sprite; sf::Vector2f m_target; sf::Vector2f m_randomOrigin; sf::Vector2i m_randomRange; float radius; float viewAngle; float viewRange; void wander(sf::Vector2f player, float t); };
#include <bits/stdc++.h> using namespace std; vector<string> split_string(string); // Complete the roadsAndLibraries function below. long roadsAndLibraries(int n, int c_lib, int c_road, vector<vector<int>> cities) { if (c_lib <= c_road) { return c_lib * n; } long cost = 0; map<int, vector<int>> c; vector<bool> v(n + 1); // cities to visit // Add roads to map for (auto r : cities) { c[r[0]].push_back(r[1]); c[r[1]].push_back(r[0]); } for (int i = 1; i <= n; i++) { stack<int> s; int nodes = 0; if (!v[city]) { s.push(city); v[city] = true; while (!s.empty()) { int visit = s.top(); s.pop(); for (auto connected : c[visit]) { if (!v[connected]) { v[connected] = true; s.push(connected); nodes++; } } } cost += (nodes) ? long(nodes) * c_road + c_lib : c_lib; } } } } } if (!visited.empty()) { cost += (visited.size() - 1) * c_road; cost += c_lib; logged.insert(visited.begin(), visited.end()); } cost += (n - logged.size()) * c_lib; return cost; } int main() { ofstream fout(getenv("OUTPUT_PATH")); int q; cin >> q; cin.ignore(numeric_limits<streamsize>::max(), '\n'); for (int q_itr = 0; q_itr < q; q_itr++) { string nmC_libC_road_temp; getline(cin, nmC_libC_road_temp); vector<string> nmC_libC_road = split_string(nmC_libC_road_temp); int n = stoi(nmC_libC_road[0]); int m = stoi(nmC_libC_road[1]); int c_lib = stoi(nmC_libC_road[2]); int c_road = stoi(nmC_libC_road[3]); vector<vector<int>> cities(m); for (int i = 0; i < m; i++) { cities[i].resize(2); for (int j = 0; j < 2; j++) { cin >> cities[i][j]; } cin.ignore(numeric_limits<streamsize>::max(), '\n'); } long result = roadsAndLibraries(n, c_lib, c_road, cities); fout << result << "\n"; } fout.close(); return 0; } vector<string> split_string(string input_string) { string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { return x == y and x == ' '; }); input_string.erase(new_end, input_string.end()); while (input_string[input_string.length() - 1] == ' ') { input_string.pop_back(); } vector<string> splits; char delimiter = ' '; size_t i = 0; size_t pos = input_string.find(delimiter); while (pos != string::npos) { splits.push_back(input_string.substr(i, pos - i)); i = pos + 1; pos = input_string.find(delimiter, i); } splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); return splits; }
#include <algorithm> #include <cctype> #include <gsl/gsl> #include <regex> #include <benchmark/benchmark.h> #include "Files.h" #include <FuzzySearch.h> std::vector<std::string> StringSearch(const std::vector<std::string>& split_by_space, const std::vector<std::string>& files) { std::vector<std::string> results; results.reserve(files.size()); for (std::string file : files) { std::transform(file.begin(), file.end(), file.begin(), [](char c) { return gsl::narrow_cast<char>(std::tolower(c)); }); size_t found_count = 0; for (const std::string& str : split_by_space) { const auto found = file.find_last_of(str); if (found != std::string::npos) { ++found_count; } else { break; } } if (found_count == split_by_space.size()) { results.push_back(file); } } return results; } std::vector<std::string> RegexSearch(const std::vector<std::string>& split_by_space, const std::vector<std::string>& files) { std::vector<std::string> results; results.reserve(files.size()); for (const std::string& str : split_by_space) { std::regex self_regex(str, std::regex_constants::icase); for (const std::string& file : files) { if (std::regex_search(file, self_regex)) { results.push_back(file); } } } return results; } std::vector<std::string> BoyerMoore(const std::vector<std::string>& split_by_space, const std::vector<std::string>& files) { std::vector<std::string> results; results.reserve(files.size()); for (const std::string& str : split_by_space) { for (const std::string& file : files) { auto it = std::search(file.cbegin(), file.cend(), std::boyer_moore_horspool_searcher(str.begin(), str.end())); if (it != file.end()) { results.push_back(file); } } } return results; } static std::string_view GetStringFunc(std::string_view string) { return string; } #define FUZZY_SEARCH_BENCHMARK(BENCHMARK_NAME) BENCHMARK(BENCHMARK_NAME)->Repetitions(2)->Unit(benchmark::kMicrosecond) void BM_FuzzyLongPattern(benchmark::State& state) { std::vector<std::string> files; for (const char* str : FuzzySearchBenchmark::FILES) { files.push_back(str); } for (const auto _ : state) { std::vector<FuzzySearch::SearchResult> results = FuzzySearch::Search("qt base view list", files.begin(), files.end(), &GetStringFunc, FuzzySearch::MatchMode::E_SOURCE_FILES); benchmark::DoNotOptimize(results); } } FUZZY_SEARCH_BENCHMARK(BM_FuzzyLongPattern); void BM_FuzzyShortPattern(benchmark::State& state) { std::vector<std::string> files; for (const char* str : FuzzySearchBenchmark::FILES) { files.push_back(str); } for (const auto _ : state) { std::vector<FuzzySearch::SearchResult> results = FuzzySearch::Search("TABLE", files.begin(), files.end(), &GetStringFunc, FuzzySearch::MatchMode::E_SOURCE_FILES); benchmark::DoNotOptimize(results); } } FUZZY_SEARCH_BENCHMARK(BM_FuzzyShortPattern); void BM_BoyerMooreLongPattern(benchmark::State& state) { std::vector<std::string> files; for (const char* str : FuzzySearchBenchmark::FILES) { files.push_back(str); } std::vector<std::string> split_by_space = {"qt", "base", "view", "list"}; for (const auto _ : state) { std::vector<std::string> results = BoyerMoore(split_by_space, files); benchmark::DoNotOptimize(results); } } FUZZY_SEARCH_BENCHMARK(BM_BoyerMooreLongPattern); void BM_BoyerMooreShortPattern(benchmark::State& state) { std::vector<std::string> files; for (const char* str : FuzzySearchBenchmark::FILES) { files.push_back(str); } std::vector<std::string> split_by_space = {"TABLE"}; for (const auto _ : state) { std::vector<std::string> results = BoyerMoore(split_by_space, files); benchmark::DoNotOptimize(results); } } FUZZY_SEARCH_BENCHMARK(BM_BoyerMooreShortPattern); void BM_FindLongPattern(benchmark::State& state) { std::vector<std::string> files; for (const char* str : FuzzySearchBenchmark::FILES) { files.push_back(str); } std::vector<std::string> split_by_space = {"qt", "base", "view", "list"}; for (const auto _ : state) { std::vector<std::string> results = StringSearch(split_by_space, files); benchmark::DoNotOptimize(results); } } FUZZY_SEARCH_BENCHMARK(BM_FindLongPattern); void BM_FindShortPattern(benchmark::State& state) { std::vector<std::string> files; for (const char* str : FuzzySearchBenchmark::FILES) { files.push_back(str); } std::vector<std::string> split_by_space = {"TABLE"}; for (const auto _ : state) { std::vector<std::string> results = StringSearch(split_by_space, files); benchmark::DoNotOptimize(results); } } FUZZY_SEARCH_BENCHMARK(BM_FindShortPattern); void BM_RegexLongPattern(benchmark::State& state) { std::vector<std::string> files; for (const char* str : FuzzySearchBenchmark::FILES) { files.push_back(str); } std::vector<std::string> split_by_space = {"qt", "base", "view", "list"}; for (const auto _ : state) { std::vector<std::string> results = RegexSearch(split_by_space, files); benchmark::DoNotOptimize(results); } } FUZZY_SEARCH_BENCHMARK(BM_RegexLongPattern); void BM_RegexShortPattern(benchmark::State& state) { std::vector<std::string> files; for (const char* str : FuzzySearchBenchmark::FILES) { files.push_back(str); } std::vector<std::string> split_by_space = {"TABLE"}; for (const auto _ : state) { std::vector<std::string> results = RegexSearch(split_by_space, files); benchmark::DoNotOptimize(results); } } FUZZY_SEARCH_BENCHMARK(BM_RegexShortPattern); BENCHMARK_MAIN();
#include<bits/stdc++.h> using namespace std; main() { int n; while(cin>>n) { int i, a, b, p=0; for(i=1; i<=n; i++) { cin>>a>>b; if(a!=b)p=1; } if(p==1) printf("Happy Alex\n"); else printf("Poor Alex\n"); } return 0; }
#include <iostream> using namespace std; int main(){ enum Sex{ MALE, FEMALE = -2, UNKNOWN, WHAT }; cout << MALE << FEMALE << UNKNOWN << WHAT << endl; int a = 2, b = 3; int arr[] = {1, a, 3}; cout << arr[1] << endl; printf("%p\n", &a); printf("%p\n", &b); printf("%p\n", &arr[0]); printf("%p\n", &arr[1]); printf("%p\n", &arr[2]); return 0; }
int test1(int x) { return x+1; } int main() { int x = test1(1); return 0; }
#include <iostream> #include "Matrix.h" #include "ComplexNumber.h" #include "IntervalNumber.h" using namespace std; /* * TO DO: Причесать мейн */ int main(int argc, char * argv[]) { Matrix< ComplexNumber > CompMatrixA(3,3), CompMatrixB(3, 3), CompMatrixC; Matrix <IntervalNumber> IntervalMatrixA(3, 3), IntervalMatrixB(3, 3), IntervalMatrixC; cout << "Now the matrix A of complex numbers will be introduced \n"; /*cin >> CompMatrixA;*/ CompMatrixA.rand_value(); cout << endl << CompMatrixA; cout << "Now the matrix B of complex numbers will be introduced \n"; /*cin >> CompMatrixB;*/ CompMatrixB.rand_value(); cout << endl << CompMatrixB; CompMatrixC = CompMatrixA - CompMatrixB; cout << endl << CompMatrixC; cout << "Now the matrix A of interval numbers will be introduced \n"; /*cin >> CompMatrixA;*/ IntervalMatrixA.rand_value(); cout << endl << IntervalMatrixA; cout << "Now the matrix B of interval numbers will be introduced \n"; /*cin >> CompMatrixB;*/ IntervalMatrixB.rand_value(); cout << endl << IntervalMatrixB; IntervalMatrixC = IntervalMatrixA - IntervalMatrixB; cout << endl << IntervalMatrixC; system("pause"); }
#pragma once #include "ofMain.h" class Misc { public: Misc(); ~Misc(); static ofFbo::Settings getDefaultFboSettings(); static std::vector< ofPoint > getLineSplitPoints( ofPolyline linesToSplit, float length ); static void drawSplitLines( std::vector< ofPoint > points ); };
//#include <iostream> #include <stdio.h> //#include <vector> #include <map> //#include <queue> //#include <set> //#include <math.h> #include <algorithm> //#include <sstream> //#include <cmath> //#include <iterator> using namespace std; char grid[100][100]; //int number of 1`s //(i,j) start point of region int out_img(int i,int j,int n,int t){ if(n==1&&grid[i][j]=='1') return 1; if(n==1&&grid[i][j]=='0') return 0; //get 4 region number of 1 int ur=out_img(i,j+(n/2),n/2,t); //upper-right int ul=out_img(i,j,n/2,t); //upper-left int ll=out_img(i+(n/2),j,n/2,t); //lower-left int lr=out_img(i+(n/2),j+(n/2),n/2,t); //lower-right //count 1 int sum1 = 0; sum1 += ur; sum1 += ul; sum1 += ll; sum1 += lr; //count 0 int sum0 = 0; sum0 += n*n; sum0 -= sum1; //check counter char all = 'x'; float nn = n*n; int zero = sum0/nn *100; int one = sum1/nn *100; if(zero>=t) all='0'; if(one>=t) all='1'; //change grid if(all!='x') for(int k=0; k<n; k++) for(int o=0; o<n; o++) grid[i+k][j+o]=all; return sum1; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt","rt",stdin); freopen ("output.txt","wt",stdout); #endif //INPUT int n,t; int icase=0; scanf("%d %d\n",&n,&t); while(n!=0){ icase++; char x; for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ scanf("%c",&x); grid[i][j]=x; }scanf("\n",&x); } ///////////////////////// out_img(0,0,n,t); printf("Image %d:\n",icase); for(int i=0 ; i<n; i++){ for(int j=0 ; j<n; j++){ x=grid[i][j]; printf("%c",x); }printf("\n"); } //////////////////////// scanf("%d %d\n",&n,&t); } #ifndef ONLINE_JUDGE fclose(stdin); fclose(stdout); #endif return 0; }
#include "../include/router_input.hh" #include "../include/util.hh" #include <sstream> #include <iostream> #include <netinet/ip.h> #include <netinet/ether.h> router_input::router_input( std::shared_ptr<tracker> trk, std::shared_ptr<output> out, std::string input_interface, int cluster_id ) : trk(trk), out(out), log(logger::get_logger("router-input")) { std::string program_name("aurora-router-rxtx"); // these 3 will throw if bad this->interface_addr = get_interface_v4_addr(input_interface); this->interface_mtu = get_interface_mtu(input_interface); this->interface_hwaddr = get_interface_hw_addr(input_interface); std::stringstream errmsg; int ret; this->ring = pfring_open(input_interface.c_str(), this->interface_mtu, PF_RING_PROMISC); if(this->ring == nullptr) { errmsg << "failed to initialize pf_ring"; this->log->message(errmsg.str()); throw std::runtime_error(errmsg.str()); } if((ret = pfring_set_application_name(this->ring, const_cast<char*>(program_name.c_str()))) != 0) { pfring_close(this->ring); this->ring = nullptr; errmsg << "pfring_set_application_name(): " << ret; this->log->message(errmsg.str()); throw std::runtime_error(errmsg.str()); } if((ret = pfring_set_socket_mode(this->ring, send_and_recv_mode)) != 0) { pfring_close(this->ring); this->ring = nullptr; errmsg << "pfring_set_socket_mode(): " << ret; this->log->message(errmsg.str()); throw std::runtime_error(errmsg.str()); } if((ret = pfring_set_direction(this->ring, rx_only_direction)) != 0) { pfring_close(this->ring); this->ring = nullptr; errmsg << "pfring_set_direction(): " << ret; this->log->message(errmsg.str()); throw std::runtime_error(errmsg.str()); } if(input_interface.find("zc:") == std::string::npos && input_interface.find("myri") == std::string::npos) { this->zc = false; if((ret = pfring_set_cluster(this->ring, cluster_id, cluster_per_flow_2_tuple)) != 0) { pfring_close(this->ring); this->ring = nullptr; errmsg << "pfring_set_cluster(): " << ret; this->log->message(errmsg.str()); throw std::runtime_error(errmsg.str()); } } else { this->zc = true; } this->running = false; this->min_size = sizeof(ether_header); this->min_size_ip4 = sizeof(ether_header)+sizeof(iphdr); this->min_size_arp = sizeof(ether_header)+sizeof(_arphdr); this->auto_add = true; errmsg << "prepared on " << input_interface; this->log->message(errmsg.str()); this->total_packets = 0; this->forwarded_packets = 0; } router_input::~router_input() { if(this->ring != nullptr) { pfring_close(this->ring); this->ring = nullptr; } } void router_input::start() { int ret; std::stringstream errmsg; if((ret = pfring_enable_ring(this->ring)) != 0) { pfring_close(this->ring); this->ring = nullptr; errmsg << "pfring_enable_ring(): " << ret; this->log->message(errmsg.str()); throw std::runtime_error(errmsg.str()); } this->running = true; this->router_thread = std::thread([this]{ u_char* pkt_buff = new u_char[this->interface_mtu]; u_char* pkt_ptr = pkt_buff; int pfring_ret = 0; pfring_pkthdr hdr; if(this->zc) { while(this->running) { pfring_ret = 0; if((pfring_ret = pfring_recv(this->ring, &pkt_ptr, 0, &hdr, false)) > 0) { handle_packet(&hdr, pkt_ptr); } else { std::this_thread::sleep_for(std::chrono::duration<int, std::nano>(100)); } } } else { while(this->running) { pfring_ret = 0; if((pfring_ret = pfring_recv(this->ring, &pkt_ptr, this->interface_mtu, &hdr, false)) > 0) { handle_packet(&hdr, pkt_ptr); } else { std::this_thread::sleep_for(std::chrono::duration<int, std::nano>(100)); } } } delete[] pkt_buff; }); this->log->message("capture started"); } void router_input::stop() { this->running = false; if(this->router_thread.joinable()) { this->router_thread.join(); this->log->message("capture stopped"); } } void router_input::handle_arp_request(pfring_pkthdr* hdr, u_char* pkt) { _arphdr* arp_hdr = reinterpret_cast<_arphdr*>(pkt + sizeof(ether_header)); if(arp_hdr->ar_op != htons(ARPOP_REQUEST)) return; if(*reinterpret_cast<uint32_t*>(arp_hdr->__ar_tip) == this->interface_addr) { this->send_arp_reply(hdr, pkt, arp_hdr); } } void router_input::send_arp_reply(pfring_pkthdr* hdr, u_char* pkt, _arphdr* arp_info) { ether_header* ether_hdr = reinterpret_cast<ether_header*>(pkt); memcpy(ether_hdr->ether_dhost, ether_hdr->ether_shost, ETH_ALEN); memcpy(ether_hdr->ether_shost, &this->interface_hwaddr.addr, ETH_ALEN); memcpy(arp_info->__ar_tha, arp_info->__ar_sha, ETH_ALEN); memcpy(arp_info->__ar_sha, &this->interface_hwaddr.addr, ETH_ALEN); memcpy(arp_info->__ar_tip, arp_info->__ar_sip, 4); memcpy(arp_info->__ar_sip, reinterpret_cast<u_char*>(&this->interface_addr), 4); arp_info->ar_op = htons(ARPOP_REPLY); pfring_send(this->ring, reinterpret_cast<char*>(pkt), sizeof(ether_header)+sizeof(_arphdr), 1); } void router_input::handle_packet(pfring_pkthdr* hdr, u_char* pkt) { if(hdr->caplen < this->min_size) return; ether_header* ether_hdr = reinterpret_cast<ether_header*>(pkt); uint16_t ethertype = ntohs(ether_hdr->ether_type); if(ethertype == ETHERTYPE_ARP) { if(hdr->caplen < this->min_size_arp) return; if(this->zc) this->handle_arp_request(hdr, pkt); return; } if(ethertype != ETHERTYPE_IP) return; if(hdr->caplen < this->min_size_ip4) return; iphdr* ip_hdr = reinterpret_cast<iphdr*>(ether_hdr + 1); if(this->auto_add) { // ignore mcast if((*reinterpret_cast<u_char*>(&ip_hdr->daddr) & 0xe0) == 0xe0) return; bool old_address = trk->destinationlist_source(&ip_hdr->daddr); if(!old_address) { std::stringstream msg; inet_ntop(AF_INET, &(ip_hdr->daddr), addr, INET_ADDRSTRLEN); msg << "auto-destlisted " << addr; this->log->message(msg.str()); msg.str(""); } } ++total_packets; if(trk->whitelist_cmp(&ip_hdr->saddr)) { this->out->forward(hdr, pkt); ++forwarded_packets; } } void router_input::load_forwarding_stats(uint64_t* total_packets, uint64_t* forwarded_packets) { *total_packets = this->total_packets; *forwarded_packets = this->forwarded_packets; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #include "adjunct/quick_toolkit/widgets/OpWindowMover.h" #include "adjunct/quick_toolkit/windows/DesktopWindow.h" DEFINE_CONSTRUCT(OpWindowMover); OpWindowMover::OpWindowMover() : OpButton(TYPE_CUSTOM, STYLE_TEXT) , m_window(NULL) , m_moving(false) { SetJustify(JUSTIFY_LEFT, FALSE); } void OpWindowMover::OnMouseMove(const OpPoint& point) { if (m_moving && m_window) { INT32 x, y; m_window->GetOuterPos(x, y); x += point.x - m_down_point.x; y += point.y - m_down_point.y; OpWindow* parent_window = m_window->GetOpWindow()->GetParentWindow(); if (parent_window) { // Limit position within the parent so the user can move it back again. UINT32 parent_w, parent_h; parent_window->GetInnerSize(&parent_w, &parent_h); int extra = 4; x = MAX(x, -m_down_point.x + extra); y = MAX(y, -m_down_point.y + extra); x = MIN(x, (INT32)parent_w - m_down_point.x - extra); y = MIN(y, (INT32)parent_h - m_down_point.y - extra); } m_window->SetOuterPos(x, y); } } void OpWindowMover::OnMouseDown(const OpPoint& point, MouseButton button, UINT8 nclicks) { if (button == MOUSE_BUTTON_1) { m_down_point = point; m_moving = true; } } void OpWindowMover::OnMouseUp(const OpPoint& point, MouseButton button, UINT8 nclicks) { m_moving = false; }
#include "rdtsc_benchmark.h" #include "ut.hpp" #include <random> #include <algorithm> #include <math.h> #include <functional> #include <vector> #include "linalg.h" using namespace boost::ut; // provides `expect`, `""_test`, etc using namespace boost::ut::bdd; // provides `given`, `when`, `then` // // DataLoader for Benchmark 1 // auto data_loader(__m256d const r0, __m256d const r1, __m256d const r2, __m256d const r3, __m256d *inv0, __m256d *inv1, __m256d *inv2, __m256d *inv3) { } void inv_2x2_x4(__m256d const r0, __m256d const r1, __m256d const r2, __m256d const r3, __m256d *inv0, __m256d *inv1, __m256d *inv2, __m256d *inv3) { double A[16], Ainv[16]; _mm256_store_pd(A+0, r0); _mm256_store_pd(A+4, r1); _mm256_store_pd(A+8, r2); _mm256_store_pd(A+12, r3); inv_2x2(A+0, Ainv+0); inv_2x2(A+4, Ainv+4); inv_2x2(A+8, Ainv+8); inv_2x2(A+12, Ainv+12); } int main() { // Declaration of inputs + test double A[16] __attribute__ ((aligned(32))); for (int i = 0; i < 16; i++) { A[i] = i; } __m256d const r0 = _mm256_load_pd( A+0 ); __m256d const r1 = _mm256_load_pd( A+4 ); __m256d const r2 = _mm256_load_pd( A+8 ); __m256d const r3 = _mm256_load_pd( A+12 ); double Inv[16] __attribute__ ((aligned(32))); __m256d inv0, inv1, inv2, inv3; batch_inverse_2x2(r0, r1, r2, r3, &inv0, &inv1, &inv2, &inv3); _mm256_store_pd( Inv+0, inv0 ); _mm256_store_pd( Inv+4, inv1 ); _mm256_store_pd( Inv+8, inv2 ); _mm256_store_pd( Inv+12, inv3 ); double AInv[16]; for (size_t i = 0; i < 4; i++) { inv_2x2(A+i*4, AInv+i*4); for (size_t j = 0; j < 4; j++) { expect(fabs(Inv[i*4+j] - AInv[i*4+j]) < 1e-10) << Inv[i*4+j] << " != " << AInv[i*4+j]; } } // ----------------------------------------- // // --------------- BENCHMARK --------------- // // ----------------------------------------- // Benchmark<decltype(&batch_inverse_2x2)> bench_u4avx("inv_2x2 benchmark (UNROLLEDx4)"); bench_u4avx.data_loader = data_loader; bench_u4avx.add_function(&inv_2x2_x4, "base_x4", 0.0); bench_u4avx.funcFlops[0] = 4*inv_2x2_flops(A, AInv); bench_u4avx.funcBytes[0] = 0; bench_u4avx.add_function(&batch_inverse_2x2, "batch_inverse_2x2", 0.0); bench_u4avx.funcFlops[1] = 4*inv_2x2_flops(A, AInv); bench_u4avx.funcBytes[1] = 0; bench_u4avx.run_benchmark(r0, r1, r2, r3, &inv0, &inv1, &inv2, &inv3); return 0; }
ZombieStalkerScientist[] = { {Loot_MAGAZINE, 5, FoodMRE}, {Loot_MAGAZINE, 1, ItemHotwireKit}, {Loot_GROUP, 3, MedicalLow}, {Loot_GROUP, 10, AmmoMilitaryZed}, {Loot_GROUP, 2, Consumable} }; ZombieStalkerScientistViral[] = { {Loot_GROUP, 10, ZombieStalkerScientist}, {Loot_MAGAZINE, 1, ItemAntibiotic1} }; ZombieStalkerDuty[] = { {Loot_MAGAZINE, 5, FoodMRE}, {Loot_MAGAZINE, 1, ItemHotwireKit}, {Loot_GROUP, 3, MedicalLow}, {Loot_GROUP, 10, AmmoMilitaryZed}, {Loot_GROUP, 2, Consumable} }; ZombieStalkerDutyViral[] = { {Loot_GROUP, 10, ZombieStalkerDuty}, {Loot_MAGAZINE, 1, ItemAntibiotic1} }; ZombieStalkerMilitary[] = { {Loot_MAGAZINE, 5, FoodMRE}, {Loot_MAGAZINE, 1, ItemHotwireKit}, {Loot_GROUP, 3, MedicalLow}, {Loot_GROUP, 10, AmmoMilitaryZed}, {Loot_GROUP, 2, Consumable} }; ZombieStalkerMilitaryViral[] = { {Loot_GROUP, 10, ZombieStalkerMilitary}, {Loot_MAGAZINE, 1, ItemAntibiotic1} }; ZombieStalkerNeutral[] = { {Loot_MAGAZINE, 5, FoodMRE}, {Loot_MAGAZINE, 1, ItemHotwireKit}, {Loot_GROUP, 3, MedicalLow}, {Loot_GROUP, 10, AmmoMilitaryZed}, {Loot_GROUP, 2, Consumable} }; ZombieStalkerNeutralViral[] = { {Loot_GROUP, 10, ZombieStalkerNeutral}, {Loot_MAGAZINE, 1, ItemAntibiotic1} }; ZombieStalkerFreedom[] = { {Loot_MAGAZINE, 5, FoodMRE}, {Loot_MAGAZINE, 1, ItemHotwireKit}, {Loot_GROUP, 3, MedicalLow}, {Loot_GROUP, 10, AmmoMilitaryZed}, {Loot_GROUP, 2, Consumable} }; ZombieStalkerFreedomViral[] = { {Loot_GROUP, 10, ZombieStalkerFreedom}, {Loot_MAGAZINE, 1, ItemAntibiotic1} }; ZombieStalkerMonolith[] = { {Loot_MAGAZINE, 5, FoodMRE}, {Loot_MAGAZINE, 1, ItemHotwireKit}, {Loot_GROUP, 3, MedicalLow}, {Loot_GROUP, 10, AmmoMilitaryZed}, {Loot_GROUP, 2, Consumable} }; ZombieStalkerMonolithViral[] = { {Loot_GROUP, 10, ZombieStalkerMonolith}, {Loot_MAGAZINE, 1, ItemAntibiotic1} };
// // Reliability.h // superasteroids // // Created by Cristian Marastoni on 12/06/14. // // #pragma once #include "Internal.h" class Connection; class Channel; class Reliability { public: Reliability(); ~Reliability(); void Reset(); void RegisterChannel(Channel *channel); void AddSentPacket(NetMessageHeader const &header, uint8 const *data); void HandleAck(uint8 channel, uint16 sequence); void HandleMessage(NetMessageHeader const &header, BitStream const &data); void OutputMessages(); void Update(); private: typedef ListNode<NetPacket> listnode_t; void InsertSorted(NetPacket *packet); void ClearPacketList(listnode_t *root); void RemovePacket(listnode_t *root, NetPacket *packet); void InsertPacket(listnode_t *node, NetPacket *packet); Channel *mChannel; listnode_t mSentPacket; listnode_t mOutOfOrder; };
#include "point.h" #include <iostream> using namespace std; Point::Point(int x, int y) :xpos(x), ypos(y) { } ostream& operator<< (ostream& ostm, const Point& ref) { ostm << '[' << ref.xpos << ", " << ref.ypos << ']' << endl; return ostm; } void Point::showPosition() const { cout << '[' << xpos << ", " << ypos << ']' << endl; } void Point::setPos(int x,int y) { xpos = x; ypos = y; }
#pragma once #include "Item.h" #include "Color.h" class Inventory : public Color { protected: vector<tagItemInfo> m_vItem; vector<tagItemInfo>::iterator m_viItem; tagItemInfo m_equipArmor; tagItemInfo m_equipWeapon; public: Inventory(); ~Inventory(); // 인벤토리 보여주기 int ShowInventory(int selectNum); // 아이템 추가 void AddItem(tagItemInfo item); // 아이템 판매 tagItemInfo SellItem(int num, int& gold); // 아이템 장착 void EquipItem(int num); tagItemInfo GetEquipArmor() { return m_equipArmor; } void SetEquipArmor(tagItemInfo equipArmor) { m_equipArmor = equipArmor; } tagItemInfo GetEquipWeapon() { return m_equipWeapon; } void SetEquipWeapon(tagItemInfo equipWeapon) { m_equipWeapon = equipWeapon; } };
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "1614" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 100000 pair<int,int> table[MAXN+5]; int ANS[MAXN+5]; int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif int num; while( ~scanf("%d",&num) ){ for(int i = 0 ; i < num ; i++ ){ scanf("%d",&table[i].first); table[i].second = i; } sort(&table[0],&table[num]); int a = 0,b = 0; for(int i = num-1 ; i >= 0 ; i-- ){ if( a > b ){ b += table[i].first; ANS[table[i].second] = 1; } else{ a += table[i].first; ANS[table[i].second] = -1; } } if( a == b ){ printf("Yes\n"); for(int i = 0 ; i < num-1 ; i++ ) printf("%d ",ANS[i] ); printf("%d\n",ANS[num-1] ); } else printf("No\n"); } return 0; }
// 0921_5.cpp : 定义控制台应用程序的入口点。 //蟠桃记 //第一天悟空吃掉桃子总数一半多一个,第二天又将剩下的桃子吃掉一半多一个,以后每天吃掉前一天剩下的一半多一个, //到第n天准备吃的时候只剩下一个桃子。聪明的你,请帮悟空算一下,他第一天开始吃的时候桃子一共有多少个呢? #include <iostream> using namespace std; int main() { int n; while (cin >> n) { if (n <= 1 || n >= 30) break; int sum = 1; int i; for (i = 1; i <n; i++) { sum = (sum + 1) * 2; } cout << sum << endl; } return 0; }
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define rep1(i, n) for(int i = 1; i <= (int)(n); i++) #define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;} #define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;} typedef long long ll; typedef pair<int, int> P; ll gcd(int x, int y){ return y?gcd(y, x%y):x;} ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);} bool ab[100000]={0}; bool ac[100000]={0}; bool bc[100000]={0}; bool isMatch(const char a, const char b){ return ((a==b)||(a=='?')||(b=='?')); } int main() { string a, b, c; cin >> a >> b >> c; int sa, sb, sc; sa = (int)a.size(); sb = (int)b.size(); sc = (int)c.size(); rep(i, sa)rep(j, sb) if(!isMatch(a[i],b[j])) ab[50000+i-j]=true; rep(i, sa)rep(j, sc) if(!isMatch(a[i],c[j])) ac[50000+i-j]=true; rep(i, sb)rep(j, sc) if(!isMatch(b[i],c[j])) bc[50000+i-j]=true; int M = 2000; int ans = 3*M; for(int i=-2*M; i<=2*M;i++) for(int j=-2*M; j<=2*M;j++){ if(!ab[50000+i] && !ac[50000+j] && !bc[j-i+50000]){ int L = min(0, min(i,j)); int R = max(sa, max(i+sb,j+sc)); ans = min(ans, R-L); } } cout << ans << endl; }
#include "qItemA.hpp" #include "qItemB.hpp" #include "qItemC.hpp" #include "qItemD.hpp" int main(int, char**) { QItemA itemA; QItemB itemB; QItemC itemC; QItemD itemD; // Fails to link if the symbol is not present. return 0; }
#include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <queue> #define rep(i,n) for(int i=0; i<n; i++) #define clr(a) memset(a, 0, sizeof(a)) using namespace std; const int maxn = 100000, inf=~0U>>3; vector <int> E[maxn]; int n ; struct record { int a[2][2], b[2][2]; // a[i][j] : maximum from the first node 's i part to the last node 's j part // b[0][j] : from the left 's j part the max walk // b[1][j] : from the right 's j part the max walk void setEmpty() { rep(i,2) rep(j,2) { b[i][j]=0; a[i][j]= i==j ? 0 : -inf; } } void reverse() { swap(a[0][1], a[1][0]) ; swap(b[0][0], b[1][0]) ; swap(b[0][1], b[1][1]) ; } record () { setEmpty(); } record (char * c) { rep(i,2) rep(j,2) a[i][j] = c[i]!='#' && c[j]!='#' ? 1+(i!=j) : -inf; rep(i,2) rep(j,2) b[i][j] = c[j]!='#' ? (c[1-j]!='#') + 1 : 0; } record operator + (const record & o) const { record ret; rep(i,2) rep(j,2) ret.a[i][j]= max(-inf, max(a[i][0] + o.a[0][j], a[i][1] + o.a[1][j])); rep(j,2) { int s = b[0][j]; rep(k,2) s = max(s, a[j][k] + o.b[0][k]); ret.b[0][j] = s; s = o.b[1][j]; rep(k,2) s = max(s, b[1][k] + o.a[k][j]); ret.b[1][j] = s; } return ret; // FORGOT THIS !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } } rec[maxn]; namespace linkCutTree { struct node { record cur, sum; node * c[2], * p ; node() {} void setChild (node *n, bool d) { n->p = this, c[d] = n; } bool d() {return this == p->c[1]; } } T[maxn]; void pushUp(node * t) { t->sum = t->cur; if ( t->c[0]!=NULL) t->sum = t->c[0]->sum + t->sum; if ( t->c[1]!=NULL) t->sum = t->sum + t->c[1]->sum; } void rotate(node *t) { node * p = t->p, *g= p->p; bool d= t->d(); p->c[d]=t->c[!d]; if(p->c[d]!=NULL) p->c[d]->p=p; t->c[!d]=p; p->p=t; t->p=g; if(g!=NULL) { if(g->c[0]==p) g->c[0]=t; else if(g->c[1]==p) g->c[1]=t; } pushUp(p); } void splay(node *t){ while (t->p && (t->p->c[t->d()]==t)){ if (t->p->p && t->p->p->c[t->p->d()]==t->p) { if(t->p->d()==t->d()) rotate(t->p), rotate(t) ; else rotate(t), rotate(t); } else rotate(t); } pushUp(t); } node * access(node *t) { node *q; for(q=NULL; t!=NULL; t=t->p) { splay(t); t->c[1]=q; pushUp(t); q=t; } return q; } void change(int x) { splay(T+x); T[x].cur = rec[x]; pushUp(T+x); } int query(int x, int y) { node * a = T+x, * b = T+y; access(a); node * r = access(b); record ret = r -> cur ; if(r->c[1]!=NULL) ret = ret + r->c[1]->sum; if (a != r) { splay (a); a->sum.reverse(); ret = a->sum + ret; a->sum.reverse(); } return max(ret.b[0][1], ret.b[0][0]); } } ; using namespace linkCutTree; queue<int> Q; void bfs() { vector<int>::iterator it; for(int i = 1; i <= n; i++ ) { T[i].c[0] = T[i].c[1] = T[i].p = NULL; T[i].cur = rec[i]; pushUp(T+i); } for( Q.push(1); Q.size(); ) { int now = Q.front(); Q.pop(); for( it = E[now].begin(); it!=E[now].end(); it++) if ( *it != 1 && T[*it].p==NULL ) T[*it].p = T+now, Q.push(*it); } } int main(){ #ifndef ONLINE_JUDGE freopen("in", "r", stdin) ; #endif int m, x, y; scanf("%d %d", &n, &m); for(int i = 1; i <= n-1; i++) { scanf("%d %d", &x, &y); E[x].push_back (y); E[y].push_back (x); } for(int i = 1; i <= n; i++) { char cmd[10]; scanf("%s", cmd); rec[i]= record(cmd); } bfs(); while( m-- ) { char cmd[10]; scanf("%s", cmd); if(cmd[0]=='Q') { scanf("%d %d", &x, &y) ; printf("%d\n", query(x,y)); } else { scanf("%d", &x); scanf("%s", cmd); rec[x]=record(cmd); change(x); } } return 0; }
#include "Match.h" std::tuple<Eigen::Array2Xd, Eigen::Array2Xd> Cvl::Match::alignMatches( Eigen::Array2Xd const & allSrcPoints, Eigen::Array2Xd const & allDstPoints, std::vector<Match> const & matches) { Eigen::Matrix2Xd src(2, matches.size()); Eigen::Matrix2Xd dst(2, matches.size()); int i = 0; for (auto const& match : matches) { src.col(i) = allSrcPoints.col(match.mTemplateId); dst.col(i) = allDstPoints.col(match.mMeasuredId); ++i; } return std::make_tuple(src, dst); }
// internal #include "tiny_ecs.hpp" // All we need to store besides the containers is the id of every entity and callbacks to be able to remove entities across containers unsigned int Entity::id_count = 1;
/* * Copyright (c) 2015-2020 Morwenn * SPDX-License-Identifier: MIT */ #ifndef CPPSORT_SORTERS_SPREAD_SORTER_FLOAT_SPREAD_SORTER_H_ #define CPPSORT_SORTERS_SPREAD_SORTER_FLOAT_SPREAD_SORTER_H_ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <cstdint> #include <iterator> #include <limits> #include <type_traits> #include <utility> #include <cpp-sort/sorter_facade.h> #include <cpp-sort/sorter_traits.h> #include <cpp-sort/utility/functional.h> #include <cpp-sort/utility/static_const.h> #include "../../detail/iterator_traits.h" #include "../../detail/spreadsort/float_sort.h" namespace cppsort { //////////////////////////////////////////////////////////// // Sorter namespace detail { struct float_spread_sorter_impl { template< typename RandomAccessIterator, typename Projection = utility::identity > auto operator()(RandomAccessIterator first, RandomAccessIterator last, Projection projection={}) const -> std::enable_if_t< std::numeric_limits<projected_t<RandomAccessIterator, Projection>>::is_iec559 && ( sizeof(projected_t<RandomAccessIterator, Projection>) == sizeof(std::uint32_t) || sizeof(projected_t<RandomAccessIterator, Projection>) == sizeof(std::uint64_t) ) && is_projection_iterator_v<Projection, RandomAccessIterator> > { static_assert( std::is_base_of< std::random_access_iterator_tag, iterator_category_t<RandomAccessIterator> >::value, "float_spread_sorter requires at least random-access iterators" ); spreadsort::float_sort(std::move(first), std::move(last), std::move(projection)); } //////////////////////////////////////////////////////////// // Sorter traits using iterator_category = std::random_access_iterator_tag; using is_always_stable = std::false_type; }; } struct float_spread_sorter: sorter_facade<detail::float_spread_sorter_impl> {}; //////////////////////////////////////////////////////////// // Sort function namespace { constexpr auto&& float_spread_sort = utility::static_const<float_spread_sorter>::value; } } #endif // CPPSORT_SORTERS_SPREAD_SORTER_FLOAT_SPREAD_SORTER_H_
#include "opencv2/objdetect/objdetect.hpp" #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> using namespace cv; using namespace std; CascadeClassifier face_cascade; std::vector<Rect> faces; int main() { VideoCapture stream1(1); VideoCapture stream2(2); //0 is the id of video device.0 if you have only one camera. if (!stream1.isOpened()) { //check if video device has been initialised cout << "cannot open camera"; } //unconditional loop while (true) { Mat cameraFrame1; stream1.read(cameraFrame1); face_cascade.load( "/home/nihir/OpenCV/data/haarcascades/haarcascade_frontalface_xml.alt" ); Mat cameraFrame2; stream2.read(cameraFrame2); face_cascade.load( "/home/nihir/OpenCV/data/haarcascades/haarcascade_frontalface_xml.alt" ); // Detect faces face_cascade.detectMultiScale( cameraFrame1, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) ); // Draw circles on the detected faces for( int i = 0; i < faces.size(); i++ ) { Point center( faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5 ); ellipse( cameraFrame1, center, Size( faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 ); } // Detect faces std::vector<Rect> faces; face_cascade.detectMultiScale( cameraFrame2, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) ); // Draw circles on the detected faces for( int i = 0; i < faces.size(); i++ ) { Point center( faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5 ); ellipse( cameraFrame2, center, Size( faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 ); } imshow("cam1", cameraFrame1); imshow("cam2", cameraFrame2); if (waitKey(10) >= 0) break; } return 0; }
#ifndef SNPSTREAMREADER_H #define SNPSTREAMREADER_H // RsaToolbox #include "Definitions.h" // Qt #include <QString> #include <QStringList> #include <QFile> #include <QTextStream> namespace RsaToolbox { class SnpStreamReader { public: // SnpStreamReader(); SnpStreamReader(QString filePathName); void setFilename(QString filePathName); bool isOpen(); bool open(); bool isClosed(); void close(); NetworkParameter parameter(); double impedance_Ohms(); uint ports(); bool isNotData(); bool isData(); uint point(); bool seekForward(double frequency, SiPrefix prefix = SiPrefix::None); bool peek(double &frequency_Hz, ComplexMatrix2D &data); bool next(); double frequency_Hz(); ComplexMatrix2D data(); ComplexDouble data(uint outputPort, uint inputPort); private: bool _isValidFile; QFile _file; QTextStream _stream; NetworkParameter _parameter; double _impedance_Ohms; uint _ports; double _frequencyFactor; uint _point; double _frequency_Hz; ComplexMatrix2D _data; bool _next(double &oldFreq, ComplexMatrix2D &oldData, qint64 &oldPos); void _rewind(double const &oldFreq, ComplexMatrix2D const &oldData, qint64 const &oldPos); QStringList _readLine(); // ignore comment static QString _removeComment(QString line); void _parsePorts(); void _readOptions(); void _parseFrequencyPrefix(QString units); void _parseNetworkParameter(QString parameter); void _parseComplexFormat(QString format); void _parseImpedance(QString impedance); uint _valuesToRead; QStringList _readValues(); // 1 + 2*ports^2 void _parseFrequency(QString value); void _resizeData(); void _parseData(QStringList data); ComplexDouble (*_convert)(double a, double b); void _setFlip(); void (SnpStreamReader::*_flip2Port)(); void _flip(); void _noFlip(); }; } #endif // SNPSTREAMREADER_H
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<algorithm> #include<cmath> using namespace std; int f[80][80][80]; int main() { int n; while (scanf("%d",&n) != EOF) { memset(f,0,sizeof(f)); f[0][0][0] = 1; for (int i = 1;i <= n; i++) for (int j = 0;j <= i; j++) for (int k = 0;k <= j; k++) { f[i][j][k] = 0; if (i > j) f[i][j][k] += f[i-1][j][k]; if (j > k) f[i][j][k] += f[i][j-1][k]; f[i][j][k] += f[i][j][k-1]; } printf("%d\n\n",f[n][n][n]); } return 0; }