text
stringlengths
8
6.88M
#include "precompiled.h" #include "registeredfunctions.h" namespace registeredfunctions { typedef multiset<StartupFunction> startup_list_t; typedef multiset<ShutdownFunction> shutdown_list_t; typedef multiset<ScriptFunction> script_list_t; startup_list_t& getStartupList(); shutdown_list_t& getShutdownList(); script_list_t& getScriptList(); } using namespace registeredfunctions; startup_list_t& registeredfunctions::getStartupList() { static startup_list_t startup_list; return startup_list; } shutdown_list_t& registeredfunctions::getShutdownList() { static shutdown_list_t shutdown_list; return shutdown_list; } script_list_t& registeredfunctions::getScriptList() { static script_list_t script_list; return script_list; } void registeredfunctions::addStartupFunction(StartupFunction& startup) { getStartupList().insert(startup); } void registeredfunctions::addShutdownFunction(ShutdownFunction& shutdown) { getShutdownList().insert(shutdown); } void registeredfunctions::addScriptFunction(ScriptFunction& script) { getScriptList().insert(script); } void registeredfunctions::fireStartupFunctions() { for (startup_list_t::iterator it = getStartupList().begin(); it != getStartupList().end(); it++) { //INFO("executing startup function [%s]", it->name.c_str()); it->func(); } } void registeredfunctions::fireShutdownFunctions() { for (shutdown_list_t::iterator it = getShutdownList().begin(); it != getShutdownList().end(); it++) it->func(); } void registeredfunctions::fireScriptFunctions(script::ScriptEngine* se) { for (script_list_t::iterator it = getScriptList().begin(); it != getScriptList().end(); it++) { it->func(se); } }
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; // Author: Tatparya Shankar void getSumOfFibonacci() { long long int sum = 0; long long int fib1 = 0; long long int fib2 = 1; long long int fibNext = fib1 + fib2; long long int number; int scan; scan = scanf( "%lld", &number ); while( fibNext < number ) { // Check if even if( fibNext % 2 == 0 ) { sum += fibNext; } fibNext = fib1 + fib2; fib1 = fib2; fib2 = fibNext; } printf( "%lld\n", sum ); } int main() { int numTestCases; int scan; scan = scanf( "%d", &numTestCases ); while( numTestCases > 0 ) { getSumOfFibonacci(); numTestCases--; } return 0; }
// Created on: 1993-06-15 // Created by: Jean Yves LEBEY // Copyright (c) 1993-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 _TopOpeBRepBuild_PaveSet_HeaderFile #define _TopOpeBRepBuild_PaveSet_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <TopoDS_Edge.hxx> #include <TopOpeBRepBuild_ListIteratorOfListOfPave.hxx> #include <TopOpeBRepBuild_LoopSet.hxx> class TopoDS_Shape; class TopOpeBRepBuild_Pave; class TopOpeBRepBuild_Loop; //! class providing an exploration of a set of vertices to build edges. //! It is similar to LoopSet from TopOpeBRepBuild where Loop is Pave. class TopOpeBRepBuild_PaveSet : public TopOpeBRepBuild_LoopSet { public: DEFINE_STANDARD_ALLOC //! Create a Pave set on edge <E>. It contains <E> vertices. Standard_EXPORT TopOpeBRepBuild_PaveSet(const TopoDS_Shape& E); Standard_EXPORT void RemovePV (const Standard_Boolean B); //! Add <PV> in the Pave set. Standard_EXPORT void Append (const Handle(TopOpeBRepBuild_Pave)& PV); Standard_EXPORT virtual void InitLoop() Standard_OVERRIDE; Standard_EXPORT virtual Standard_Boolean MoreLoop() const Standard_OVERRIDE; Standard_EXPORT virtual void NextLoop() Standard_OVERRIDE; Standard_EXPORT virtual Handle(TopOpeBRepBuild_Loop) Loop() const Standard_OVERRIDE; Standard_EXPORT const TopoDS_Edge& Edge() const; Standard_EXPORT Standard_Boolean HasEqualParameters(); Standard_EXPORT Standard_Real EqualParameters() const; Standard_EXPORT Standard_Boolean ClosedVertices(); Standard_EXPORT static void SortPave (const TopOpeBRepBuild_ListOfPave& Lin, TopOpeBRepBuild_ListOfPave& Lout); protected: private: Standard_EXPORT void Prepare(); TopoDS_Edge myEdge; TopOpeBRepBuild_ListOfPave myVertices; TopOpeBRepBuild_ListIteratorOfListOfPave myVerticesIt; Standard_Boolean myHasEqualParameters; Standard_Real myEqualParameters; Standard_Boolean myClosed; Standard_Boolean myPrepareDone; Standard_Boolean myRemovePV; }; #endif // _TopOpeBRepBuild_PaveSet_HeaderFile
#ifndef TRAJECTORYVIEW_H #define TRAJECTORYVIEW_H #include <QGraphicsScene> #include <QGraphicsTextItem> #include <QGraphicsView> #include <QMouseEvent> #include <QScrollBar> #include <QTimeLine> #include <QTextStream> #include <QToolTip> #include <QWheelEvent> #include <QDebug> #include "Editor.h" #include "MainWindow.h" #include "TrajectoryGroup.h" #include "TrajectoryScene.h" #include "UserPreferences.h" class TrajectoryScene; class MainWindow; /** * @brief TrajectoryView display the loaded trajectory */ class TrajectoryView : public QGraphicsView { Q_OBJECT public: TrajectoryView(Editor *editor, QWidget* parent = NULL); void refresh(void); void toggle_normals(void); protected: virtual void wheelEvent(QWheelEvent *event); virtual void drawBackground(QPainter *painter, const QRectF& rect); virtual void enterEvent(QEvent *event); virtual void mouseReleaseEvent(QMouseEvent *event); signals: void signal_enable_add_modifier(bool on); private slots: void scaling_time(qreal); void anim_finished(); void update_nearest_point(QPointF mouse_position); void select(bool multiple = false); private: Editor *editor_; TrajectoryScene *trajectory_scene_; Point *nearest_point_; Point *selection_start_; Point *selection_end_; Selection *current_selection_; int scheduled_scalings_; ///<@brief Scheduled steps in zoom animation // Getters Editor *editor(void); TrajectoryScene *trajectory_scene(void); Point *nearest_point(void); Point *selection_start(void); Point *selection_end(void); Selection *current_selection(void); int scheduled_scalings(void); double scene_rotation_; // Setters void editor(Editor *editor); void trajectory_scene(TrajectoryScene *trajectory_scene); void nearest_point(Point *nearest_point); void selection_start(Point *selection_start); void selection_end(Point *selection_end); void current_selection(Selection *current_selection); void scheduled_scalings(int scheduled_scalings); void decrement_scheduled_scalings(unsigned int value); void increment_scheduled_scalings(unsigned int value); // Methods void refresh_normals(void); void refresh_default_points(void); void refresh_trajectories(void); void refresh_selected_trajectories(void); void refresh_points(void); void refresh_selected_points(void); void refresh_nearest_point(void); QString tooltip_text(Point *point); }; #endif // TRAJECTORYVIEW_H
#include <stdint.h> #include <stdlib.h> /** * @brief 进行转发时所需的 IP 头的更新: * 你需要先检查 IP 头校验和的正确性,如果不正确,直接返回 false ; * 如果正确,请更新 TTL 和 IP 头校验和,并返回 true 。 * 你可以从 checksum 题中复制代码到这里使用。 * @param packet 收到的 IP 包,既是输入也是输出,原地更改 * @param len 即 packet 的长度,单位为字节 * @return 校验和无误则返回 true ,有误则返回 false */ bool forward(uint8_t *packet, size_t len) { // TODO: return false; }
#include<bits/stdc++.h> using namespace std; int main(){ int n,a,b,c,ans,count; ans = 0; cin>>n; for (int i = 0; i < n; i++) { count = 0; cin>>a>>b>>c; if(a==1){ count += 1; } if(b==1){ count += 1; } if(c==1){ count += 1; } if(count>1){ ans += 1; } } cout<<ans; return 0; }
/* BEGIN LICENSE */ /***************************************************************************** * SKFind : the SK search engine * Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr> * $Id: filters.cpp,v 1.13.2.3 2005/02/21 14:22:46 krys Exp $ * * Authors: Mathieu Poumeyrol <poumeyrol @at@ idm .dot. fr> * Arnaud de Bossoreille de Ribou <debossoreille @at@ idm .dot. fr> * Marc Ariberti <ariberti @at@ idm .dot. fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Alternatively you can contact IDM <skcontact @at@ idm> for other license * contracts concerning parts of the code owned by IDM. * *****************************************************************************/ /* END LICENSE */ #include <skfind/skfind.h> #include <skfind/frontend/wordlist/wordlist.h> #include <skfind/frontend/wordlist/wildcardwordlist.h> #include "parse.h" #include "index.h" #include "tokens.h" #include "filters.h" // IndexNearDocFilter SK_REFCOUNT_IMPL_DEFAULT(IndexNearDocFilter) SKERR IndexNearDocFilter::Init(SKIndex *pIndex, PRUint32 iNearThreshold, SKIRecordSet *pRS1, SKIRecordSet *pRS2, PRBool bAssertOrder) { m_bAssertOrder = bAssertOrder; m_pIndex = pIndex; m_iNearThreshold = iNearThreshold; m_pRS1 = pRS1; m_pRS2 = pRS2; SKERR err; err = m_pRS1->GetCount(&m_iCount1); if(err != noErr) return err; err = m_pRS2->GetCount(&m_iCount2); if(err != noErr) return err; return Reset(); } SKERR IndexNearDocFilter::CheckRank(PRUint32 iRank, PRBool* bKeepIt) { SKERR err = m_pCursor->ComputeCursorForm(); if (err != noErr) return err; PRUint32 iDocId = m_pCursor->GetSharedCursorDataRead()[iRank]; skPtr<SKCursor> pOcc1; err = m_pIndex->BuildOccurrenceList(m_pRS1, &m_iNext1, m_iCount1, iDocId, pOcc1.already_AddRefed()); if(err != noErr) return err; skPtr<SKCursor> pOcc2; err = m_pIndex->BuildOccurrenceList(m_pRS2, &m_iNext2, m_iCount2, iDocId, pOcc2.already_AddRefed()); if(err != noErr) return err; return CheckOcc(pOcc1, pOcc2, bKeepIt); } SKERR IndexNearDocFilter::Reset() { m_iNext1 = m_iNext2 = 0; return noErr; } SKERR IndexNearDocFilter::CheckOcc(SKCursor *pOcc1, SKCursor *pOcc2, PRBool *bKeepIt) { PRUint32 i1, i2, iCount1, iCount2; const PRUint32 *pData1, *pData2; SKERR err; err = pOcc1->GetCount(&iCount1); if(err != noErr) return err; err = pOcc2->GetCount(&iCount2); if(err != noErr) return err; if(iCount2 == 0 || iCount1 == 0) { bKeepIt = 0; return noErr; } PR_ASSERT( (iCount2>0) && (iCount1>0) ); err = pOcc1->ComputeCursorForm(); if (err != noErr) return err; pData1 = pOcc1->GetSharedCursorDataRead(); err = pOcc2->ComputeCursorForm(); if (err != noErr) return err; pData2 = pOcc2->GetSharedCursorDataRead(); if((iCount1 && !pData1) || (iCount2 && !pData2)) return err_failure; *bKeepIt = PR_FALSE; i1 = i2 = 0; PRUint32 pos1 = pData1[i1]; PRUint32 pos2 = pData2[i2]; while( true ) { if (pos1<=pos2) { if ( (pos2-pos1) <= m_iNearThreshold ) { *bKeepIt = PR_TRUE; return noErr; } else { ++i1; if (i1==iCount1) return noErr; pos1=pData1[i1]; } } else { if (!m_bAssertOrder && (pos1-pos2) <= m_iNearThreshold) { *bKeepIt = PR_TRUE; return noErr; } else { ++i2; if (i2==iCount2) return noErr; pos2 = pData2[i2]; } } } } // IndexDocPhraseFilter SK_REFCOUNT_IMPL_DEFAULT(IndexDocPhraseFilter); IndexDocPhraseFilter::IndexDocPhraseFilter() { m_pTokens = NULL; } SKERR IndexDocPhraseFilter::Init(IndexTokens *pTokens) { m_pTokens = pTokens; return noErr; } SKERR IndexDocPhraseFilter::CheckRank(PRUint32 iRank, PRBool* bKeepIt) { *bKeepIt = PR_FALSE; if(!m_pTokens) return err_failure; skPtr<SKCursor> pMatches; SKERR err; err = m_pCursor->ComputeCursorForm(); if (err != noErr) return err; err = m_pTokens->ComputePhraseHiliteInfo( m_pCursor->GetSharedCursorDataRead()[iRank], pMatches.already_AddRefed()); if(err != noErr) return err; PRUint32 iCount; err = pMatches->GetCount(&iCount); if(err != noErr) return err; if(iCount > 0) *bKeepIt = PR_TRUE; return noErr; } // IndexNearOccFilter SK_REFCOUNT_IMPL_DEFAULT(IndexNearOccFilter); SKERR IndexNearOccFilter::Init(SKCursor *pExternalCursor, PRUint32 iNearThreshold, PRBool bForwardFiltering) { m_pExternalCursor = pExternalCursor; m_iNearThreshold = iNearThreshold; m_bForwardFiltering = bForwardFiltering; SKERR err; err = m_pExternalCursor->GetCount(&m_iCount); if(err != noErr) return err; return Reset(); } SKERR IndexNearOccFilter::CheckRank(PRUint32 iRank, PRBool* bKeepIt) { SKERR err; *bKeepIt = PR_FALSE; err = m_pCursor->ComputeCursorForm(); if (err != noErr) return err; PRUint32 iPos = m_pCursor->GetSharedCursorDataRead()[iRank]; err = m_pExternalCursor->ComputeCursorForm(); if (err != noErr) return err; const PRUint32 *pExternalData=m_pExternalCursor->GetSharedCursorDataRead(); if(m_bForwardFiltering) { while( (m_iNext < m_iCount) && (pExternalData[m_iNext] + m_iNearThreshold < iPos)) { m_iNext++; } if((m_iNext < m_iCount) && (pExternalData[m_iNext] < iPos)) { *bKeepIt = PR_TRUE; } } else { while((m_iNext < m_iCount) && (pExternalData[m_iNext] < iPos)) { m_iNext++; } if( (m_iNext < m_iCount) && (pExternalData[m_iNext] <= iPos + m_iNearThreshold)) { *bKeepIt = PR_TRUE; } } return noErr; } SKERR IndexNearOccFilter::Reset() { m_iNext = 0; return noErr; }
#ifndef DOCTOR_H #define DOCTOR_H #pragma once #include<iostream> #include"person.h" #include<iomanip> class doctor :public Person { private: std::string Expertise; public: static int count; doctor() {} doctor(std::string Name, std::string Family, std::string Phone, std::string Code, std::string Expertise) :Person(Name, Family, Phone, Code) { set_Expertise(Expertise); count++; } void set_Expertise(std::string Expertise); std::string get_Expertise()const { return Expertise; } void pritCount()const { std::cout << count; } void show()const; }; int doctor::count = 0; void doctor::set_Expertise(std::string Expertise) { this->Expertise = Expertise; } void doctor::show() const { std::cout << Name << std::setw(10) << " " << Family << std::setw(8) << Phone << std::setw(9) << Code << std::setw(9) << Expertise << std::endl; } #endif // !DOCTOR_H
#include <iostream> #include <iomanip> using namespace std; //method declarations long long int factorial(int N); int main(){ int numberInput; long long int factorialAns; //ask the user for a number cout << "Enter a number to use to compute a factorial... or enter a negative number to quit: " << endl; cin >> numberInput; //will continue asking until a negative number of given while(numberInput >= 0){ //zero is an exception so it'll print out one if(numberInput == 0){ cout << numberInput << "!" << " = " << 1; } else{ //if it's not zero AND it's positive then it will do the factorial factorialAns = factorial(numberInput); //after the total number for the factorial is found you print it out cout << numberInput << "!" << " = " << factorialAns << endl << endl; //reasks the user for a number cout << "Enter a number to use to compute a factorial... or enter a negative number to quit: " << endl; cin >> numberInput; } } cout << endl; //if the number input is negative it will print this out cout << "Quitting!" << endl; return 0; } int factorial(int N){ if(N<=1){ return 1; } else{ return N * factorial(N--); } }
// // getParameters.cpp // PlaneMap // // Created by Yimeng Zhang on 5/25/14. // Copyright (c) 2014 Yimeng Zhang. All rights reserved. // #include "getParameters.h" #include <cstdlib> #include <cstdio> #include <stdint.h> #include <fstream> #include <sstream> #include <glm/gtc/matrix_transform.hpp> void getParameters(ParameterStruct *parameterStruct, int argc, const char * argv[]){ assert(argc>=6); int temp; size_t count; // arg 0 is useless // arg 1 is width temp = atoi(argv[1]); assert(temp>=0); (*parameterStruct).width = temp; // arg 2 is height temp = atoi(argv[2]); assert(temp>=0); (*parameterStruct).height = temp; // arg 3 is vertex array matrix uint16_t numberOfSurface; // each surface is described by 6 floats. FILE *fp = NULL; fp = fopen(argv[3], "rb"); fread(&numberOfSurface, sizeof(uint16_t),1, fp); (*parameterStruct).vectorBufferArray.reserve(numberOfSurface*3*6); assert((*parameterStruct).vectorBufferArray.capacity() >=numberOfSurface*3*6); GLfloat tempVertexArray[18]; count = 0; for (int iSurface = 0; iSurface < numberOfSurface; iSurface++){ count+=fread(tempVertexArray,sizeof(GLfloat),18,fp); for (int iVertex = 0; iVertex < 18; iVertex++){ (*parameterStruct).vectorBufferArray.push_back(tempVertexArray[iVertex]); } } assert(count==numberOfSurface*3*6); fclose(fp); fp = NULL; // arg 4 is resource name array std::ifstream fileStream; fileStream.open(argv[4]); std::string textureName; while(std::getline(fileStream, textureName)){ (*parameterStruct).imageFileNameArray.push_back(textureName); } fileStream.close(); // arg 5 is matrix array // what about just hacking them now?... fileStream.open(argv[5]); std::string tempString; std::getline(fileStream,tempString); int cameraTotal = std::stoi(tempString); (*parameterStruct).MVPArray.reserve(cameraTotal); assert((*parameterStruct).MVPArray.capacity() >=cameraTotal); std::stringstream ss; for (int iCamera = 0; iCamera < cameraTotal; iCamera++) { // first, two numbers for perspective matrix. std::getline(fileStream,tempString); (*parameterStruct).MVPNameArray.push_back(tempString); std::getline(fileStream,tempString); float angle; float ratio; ss.clear(); ss.str(tempString); ss >> angle; ss >> ratio; glm::mat4 projMat = glm::perspective(angle,ratio,0.1f,100.0f); // second, lookat matrix. 9 numbers. std::getline(fileStream,tempString); float vectorC[9]; ss.clear(); ss.str(tempString); float tempIC; for (int iC = 0; iC < 9; iC++){ ss >> tempIC; vectorC[iC] = tempIC; } glm::mat4 viewMat = glm::lookAt( glm::vec3(vectorC[0],vectorC[1],vectorC[2]), glm::vec3(vectorC[3],vectorC[4],vectorC[5]), glm::vec3(vectorC[6],vectorC[7],vectorC[8])); // use identity matrix for model. (*parameterStruct).MVPArray.push_back(projMat*viewMat); } fileStream.close(); if (argc<7) { (*parameterStruct).outputSuffix = ".flt"; } else { (*parameterStruct).outputSuffix = argv[6]; } if (argc<8) { (*parameterStruct).outputPrefix = ""; } else { (*parameterStruct).outputPrefix = argv[7]; } if (argc < 9) { (*parameterStruct).outputFileNameListName = "output"; } else { (*parameterStruct).outputFileNameListName = argv[8]; } if (argc < 10) { (*parameterStruct).singleOutput = true; } else { temp = atoi(argv[9]); if (temp != 0) { (*parameterStruct).singleOutput = true; } else { (*parameterStruct).singleOutput = false; } } }
// Copyright (c) 1991-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 _gp_Mat_HeaderFile #define _gp_Mat_HeaderFile #include <gp.hxx> #include <Standard_OutOfRange.hxx> #include <Standard_OStream.hxx> #include <Standard_ConstructionError.hxx> class gp_XYZ; //! Describes a three column, three row matrix. //! This sort of object is used in various vectorial or matrix computations. class gp_Mat { public: DEFINE_STANDARD_ALLOC //! creates a matrix with null coefficients. gp_Mat() { myMat[0][0] = myMat[0][1] = myMat[0][2] = myMat[1][0] = myMat[1][1] = myMat[1][2] = myMat[2][0] = myMat[2][1] = myMat[2][2] = 0.0; } gp_Mat (const Standard_Real theA11, const Standard_Real theA12, const Standard_Real theA13, const Standard_Real theA21, const Standard_Real theA22, const Standard_Real theA23, const Standard_Real theA31, const Standard_Real theA32, const Standard_Real theA33); //! Creates a matrix. //! theCol1, theCol2, theCol3 are the 3 columns of the matrix. Standard_EXPORT gp_Mat (const gp_XYZ& theCol1, const gp_XYZ& theCol2, const gp_XYZ& theCol3); //! Assigns the three coordinates of theValue to the column of index //! theCol of this matrix. //! Raises OutOfRange if theCol < 1 or theCol > 3. Standard_EXPORT void SetCol (const Standard_Integer theCol, const gp_XYZ& theValue); //! Assigns the number triples theCol1, theCol2, theCol3 to the three //! columns of this matrix. Standard_EXPORT void SetCols (const gp_XYZ& theCol1, const gp_XYZ& theCol2, const gp_XYZ& theCol3); //! Modifies the matrix M so that applying it to any number //! triple (X, Y, Z) produces the same result as the cross //! product of theRef and the number triple (X, Y, Z): //! i.e.: M * {X,Y,Z}t = theRef.Cross({X, Y ,Z}) //! this matrix is anti symmetric. To apply this matrix to the //! triplet {XYZ} is the same as to do the cross product between the //! triplet theRef and the triplet {XYZ}. //! Note: this matrix is anti-symmetric. Standard_EXPORT void SetCross (const gp_XYZ& theRef); //! Modifies the main diagonal of the matrix. //! @code //! <me>.Value (1, 1) = theX1 //! <me>.Value (2, 2) = theX2 //! <me>.Value (3, 3) = theX3 //! @endcode //! The other coefficients of the matrix are not modified. void SetDiagonal (const Standard_Real theX1, const Standard_Real theX2, const Standard_Real theX3) { myMat[0][0] = theX1; myMat[1][1] = theX2; myMat[2][2] = theX3; } //! Modifies this matrix so that applying it to any number //! triple (X, Y, Z) produces the same result as the scalar //! product of theRef and the number triple (X, Y, Z): //! this * (X,Y,Z) = theRef.(X,Y,Z) //! Note: this matrix is symmetric. Standard_EXPORT void SetDot (const gp_XYZ& theRef); //! Modifies this matrix so that it represents the Identity matrix. void SetIdentity() { myMat[0][0] = myMat[1][1] = myMat[2][2] = 1.0; myMat[0][1] = myMat[0][2] = myMat[1][0] = myMat[1][2] = myMat[2][0] = myMat[2][1] = 0.0; } //! Modifies this matrix so that it represents a rotation. theAng is the angular value in //! radians and the XYZ axis gives the direction of the //! rotation. //! Raises ConstructionError if XYZ.Modulus() <= Resolution() Standard_EXPORT void SetRotation (const gp_XYZ& theAxis, const Standard_Real theAng); //! Assigns the three coordinates of Value to the row of index //! theRow of this matrix. Raises OutOfRange if theRow < 1 or theRow > 3. Standard_EXPORT void SetRow (const Standard_Integer theRow, const gp_XYZ& theValue); //! Assigns the number triples theRow1, theRow2, theRow3 to the three //! rows of this matrix. Standard_EXPORT void SetRows (const gp_XYZ& theRow1, const gp_XYZ& theRow2, const gp_XYZ& theRow3); //! Modifies the matrix so that it represents //! a scaling transformation, where theS is the scale factor. : //! @code //! | theS 0.0 0.0 | //! <me> = | 0.0 theS 0.0 | //! | 0.0 0.0 theS | //! @endcode void SetScale (const Standard_Real theS) { myMat[0][0] = myMat[1][1] = myMat[2][2] = theS; myMat[0][1] = myMat[0][2] = myMat[1][0] = myMat[1][2] = myMat[2][0] = myMat[2][1] = 0.0; } //! Assigns <theValue> to the coefficient of row theRow, column theCol of this matrix. //! Raises OutOfRange if theRow < 1 or theRow > 3 or theCol < 1 or theCol > 3 void SetValue (const Standard_Integer theRow, const Standard_Integer theCol, const Standard_Real theValue) { Standard_OutOfRange_Raise_if (theRow < 1 || theRow > 3 || theCol < 1 || theCol > 3, " "); myMat[theRow - 1][theCol - 1] = theValue; } //! Returns the column of theCol index. //! Raises OutOfRange if theCol < 1 or theCol > 3 Standard_EXPORT gp_XYZ Column (const Standard_Integer theCol) const; //! Computes the determinant of the matrix. Standard_Real Determinant() const { return myMat[0][0] * (myMat[1][1] * myMat[2][2] - myMat[2][1] * myMat[1][2]) - myMat[0][1] * (myMat[1][0] * myMat[2][2] - myMat[2][0] * myMat[1][2]) + myMat[0][2] * (myMat[1][0] * myMat[2][1] - myMat[2][0] * myMat[1][1]); } //! Returns the main diagonal of the matrix. Standard_EXPORT gp_XYZ Diagonal() const; //! returns the row of theRow index. //! Raises OutOfRange if theRow < 1 or theRow > 3 Standard_EXPORT gp_XYZ Row (const Standard_Integer theRow) const; //! Returns the coefficient of range (theRow, theCol) //! Raises OutOfRange if theRow < 1 or theRow > 3 or theCol < 1 or theCol > 3 const Standard_Real& Value (const Standard_Integer theRow, const Standard_Integer theCol) const { Standard_OutOfRange_Raise_if (theRow < 1 || theRow > 3 || theCol < 1 || theCol > 3, " "); return myMat[theRow - 1][theCol - 1]; } const Standard_Real& operator() (const Standard_Integer theRow, const Standard_Integer theCol) const { return Value (theRow, theCol); } //! Returns the coefficient of range (theRow, theCol) //! Raises OutOfRange if theRow < 1 or theRow > 3 or theCol < 1 or theCol > 3 Standard_Real& ChangeValue (const Standard_Integer theRow, const Standard_Integer theCol) { Standard_OutOfRange_Raise_if (theRow < 1 || theRow > 3 || theCol < 1 || theCol > 3, " "); return myMat[theRow - 1][theCol - 1]; } Standard_Real& operator() (const Standard_Integer theRow, const Standard_Integer theCol) { return ChangeValue (theRow, theCol); } //! The Gauss LU decomposition is used to invert the matrix //! (see Math package) so the matrix is considered as singular if //! the largest pivot found is lower or equal to Resolution from gp. Standard_Boolean IsSingular() const { // Pour etre sur que Gauss va fonctionner, il faut faire Gauss ... Standard_Real aVal = Determinant(); if (aVal < 0) { aVal = -aVal; } return aVal <= gp::Resolution(); } void Add (const gp_Mat& theOther); void operator += (const gp_Mat& theOther) { Add (theOther); } //! Computes the sum of this matrix and //! the matrix theOther for each coefficient of the matrix : //! <me>.Coef(i,j) + <theOther>.Coef(i,j) Standard_NODISCARD gp_Mat Added (const gp_Mat& theOther) const; Standard_NODISCARD gp_Mat operator + (const gp_Mat& theOther) const { return Added (theOther); } void Divide (const Standard_Real theScalar); void operator /= (const Standard_Real theScalar) { Divide (theScalar); } //! Divides all the coefficients of the matrix by Scalar Standard_NODISCARD gp_Mat Divided (const Standard_Real theScalar) const; Standard_NODISCARD gp_Mat operator / (const Standard_Real theScalar) const { return Divided (theScalar); } Standard_EXPORT void Invert(); //! Inverses the matrix and raises if the matrix is singular. //! - Invert assigns the result to this matrix, while //! - Inverted creates a new one. //! Warning //! The Gauss LU decomposition is used to invert the matrix. //! Consequently, the matrix is considered as singular if the //! largest pivot found is less than or equal to gp::Resolution(). //! Exceptions //! Standard_ConstructionError if this matrix is singular, //! and therefore cannot be inverted. Standard_NODISCARD Standard_EXPORT gp_Mat Inverted() const; //! Computes the product of two matrices <me> * <Other> Standard_NODISCARD gp_Mat Multiplied (const gp_Mat& theOther) const { gp_Mat aNewMat = *this; aNewMat.Multiply (theOther); return aNewMat; } Standard_NODISCARD gp_Mat operator * (const gp_Mat& theOther) const { return Multiplied (theOther); } //! Computes the product of two matrices <me> = <Other> * <me>. void Multiply (const gp_Mat& theOther); void operator *= (const gp_Mat& theOther) { Multiply (theOther); } void PreMultiply (const gp_Mat& theOther); Standard_NODISCARD gp_Mat Multiplied (const Standard_Real theScalar) const; Standard_NODISCARD gp_Mat operator * (const Standard_Real theScalar) const { return Multiplied (theScalar); } //! Multiplies all the coefficients of the matrix by Scalar void Multiply (const Standard_Real theScalar); void operator *= (const Standard_Real theScalar) { Multiply (theScalar); } Standard_EXPORT void Power (const Standard_Integer N); //! Computes <me> = <me> * <me> * .......* <me>, theN time. //! if theN = 0 <me> = Identity //! if theN < 0 <me> = <me>.Invert() *...........* <me>.Invert(). //! If theN < 0 an exception will be raised if the matrix is not //! inversible Standard_NODISCARD gp_Mat Powered (const Standard_Integer theN) const { gp_Mat aMatN = *this; aMatN.Power (theN); return aMatN; } void Subtract (const gp_Mat& theOther); void operator -= (const gp_Mat& theOther) { Subtract (theOther); } //! cOmputes for each coefficient of the matrix : //! <me>.Coef(i,j) - <theOther>.Coef(i,j) Standard_NODISCARD gp_Mat Subtracted (const gp_Mat& theOther) const; Standard_NODISCARD gp_Mat operator - (const gp_Mat& theOther) const { return Subtracted (theOther); } void Transpose(); //! Transposes the matrix. A(j, i) -> A (i, j) Standard_NODISCARD gp_Mat Transposed() const { gp_Mat aNewMat = *this; aNewMat.Transpose(); return aNewMat; } //! Dumps the content of me into the stream Standard_EXPORT void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const; friend class gp_XYZ; friend class gp_Trsf; friend class gp_GTrsf; private: Standard_Real myMat[3][3]; }; //======================================================================= //function : gp_Mat // purpose : //======================================================================= inline gp_Mat::gp_Mat (const Standard_Real theA11, const Standard_Real theA12, const Standard_Real theA13, const Standard_Real theA21, const Standard_Real theA22, const Standard_Real theA23, const Standard_Real theA31, const Standard_Real theA32, const Standard_Real theA33) { myMat[0][0] = theA11; myMat[0][1] = theA12; myMat[0][2] = theA13; myMat[1][0] = theA21; myMat[1][1] = theA22; myMat[1][2] = theA23; myMat[2][0] = theA31; myMat[2][1] = theA32; myMat[2][2] = theA33; } //======================================================================= //function : Add // purpose : //======================================================================= inline void gp_Mat::Add (const gp_Mat& theOther) { myMat[0][0] += theOther.myMat[0][0]; myMat[0][1] += theOther.myMat[0][1]; myMat[0][2] += theOther.myMat[0][2]; myMat[1][0] += theOther.myMat[1][0]; myMat[1][1] += theOther.myMat[1][1]; myMat[1][2] += theOther.myMat[1][2]; myMat[2][0] += theOther.myMat[2][0]; myMat[2][1] += theOther.myMat[2][1]; myMat[2][2] += theOther.myMat[2][2]; } //======================================================================= //function : Added // purpose : //======================================================================= inline gp_Mat gp_Mat::Added (const gp_Mat& theOther) const { gp_Mat aNewMat; aNewMat.myMat[0][0] = myMat[0][0] + theOther.myMat[0][0]; aNewMat.myMat[0][1] = myMat[0][1] + theOther.myMat[0][1]; aNewMat.myMat[0][2] = myMat[0][2] + theOther.myMat[0][2]; aNewMat.myMat[1][0] = myMat[1][0] + theOther.myMat[1][0]; aNewMat.myMat[1][1] = myMat[1][1] + theOther.myMat[1][1]; aNewMat.myMat[1][2] = myMat[1][2] + theOther.myMat[1][2]; aNewMat.myMat[2][0] = myMat[2][0] + theOther.myMat[2][0]; aNewMat.myMat[2][1] = myMat[2][1] + theOther.myMat[2][1]; aNewMat.myMat[2][2] = myMat[2][2] + theOther.myMat[2][2]; return aNewMat; } //======================================================================= //function : Divide // purpose : //======================================================================= inline void gp_Mat::Divide (const Standard_Real theScalar) { Standard_Real aVal = theScalar; if (aVal < 0) { aVal = -aVal; } Standard_ConstructionError_Raise_if (aVal <= gp::Resolution(),"gp_Mat : Divide by 0"); const Standard_Real anUnSurScalar = 1.0 / theScalar; myMat[0][0] *= anUnSurScalar; myMat[0][1] *= anUnSurScalar; myMat[0][2] *= anUnSurScalar; myMat[1][0] *= anUnSurScalar; myMat[1][1] *= anUnSurScalar; myMat[1][2] *= anUnSurScalar; myMat[2][0] *= anUnSurScalar; myMat[2][1] *= anUnSurScalar; myMat[2][2] *= anUnSurScalar; } //======================================================================= //function : Divided // purpose : //======================================================================= inline gp_Mat gp_Mat::Divided (const Standard_Real theScalar) const { Standard_Real aVal = theScalar; if (aVal < 0) { aVal = -aVal; } Standard_ConstructionError_Raise_if (aVal <= gp::Resolution(),"gp_Mat : Divide by 0"); gp_Mat aNewMat; const Standard_Real anUnSurScalar = 1.0 / theScalar; aNewMat.myMat[0][0] = myMat[0][0] * anUnSurScalar; aNewMat.myMat[0][1] = myMat[0][1] * anUnSurScalar; aNewMat.myMat[0][2] = myMat[0][2] * anUnSurScalar; aNewMat.myMat[1][0] = myMat[1][0] * anUnSurScalar; aNewMat.myMat[1][1] = myMat[1][1] * anUnSurScalar; aNewMat.myMat[1][2] = myMat[1][2] * anUnSurScalar; aNewMat.myMat[2][0] = myMat[2][0] * anUnSurScalar; aNewMat.myMat[2][1] = myMat[2][1] * anUnSurScalar; aNewMat.myMat[2][2] = myMat[2][2] * anUnSurScalar; return aNewMat; } //======================================================================= //function : Multiply // purpose : //======================================================================= inline void gp_Mat::Multiply (const gp_Mat& theOther) { const Standard_Real aT00 = myMat[0][0] * theOther.myMat[0][0] + myMat[0][1] * theOther.myMat[1][0] + myMat[0][2] * theOther.myMat[2][0]; const Standard_Real aT01 = myMat[0][0] * theOther.myMat[0][1] + myMat[0][1] * theOther.myMat[1][1] + myMat[0][2] * theOther.myMat[2][1]; const Standard_Real aT02 = myMat[0][0] * theOther.myMat[0][2] + myMat[0][1] * theOther.myMat[1][2] + myMat[0][2] * theOther.myMat[2][2]; const Standard_Real aT10 = myMat[1][0] * theOther.myMat[0][0] + myMat[1][1] * theOther.myMat[1][0] + myMat[1][2] * theOther.myMat[2][0]; const Standard_Real aT11 = myMat[1][0] * theOther.myMat[0][1] + myMat[1][1] * theOther.myMat[1][1] + myMat[1][2] * theOther.myMat[2][1]; const Standard_Real aT12 = myMat[1][0] * theOther.myMat[0][2] + myMat[1][1] * theOther.myMat[1][2] + myMat[1][2] * theOther.myMat[2][2]; const Standard_Real aT20 = myMat[2][0] * theOther.myMat[0][0] + myMat[2][1] * theOther.myMat[1][0] + myMat[2][2] * theOther.myMat[2][0]; const Standard_Real aT21 = myMat[2][0] * theOther.myMat[0][1] + myMat[2][1] * theOther.myMat[1][1] + myMat[2][2] * theOther.myMat[2][1]; const Standard_Real aT22 = myMat[2][0] * theOther.myMat[0][2] + myMat[2][1] * theOther.myMat[1][2] + myMat[2][2] * theOther.myMat[2][2]; myMat[0][0] = aT00; myMat[0][1] = aT01; myMat[0][2] = aT02; myMat[1][0] = aT10; myMat[1][1] = aT11; myMat[1][2] = aT12; myMat[2][0] = aT20; myMat[2][1] = aT21; myMat[2][2] = aT22; } //======================================================================= //function : PreMultiply // purpose : //======================================================================= inline void gp_Mat::PreMultiply (const gp_Mat& theOther) { const Standard_Real aT00 = theOther.myMat[0][0] * myMat[0][0] + theOther.myMat[0][1] * myMat[1][0] + theOther.myMat[0][2] * myMat[2][0]; const Standard_Real aT01 = theOther.myMat[0][0] * myMat[0][1] + theOther.myMat[0][1] * myMat[1][1] + theOther.myMat[0][2] * myMat[2][1]; const Standard_Real aT02 = theOther.myMat[0][0] * myMat[0][2] + theOther.myMat[0][1] * myMat[1][2] + theOther.myMat[0][2] * myMat[2][2]; const Standard_Real aT10 = theOther.myMat[1][0] * myMat[0][0] + theOther.myMat[1][1] * myMat[1][0] + theOther.myMat[1][2] * myMat[2][0]; const Standard_Real aT11 = theOther.myMat[1][0] * myMat[0][1] + theOther.myMat[1][1] * myMat[1][1] + theOther.myMat[1][2] * myMat[2][1]; const Standard_Real aT12 = theOther.myMat[1][0] * myMat[0][2] + theOther.myMat[1][1] * myMat[1][2] + theOther.myMat[1][2] * myMat[2][2]; const Standard_Real aT20 = theOther.myMat[2][0] * myMat[0][0] + theOther.myMat[2][1] * myMat[1][0] + theOther.myMat[2][2] * myMat[2][0]; const Standard_Real aT21 = theOther.myMat[2][0] * myMat[0][1] + theOther.myMat[2][1] * myMat[1][1] + theOther.myMat[2][2] * myMat[2][1]; const Standard_Real aT22 = theOther.myMat[2][0] * myMat[0][2] + theOther.myMat[2][1] * myMat[1][2] + theOther.myMat[2][2] * myMat[2][2]; myMat[0][0] = aT00; myMat[0][1] = aT01; myMat[0][2] = aT02; myMat[1][0] = aT10; myMat[1][1] = aT11; myMat[1][2] = aT12; myMat[2][0] = aT20; myMat[2][1] = aT21; myMat[2][2] = aT22; } //======================================================================= //function : Multiplied // purpose : //======================================================================= inline gp_Mat gp_Mat::Multiplied (const Standard_Real theScalar) const { gp_Mat aNewMat; aNewMat.myMat[0][0] = theScalar * myMat[0][0]; aNewMat.myMat[0][1] = theScalar * myMat[0][1]; aNewMat.myMat[0][2] = theScalar * myMat[0][2]; aNewMat.myMat[1][0] = theScalar * myMat[1][0]; aNewMat.myMat[1][1] = theScalar * myMat[1][1]; aNewMat.myMat[1][2] = theScalar * myMat[1][2]; aNewMat.myMat[2][0] = theScalar * myMat[2][0]; aNewMat.myMat[2][1] = theScalar * myMat[2][1]; aNewMat.myMat[2][2] = theScalar * myMat[2][2]; return aNewMat; } //======================================================================= //function : Multiply // purpose : //======================================================================= inline void gp_Mat::Multiply (const Standard_Real theScalar) { myMat[0][0] *= theScalar; myMat[0][1] *= theScalar; myMat[0][2] *= theScalar; myMat[1][0] *= theScalar; myMat[1][1] *= theScalar; myMat[1][2] *= theScalar; myMat[2][0] *= theScalar; myMat[2][1] *= theScalar; myMat[2][2] *= theScalar; } //======================================================================= //function : Subtract // purpose : //======================================================================= inline void gp_Mat::Subtract (const gp_Mat& theOther) { myMat[0][0] -= theOther.myMat[0][0]; myMat[0][1] -= theOther.myMat[0][1]; myMat[0][2] -= theOther.myMat[0][2]; myMat[1][0] -= theOther.myMat[1][0]; myMat[1][1] -= theOther.myMat[1][1]; myMat[1][2] -= theOther.myMat[1][2]; myMat[2][0] -= theOther.myMat[2][0]; myMat[2][1] -= theOther.myMat[2][1]; myMat[2][2] -= theOther.myMat[2][2]; } //======================================================================= //function : Subtracted // purpose : //======================================================================= inline gp_Mat gp_Mat::Subtracted (const gp_Mat& theOther) const { gp_Mat aNewMat; aNewMat.myMat[0][0] = myMat[0][0] - theOther.myMat[0][0]; aNewMat.myMat[0][1] = myMat[0][1] - theOther.myMat[0][1]; aNewMat.myMat[0][2] = myMat[0][2] - theOther.myMat[0][2]; aNewMat.myMat[1][0] = myMat[1][0] - theOther.myMat[1][0]; aNewMat.myMat[1][1] = myMat[1][1] - theOther.myMat[1][1]; aNewMat.myMat[1][2] = myMat[1][2] - theOther.myMat[1][2]; aNewMat.myMat[2][0] = myMat[2][0] - theOther.myMat[2][0]; aNewMat.myMat[2][1] = myMat[2][1] - theOther.myMat[2][1]; aNewMat.myMat[2][2] = myMat[2][2] - theOther.myMat[2][2]; return aNewMat; } //======================================================================= //function : Transpose // purpose : //======================================================================= // On macOS 10.13.6 with XCode 9.4.1 the compiler has a bug leading to // generation of invalid code when method gp_Mat::Transpose() is called // for a matrix which is when applied to vector; it looks like vector // is transformed before the matrix is actually transposed; see #29978. // To avoid this, we disable compiler optimization here. #if defined(__APPLE__) && (__apple_build_version__ > 9020000) __attribute__((optnone)) #endif inline void gp_Mat::Transpose() { Standard_Real aTemp; aTemp = myMat[0][1]; myMat[0][1] = myMat[1][0]; myMat[1][0] = aTemp; aTemp = myMat[0][2]; myMat[0][2] = myMat[2][0]; myMat[2][0] = aTemp; aTemp = myMat[1][2]; myMat[1][2] = myMat[2][1]; myMat[2][1] = aTemp; } //======================================================================= //function : operator* // purpose : //======================================================================= inline gp_Mat operator* (const Standard_Real theScalar, const gp_Mat& theMat3D) { return theMat3D.Multiplied (theScalar); } #endif // _gp_Mat_HeaderFile
#include "Object.h" #include "ObjectStatus.h" #include "Calculater.h" #include "Define.h" #include <math.h> #include <QFile> #include <QIODevice> #include <QByteArray> #include <QJsonDocument> #include <QJsonObject> #include <QJsonArray> #include <QJsonValue> Object::Object(const char* fileName) : velocity(Vector()), omegaVector(Vector(0, 1, 0)), omega(0), gravityCenter(Vector()), fixed(false), name(fileName) { radius = 0; isDominated = false; status = new ObjectStatus(); QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) this->exitWithError("cannot open file.\n"); QByteArray bytes(""); while (!file.atEnd()) { bytes += file.readLine(); } QJsonDocument doc = QJsonDocument::fromJson(bytes); if (doc.isNull()) this->exitWithError("reading json failed...\n"); QJsonObject obj = doc.object(); this->parseVertexs(obj["vertexs"]); this->parseLines(obj["lines"]); this->parsePolygons(obj["polygons"]); this->parseMass(obj["mass"]); this->parseVelocity(obj["velocity"]); this->parseSubParams(obj); file.close(); reloadRadius(); } void Object::exitWithError(const char *str) { std::cerr << str << std::endl; exit(1); } void Object::parseVertexs(const QJsonValue &val) { if (!val.isArray()) this->exitWithError("incorrect vertex\n"); QJsonArray jsonVertexs = val.toArray(); this->vertexNum = jsonVertexs.size(); this->vertex = new Vector[this->vertexNum]; this->vertexEmbodyFlag = new bool[this->vertexNum]; int count = 0; for (auto i = jsonVertexs.begin(); i != jsonVertexs.end(); i++) { QJsonArray jsonVertex = (*i).toArray(); float x = jsonVertex.at(0).toDouble(); float y = jsonVertex.at(1).toDouble(); float z = jsonVertex.at(2).toDouble(); this->vertex[count].setVector(x, y, z); this->vertexEmbodyFlag[count] = true; this->gravityCenter += this->vertex[count]; count++; } this->gravityCenter /= count; } void Object::parseLines(const QJsonValue &val) { if (!val.isArray()) this->exitWithError("incorrect lines\n"); QJsonArray jsonLines = val.toArray(); this->lineNum = jsonLines.size(); this->lineLVertexIndex = new short[this->lineNum]; this->lineRVertexIndex = new short[this->lineNum]; for (int i = 0; i < this->lineNum; i++) { QJsonArray jsonLine = jsonLines.at(i).toArray(); this->lineLVertexIndex[i] = jsonLine.at(0).toInt() - 1; this->lineRVertexIndex[i] = jsonLine.at(1).toInt() - 1; } } void Object::parsePolygons(const QJsonValue &val) { if (!val.isArray()) this->exitWithError("incorrect polygons\n"); QJsonArray jsonPolygons = val.toArray(); this->polygonNum = jsonPolygons.size(); this->polygon1VertexIndex = new short[this->polygonNum]; this->polygon2VertexIndex = new short[this->polygonNum]; this->polygon3VertexIndex = new short[this->polygonNum]; this->polygonR = new short[this->polygonNum]; this->polygonG = new short[this->polygonNum]; this->polygonB = new short[this->polygonNum]; this->polygonEmbodyFlag = new bool[this->polygonNum]; this->polygonInsideFlag = new bool[this->polygonNum]; for (int i = 0; i < this->polygonNum; i++) { QJsonObject jsonPolygon = jsonPolygons.at(i).toObject(); QJsonArray jsonVertexIndex = jsonPolygon["vertex_index"].toArray(); this->polygon1VertexIndex[i] = jsonVertexIndex.at(0).toInt() - 1; this->polygon2VertexIndex[i] = jsonVertexIndex.at(1).toInt() - 1; this->polygon3VertexIndex[i] = jsonVertexIndex.at(2).toInt() - 1; QJsonArray jsonColor = jsonPolygon["color"].toArray(); this->polygonR[i] = jsonColor.at(0).toDouble() * 32767; this->polygonG[i] = jsonColor.at(1).toDouble() * 32767; this->polygonB[i] = jsonColor.at(2).toDouble() * 32767; this->polygonEmbodyFlag[i] = true; } for (int i = 0; i < this->polygonNum; i++) { short penetratedPlgnNum = 0; const Vector a1 = getPolygon1Vertex(i); const Vector a2 = getPolygon2Vertex(i); const Vector a3 = getPolygon3Vertex(i); Vector n = (a2 - a1) % (a3 - a1); for (short j = 0; j < this->polygonNum; j++) { if (i == j || polygonEmbodyFlag[j] == false) continue; const Vector b1 = getPolygon1Vertex(j); const Vector b2 = getPolygon2Vertex(j); const Vector b3 = getPolygon3Vertex(j); Vector solution; if (Calculater::solveCubicEquation( b2 - b1, b3 - b1, n * -1.0, (a1 + (a2 * 2) + (a3 * 3)) / 6.0 - b1, &solution )) { if (0 <= solution.getX() && 0 <= solution.getY() && solution.getX() + solution.getY() <= 1 && 0 < solution.getZ() ) { penetratedPlgnNum++; } } } this->polygonInsideFlag[i] = penetratedPlgnNum % 2; } } void Object::parseMass(const QJsonValue &val) { if (val.isNull()) { this->mass = 1; return; } if (!val.isDouble()) this->exitWithError("incorrect mass\n"); this->mass = val.toDouble(); this->inertiaMoment = this->mass * MOMENT_PER_MASS; } void Object::parseVelocity(const QJsonValue &val) { if (val.isNull()) { this->velocity.setVector(0, 0, 0); return; } if (!val.isArray()) this->exitWithError("incorrect velocity\n"); QJsonArray jsonVelocity = val.toArray(); float vx = jsonVelocity.at(0).toDouble(); float vy = jsonVelocity.at(1).toDouble(); float vz = jsonVelocity.at(2).toDouble(); this->velocity.setVector(vx, vy, vz); } void Object::parseSubParams(const QJsonObject &obj) { //do nothing } Object::Object(const Object& object) : name(object.name) { vertexNum = object.vertexNum; lineNum = object.lineNum; polygonNum = object.polygonNum; vertex = new Vector[vertexNum]; gravityCenter = object.gravityCenter; vertexEmbodyFlag = new bool[vertexNum]; for (short i = 0 ; i < vertexNum ; i++) { vertex[i] = object.vertex[i]; vertexEmbodyFlag[i] = object.vertexEmbodyFlag[i]; } lineLVertexIndex = new short[lineNum]; lineRVertexIndex = new short[lineNum]; for (short i = 0 ; i < lineNum ; i++) { lineLVertexIndex[i] = object.lineLVertexIndex[i]; lineRVertexIndex[i] = object.lineRVertexIndex[i]; } polygon1VertexIndex = new short[polygonNum]; polygon2VertexIndex = new short[polygonNum]; polygon3VertexIndex = new short[polygonNum]; polygonR = new short[polygonNum]; polygonG = new short[polygonNum]; polygonB = new short[polygonNum]; polygonEmbodyFlag = new bool[polygonNum]; polygonInsideFlag = new bool[polygonNum]; for (short i = 0 ; i < polygonNum ; i++) { polygon1VertexIndex[i] = object.polygon1VertexIndex[i]; polygon2VertexIndex[i] = object.polygon2VertexIndex[i]; polygon3VertexIndex[i] = object.polygon3VertexIndex[i]; polygonR[i] = object.polygonR[i]; polygonG[i] = object.polygonG[i]; polygonB[i] = object.polygonB[i]; polygonEmbodyFlag[i] = object.polygonEmbodyFlag[i]; polygonInsideFlag[i] = object.polygonInsideFlag[i]; } velocity = object.velocity; omegaVector = object.omegaVector; omega = object.omega; radius = object.radius; mass = object.mass; inertiaMoment = object.inertiaMoment; fixed = object.fixed; isDominated = object.isDominated; status = new ObjectStatus(*(object.status)); } Object::~Object(void) { delete[] vertex; delete[] lineLVertexIndex; delete[] lineRVertexIndex; delete[] polygon1VertexIndex; delete[] polygon2VertexIndex; delete[] polygon3VertexIndex; delete[] polygonR; delete[] polygonG; delete[] polygonB; delete[] vertexEmbodyFlag; delete[] polygonEmbodyFlag; delete[] polygonInsideFlag; delete status; } void Object::composeObject(Object* material) //atode nakusu. vertex nadoga dokuritusitamama unndouno eikyouwo tomoni ukeru sikumini sitai { Vector* tempVertex = new Vector[vertexNum + material->getVertexNum()]; short* tempLineLVertexIndex = new short[lineNum + material->getLineNum()]; short* tempLineRVertexIndex = new short[lineNum + material->getLineNum()]; short* tempPolygon1VertexIndex = new short[polygonNum + material->getPolygonNum()]; short* tempPolygon2VertexIndex = new short[polygonNum + material->getPolygonNum()]; short* tempPolygon3VertexIndex = new short[polygonNum + material->getPolygonNum()]; short* tempPolygonR = new short[polygonNum + material->getPolygonNum()]; short* tempPolygonG = new short[polygonNum + material->getPolygonNum()]; short* tempPolygonB = new short[polygonNum + material->getPolygonNum()]; bool* tempVertexEmbodyFlag = new bool[vertexNum + material->getVertexNum()]; bool* tempPolygonEmbodyFlag = new bool[polygonNum + material->getPolygonNum()]; bool* tempPolygonInsideFlag = new bool[polygonNum + material->getPolygonNum()]; for (short i = 0; i < vertexNum + material->getVertexNum(); i++) { if (i < vertexNum) { tempVertex[i] = vertex[i]; tempVertexEmbodyFlag[i] = vertexEmbodyFlag[i]; } else { tempVertex[i] = material->getVertex(i - vertexNum); tempVertexEmbodyFlag[i] = material->isVertexEmbody(i - vertexNum); } } delete[] vertex; delete[] vertexEmbodyFlag; vertex = tempVertex; vertexEmbodyFlag = tempVertexEmbodyFlag; for (short i = 0; i < lineNum + material->getLineNum(); i++) { if (i < lineNum) { tempLineLVertexIndex[i] = lineLVertexIndex[i]; tempLineRVertexIndex[i] = lineRVertexIndex[i]; } else { tempLineLVertexIndex[i] = vertexNum + material->lineLVertexIndex[i - lineNum]; tempLineRVertexIndex[i] = vertexNum + material->lineRVertexIndex[i - lineNum]; } } delete[] lineLVertexIndex; delete[] lineRVertexIndex; lineLVertexIndex = tempLineLVertexIndex; lineRVertexIndex = tempLineRVertexIndex; for (short i = 0; i < polygonNum + material->getPolygonNum(); i++) { if (i < polygonNum) { tempPolygon1VertexIndex[i] = polygon1VertexIndex[i]; tempPolygon2VertexIndex[i] = polygon2VertexIndex[i]; tempPolygon3VertexIndex[i] = polygon3VertexIndex[i]; tempPolygonR[i] = polygonR[i]; tempPolygonG[i] = polygonG[i]; tempPolygonB[i] = polygonB[i]; tempPolygonEmbodyFlag[i] = polygonEmbodyFlag[i]; tempPolygonInsideFlag[i] = polygonInsideFlag[i]; } else { tempPolygon1VertexIndex[i] = vertexNum + material->polygon1VertexIndex[i - polygonNum]; tempPolygon2VertexIndex[i] = vertexNum + material->polygon2VertexIndex[i - polygonNum]; tempPolygon3VertexIndex[i] = vertexNum + material->polygon3VertexIndex[i - polygonNum]; tempPolygonR[i] = material->polygonR[i - polygonNum]; tempPolygonG[i] = material->polygonG[i - polygonNum]; tempPolygonB[i] = material->polygonB[i - polygonNum]; tempPolygonEmbodyFlag[i] = material->isPolygonEmbody(i - polygonNum); tempPolygonInsideFlag[i] = material->isPolygonInside(i - polygonNum); } } vertexNum += material->getVertexNum(); lineNum += material->getLineNum(); polygonNum += material->getPolygonNum(); delete[] polygon1VertexIndex; delete[] polygon2VertexIndex; delete[] polygon3VertexIndex; delete[] polygonR; delete[] polygonG; delete[] polygonB; delete[] polygonEmbodyFlag; delete[] polygonInsideFlag; polygon1VertexIndex = tempPolygon1VertexIndex; polygon2VertexIndex = tempPolygon2VertexIndex; polygon3VertexIndex = tempPolygon3VertexIndex; polygonR = tempPolygonR; polygonG = tempPolygonG; polygonB = tempPolygonB; polygonEmbodyFlag = tempPolygonEmbodyFlag; polygonInsideFlag = tempPolygonInsideFlag; // gravity center is not change?? // radius change?? } Object* Object::decomposeObject(int vertexId, int polygonId, int lineId, const char* name) { Object* obj = new Object(name); obj->velocity.setVector(0, 0, 0); Vector* tempVertex = new Vector[vertexId]; short* tempLineLVertexIndex = new short[lineId]; short* tempLineRVertexIndex = new short[lineId]; short* tempPolygon1VertexIndex = new short[polygonId]; short* tempPolygon2VertexIndex = new short[polygonId]; short* tempPolygon3VertexIndex = new short[polygonId]; short* tempPolygonR = new short[polygonId]; short* tempPolygonG = new short[polygonId]; short* tempPolygonB = new short[polygonId]; bool* tempVertexEmbodyFlag = new bool[vertexId]; bool* tempPolygonEmbodyFlag = new bool[polygonId]; bool* tempPolygonInsideFlag = new bool[polygonId]; Vector newGravityCenter; int embodyVertexNum = 0; for (int i = 0; i < vertexNum; i++) { if (i < vertexId) { tempVertex[i] = vertex[i]; tempVertexEmbodyFlag[i] = vertexEmbodyFlag[i]; } else { obj->vertex[i - vertexId] = vertex[i];//?? feiaj->fjeawo[i] obj->vertexEmbodyFlag[i - vertexId] = vertexEmbodyFlag[i]; if (vertexEmbodyFlag[i]) { newGravityCenter += vertex[i]; embodyVertexNum++; } } } obj->gravityCenter = newGravityCenter / embodyVertexNum; delete[] vertex; delete[] vertexEmbodyFlag; vertex = tempVertex; vertexEmbodyFlag = tempVertexEmbodyFlag; vertexNum = vertexId; for (int i = 0; i < lineNum; i++) { if (i < lineId) { tempLineLVertexIndex[i] = lineLVertexIndex[i]; tempLineRVertexIndex[i] = lineRVertexIndex[i]; } else { obj->lineLVertexIndex[i - lineId] = lineLVertexIndex[i] - vertexId; obj->lineRVertexIndex[i - lineId] = lineRVertexIndex[i] - vertexId; } } delete[] lineLVertexIndex; delete[] lineRVertexIndex; lineLVertexIndex = tempLineLVertexIndex; lineRVertexIndex = tempLineRVertexIndex; lineNum = lineId; for (short i = 0; i < polygonNum; i++) { if (i < polygonId) { tempPolygon1VertexIndex[i] = polygon1VertexIndex[i]; tempPolygon2VertexIndex[i] = polygon2VertexIndex[i]; tempPolygon3VertexIndex[i] = polygon3VertexIndex[i]; tempPolygonR[i] = polygonR[i]; tempPolygonG[i] = polygonG[i]; tempPolygonB[i] = polygonB[i]; tempPolygonEmbodyFlag[i] = polygonEmbodyFlag[i]; tempPolygonInsideFlag[i] = polygonInsideFlag[i]; } else { obj->polygon1VertexIndex[i - polygonId] = polygon1VertexIndex[i] - vertexId; obj->polygon2VertexIndex[i - polygonId] = polygon2VertexIndex[i] - vertexId; obj->polygon3VertexIndex[i - polygonId] = polygon3VertexIndex[i] - vertexId; obj->polygonR[i - polygonId] = polygonR[i]; obj->polygonG[i - polygonId] = polygonG[i]; obj->polygonB[i - polygonId] = polygonB[i]; obj->polygonEmbodyFlag[i - polygonId] = polygonEmbodyFlag[i]; obj->polygonInsideFlag[i - polygonId] = polygonInsideFlag[i]; } } delete[] polygon1VertexIndex; delete[] polygon2VertexIndex; delete[] polygon3VertexIndex; delete[] polygonR; delete[] polygonG; delete[] polygonB; delete[] polygonEmbodyFlag; delete[] polygonInsideFlag; polygon1VertexIndex = tempPolygon1VertexIndex; polygon2VertexIndex = tempPolygon2VertexIndex; polygon3VertexIndex = tempPolygon3VertexIndex; polygonR = tempPolygonR; polygonG = tempPolygonG; polygonB = tempPolygonB; polygonEmbodyFlag = tempPolygonEmbodyFlag; polygonInsideFlag = tempPolygonInsideFlag; polygonNum = polygonId; return obj; } void Object::reloadRadius(void) { for (short i = 0; i < vertexNum; i++) { if (vertexEmbodyFlag[i] == false) continue; if (radius < (vertex[i] - gravityCenter).getMagnitude()) radius = (vertex[i] - gravityCenter).getMagnitude(); } } short Object::getVertexNum(void) const { return vertexNum; } short Object::getPolygonNum(void) const { return polygonNum; } short Object::getLineNum(void) const { return lineNum; } const Vector& Object::getGravityCenter(void) const { return gravityCenter; } const Vector& Object::getVertex(short vertexIndex) const { return vertex[vertexIndex]; } const Vector& Object::getPolygon1Vertex(short polygonIndex) const { return vertex[polygon1VertexIndex[polygonIndex]]; } const Vector& Object::getPolygon2Vertex(short polygonIndex) const { return vertex[polygon2VertexIndex[polygonIndex]]; } const Vector& Object::getPolygon3Vertex(short polygonIndex) const { return vertex[polygon3VertexIndex[polygonIndex]]; } const Vector& Object::getLineLVertex(short lineIndex) const { return vertex[lineLVertexIndex[lineIndex]]; } const Vector& Object::getLineRVertex(short lineIndex) const { return vertex[lineRVertexIndex[lineIndex]]; } Vector Object::getVrtxBasedOnG(short vrtxIdx) { return vertex[vrtxIdx] - gravityCenter; } Vector Object::getPlgnBasedOnG(short plgnIdx) { // here is more exact one. however computer must calculate more and more. return ( vertex[polygon1VertexIndex[plgnIdx]] + vertex[polygon2VertexIndex[plgnIdx]] + vertex[polygon3VertexIndex[plgnIdx]] ) / 3.0 - gravityCenter; // approximately one // return vertex[polygon1VertexIndex[plgnIdx]] - gravityCenter; } Vector Object::getLineBasedOnG(short lineIdx) { // here is more exact one. however computer must calculate more and more. return ( vertex[lineLVertexIndex[lineIdx]] + vertex[lineRVertexIndex[lineIdx]] ) / 2.0 - gravityCenter; // approximately one // return vertex[lineLVertexIndex[lineIdx]] - gravityCenter; } Vector Object::getDeltaVertex(short idx) { Vector nextVertex = vertex[idx]; Calculater::rotateRad(&nextVertex, gravityCenter, omegaVector, omega); return velocity + (nextVertex - vertex[idx]); } Vector Object::getDeltaPolygon(short idx) { Vector R = getPlgnBasedOnG(idx); Vector nextR = R; Calculater::rotateRad(&nextR, Vector(0, 0, 0), omegaVector, omega); return velocity + (nextR - R); } Vector Object::getDeltaLine(short idx) { Vector R = getLineBasedOnG(idx); Vector nextR = R; Calculater::rotateRad(&nextR, Vector(0, 0, 0), omegaVector, omega); return velocity + (nextR - R); } Vector Object::getPlgnInside(short idx) { Vector inside = ( (vertex[polygon2VertexIndex[idx]] - vertex[polygon1VertexIndex[idx]]) % (vertex[polygon3VertexIndex[idx]] - vertex[polygon1VertexIndex[idx]]) ) * (isPolygonInside(idx) ? 1.0 : -1.0); return inside / inside.getMagnitude(); } Array< Pair<int> > Object::getCommonVertexIdxInPolygons(short plgnIdx1, short plgnIdx2) { Array< Pair<int> > pairList(3); for (short i = 0; i < 3; i++) { short vertexIdx1; switch (i) { case 0: vertexIdx1 = polygon1VertexIndex[plgnIdx1]; break; case 1: vertexIdx1 = polygon2VertexIndex[plgnIdx1]; break; case 2: vertexIdx1 = polygon3VertexIndex[plgnIdx1]; break; } for (short j = 0; j < 3; j++) { short vertexIdx2; switch (j) { case 0: vertexIdx2 = polygon1VertexIndex[plgnIdx2]; break; case 1: vertexIdx2 = polygon2VertexIndex[plgnIdx2]; break; case 2: vertexIdx2 = polygon3VertexIndex[plgnIdx2]; break; } if (vertexIdx1 == vertexIdx2) { pairList.add(Pair<int>(i + 1, j + 1)); break; } } } return pairList; } float Object::getRadius(void) const { return radius; } float Object::getMass(void) { return mass; } float Object::getInertiaMoment(void) { return inertiaMoment; } const Vector& Object::getVelocity(void) const { return velocity; } Vector Object::getOmega(void) const { return omegaVector * omega; } Vector Object::getOmegaBaseVector(void) { return omegaVector; } float Object::getOmegaMagnitude(void) { return omega; } short Object::getPolygonR(short num) const { return polygonR[num]; } short Object::getPolygonG(short num) const { return polygonG[num]; } short Object::getPolygonB(short num) const { return polygonB[num]; } char Object::whichClass(void) { return 'O'; } ObjectStatus* Object::getStatus(void) { return status; } const char* Object::getName(void) { return name; } bool Object::isActive(void) { return (velocity.getMagnitude() != 0); } bool Object::isFixed(void) { return fixed; } bool Object::isVertexEmbody(short vertexIndex) const { return vertexEmbodyFlag[vertexIndex]; } bool Object::isPolygonEmbody(short polygonIndex) const { return polygonEmbodyFlag[polygonIndex]; } bool Object::isPolygonInside(short index) const { return polygonInsideFlag[index]; } void Object::setVertex(short num, const Vector& vector) { vertex[num] = vector; } void Object::setVertex(short num, float x, float y, float z) { vertex[num].setVector(x, y, z); } void Object::setGravityCenter(const Vector& vector) { gravityCenter = vector; } void Object::setGravityCenter(float x, float y, float z) { gravityCenter.setVector(x, y, z); } void Object::setVelocity(const Vector& vector) { velocity = vector; } void Object::setVelocity(float x, float y, float z) { velocity.setVector(x, y, z); } void Object::setOmega(const Vector& vector) { omega = vector.getMagnitude(); if (omega != 0) omegaVector = vector / omega; } void Object::setOmega(float x, float y, float z) { Vector vector(x, y, z); setOmega(vector); } void Object::setInertiaMoment(float inertiaMoment) { this->inertiaMoment = inertiaMoment; } void Object::setDomination(bool originalIsDominated) { isDominated = originalIsDominated; } void Object::fix(void) { fixed = true; stop(); } void Object::release(void) { fixed = false; } void Object::update(void) { velocity *= 0.95; omega *= 0.95; this->run(); this->rotate(); } void Object::run(void) { for (short i = 0 ; i < vertexNum ; i++) { vertex[i] += velocity; } gravityCenter += velocity; } void Object::back(void) { for (short i = 0 ; i < vertexNum ; i++) { vertex[i] -= velocity; } gravityCenter -= velocity; } void Object::stop(void) { velocity.setVector(0, 0, 0); omega = 0; } void Object::moveRelative(const Vector& vector) { for (short i = 0 ; i < vertexNum ; i++) { vertex[i] += vector; } gravityCenter += vector; } void Object::moveRelative(float x, float y, float z) { Vector vector(x, y, z); this->moveRelative(vector); } void Object::moveAbsolute(const Vector& vector) { Vector temp = vector - gravityCenter; this->moveRelative(temp); } void Object::moveAbsolute(float x, float y, float z) { Vector vector(x, y, z); this->moveAbsolute(vector); } void Object::rotate(void) { for (short i = 0 ; i < vertexNum ; i++) { Calculater::rotateRad(&vertex[i], gravityCenter, omegaVector, omega); } } void Object::push(Vector vector) { if (fixed) return; velocity += (vector / mass); } void Object::accelerate(Vector vector) { velocity += vector; } //fix check is executed in object class void Object::applyTorque(Vector torque) { if (fixed) return; omegaVector *= omega; omegaVector += (torque / inertiaMoment); omega = omegaVector.getMagnitude(); if (omega != 0) omegaVector /= omega; } void Object::enblack(short num) { polygonR[num] = 0; polygonG[num] = 0; polygonB[num] = 0; } /* void Object::debug(void) { printf("%f : %f %f %f;\n", omega, omegaVector.getX(), omegaVector.getY(), omegaVector.getZ()); } */
#ifndef SET_H #define SET_H template<typename T> class Set { public: virtual void add(T) = 0; virtual bool contains(T&) = 0; }; #endif
#ifndef TEXTURE_LOADER_H #define TEXTURE_LOADER_H #include <GL\glew.h> #include <string> typedef unsigned int U32; typedef unsigned char U8; class TextureLoader { public: enum TextureType { NONE, PNG, JPG, }; TextureLoader(); TextureLoader(const char* fileName, const char* extension); ~TextureLoader(); bool Read(const char* fileName, const char* extension); U32 GetWidth()const; U32 GetHeight()const; U32 GetBytesPerPixel()const; void Bind(int slot = 0); void UnBind(); U32 GetHandle() { return m_texHandle; } void SetName(const std::string& name); std::string GetName(); const U8* GetBuffer()const; TextureType GetTextureType() { return m_textureType; } private: bool ReadPng(const char* fileName); bool ReadJpeg(const char* fileName); TextureType m_textureType; GLenum m_textureTarget; U8* m_pixels; U32 m_width; U32 m_height; U32 m_bytesPerPixel; U32 m_texHandle; std::string m_name; }; #endif
#pragma once #include"Product.h" class ConcreteProductA:public Product{ public: ConcreteProductA(); virtual ~ConcreteProductA(); virtual void Use(); };
#include "consumer.h" #include <string> #include "bnlogif.h" #include "algo/aes_algo.h" //begin cipher by liulijin 20170606 add #include "config.h" //end cipher by liulijin 20170606 add static int POS_TYPE = 4; static string PRIX_BSDR_PRODUCER = "/yl/broadcast/bsdr/producer"; static string TYPE_GET_DATA = "getdata"; static string TYPE_GET_TRAN = "gettraninfo"; static string TYPE_GET_TXID = "gettxid"; //Jerry : add 20180305 static string TYPE_GET_REG_DATA = "getregdata"; static string TYPE_GET_REG_DATA_SIZE = "getregdatasize"; static string TYPE_GET_REG_DATA_PRICE = "getregdataprice"; static string TYPE_GET_MARKET_FROM_MARKET ="getmarketinfofrommarket"; static string TYPE_GET_MARKET_FROM_USER = "getmarketinfofromuser"; static string TYPE_GET_MARKET_FROM_TEC_COMPANY = "getmarketinfofromteccomapany"; static string TYPE_GET_MARKET_FROM_TEC_COMPANY_AS_USER = "getmarketinfofromteccomapanyasuser"; static string TYPE_GET_REG_DATA_FROM_OTHER_USER = "getregdatafromotheruser"; static string TYPE_REQ_USER_PUBKEY_SYNC = "requestuserpubkeysync"; static string TYPE_GET_AUTH_TOKEN = "getauthtoken"; static string TYPE_GET_AUTH_RANDOM = "getauthrandom"; //Jerry add 20180319 static string TYPE_GET_MARKET_FROM_BN = "getmarketinfofrombn"; // Jerry add 20180319 static string TYPE_GET_CONSUME_BILL = "getconsumebill"; static string TYPE_GET_CONSUME_SUM = "getconsumesum"; static string TYPE_UPDATE_MARKET_BALANCE_FROM_BN_NODE = "updatemarketbalancefrombnnode";// Jerry add 20180404 static string TYPE_ADD_MARKET_TO_BN_NODE ="addmarkettobnnode"; static string TYPE_DISABLE_MARKET_FROM_BN_NODE ="disablemarketfrombnnode"; //New interface add by gd 2018.04.05, Used to notify BSDR to store the specified data on chain static string TYPE_NOTIFY_ON_CHAIN ="notifyonchain"; static string TYPE_UPDATE_REGISTER_DATA_PRICE = "registerdataprice"; static string TYPE_DISABLE_REGISTER_DATA ="banregdata"; static string TYPE_UPDATE_REGISTER_DATA="updateregdata"; static string TYPE_SET_REGISTER_DATA="setregdata"; Consumer::Consumer() : m_pData(NULL) { m_pface = std::unique_ptr<Face>(new Face); } Consumer::~Consumer() { if (m_pData != NULL) { free(m_pData); m_pData = NULL; } } void Consumer::setProNum(int pronum) { m_pronum = pronum; } void Consumer::RegisterDataSet(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_SET_REGISTER_DATA + "/" + param; expressInterestName(strName); } void Consumer::RegisterDataDisable(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_DISABLE_REGISTER_DATA + "/" + param; expressInterestName(strName); } void Consumer::RegisterDataUpdate(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_UPDATE_REGISTER_DATA + "/" + param; expressInterestName(strName); } void Consumer::RegisterDataPriceUpdate(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_UPDATE_REGISTER_DATA_PRICE + "/" + param; expressInterestName(strName); } void Consumer::UpdateMarketBalanceFromBnNode(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_UPDATE_MARKET_BALANCE_FROM_BN_NODE + "/" + param; expressInterestName(strName); } void Consumer::AddMarketToBnNode(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_ADD_MARKET_TO_BN_NODE + "/" + param; expressInterestName(strName); } void Consumer::DisableMarketFromBnNode(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_DISABLE_MARKET_FROM_BN_NODE + "/" + param; expressInterestName(strName); } //Jerry: add 20180305 void Consumer::GetRegData(const string& strMarket,const char * param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_GET_REG_DATA + "/" + param; expressInterestName(strName); } //Jerry: add 20180305 void Consumer::GetRegDataSize(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_GET_REG_DATA_SIZE + "/" + param; expressInterestName(strName); } void Consumer::GetRegDataPrice(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_GET_REG_DATA_PRICE + "/" + param; expressInterestName(strName); } void Consumer::GetMarketInfoFromMarket(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_GET_MARKET_FROM_MARKET + "/" + param; expressInterestName(strName); } void Consumer::GetMarketInfoFromUser(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_GET_MARKET_FROM_USER+ "/" + param; expressInterestName(strName); } void Consumer::GetMarketInfoFromTecCompany(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_GET_MARKET_FROM_TEC_COMPANY + "/" + param; expressInterestName(strName); } void Consumer::GetMarketInfoFromTecCompanyAsUser(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_GET_MARKET_FROM_TEC_COMPANY_AS_USER + "/" + param; expressInterestName(strName); } void Consumer::GetMarketInfoFromBn(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_GET_MARKET_FROM_BN + "/" + param; expressInterestName(strName); } void Consumer::GetRegDataFromOtherUser(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_GET_REG_DATA_FROM_OTHER_USER + "/" + param; expressInterestName(strName); } void Consumer::UserPubkeySync(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_REQ_USER_PUBKEY_SYNC + "/" + param; expressInterestName(strName); } void Consumer::GetAuthRandom(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_GET_AUTH_RANDOM + "/" + param; expressInterestName(strName); } void Consumer::GetAuthToken(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_GET_AUTH_TOKEN + "/" + param; expressInterestName(strName); } void Consumer::GetConsumeBill(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_GET_CONSUME_BILL + "/" + param; expressInterestName(strName); } void Consumer::GetConsumeBillSum(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_GET_CONSUME_SUM + "/" + param; expressInterestName(strName); } void Consumer::expressInterestName(const string& strName) { // printf("expressInterestName: strName is %s\n", strName.c_str()); Interest interest(Name(strName.c_str())); interest.setInterestLifetime(time::milliseconds(10000)); interest.setMustBeFresh(true); if(nullptr == m_pface) { m_pface = std::unique_ptr<Face>(new Face); } if (nullptr == m_pface) { BN_LOG_ERROR("get block data error[new face failed]."); m_errormsg = "new face failed"; return; } try { BN_LOG_DEBUG("express interest:%s", strName.c_str()); m_pface->expressInterest(interest, bind(&Consumer::onData, this, _1, _2), bind(&Consumer::onNack, this, _1, _2), bind(&Consumer::onTimeout, this, _1)); // processEvents will block until the requested data received or timeout occurs m_pface->processEvents(); } catch (std::runtime_error& e) { m_pface = nullptr; BN_LOG_ERROR("get block date catch error:%s", e.what()); m_errormsg = "ylfd error"; } catch (...) { m_pface = nullptr; BN_LOG_ERROR("get block date catch unknow error:"); m_errormsg = "unknow ylfd error"; } } //New interface add by gd 2018.04.05, Used to notify BSDR to store the specified data on chain void Consumer::NotifyOnChain(const string& strMarket, const char* param) { m_success = false; std::ostringstream s; s<<m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + strMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_NOTIFY_ON_CHAIN + "/" + param; expressInterestName(strName); } /* void Consumer::GetBlockData(const string& consumerMarket, const string& dataMarket, const string& blocklabel) { m_success = false; std::ostringstream s; s << m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + dataMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_GET_DATA + "/" + consumerMarket + "/" + dataMarket + blocklabel; if (nullptr == m_pface) { BN_LOG_ERROR("get block data error[new face failed]."); m_errormsg = "new face failed"; return; } try { BN_LOG_DEBUG("express interest:%s", strName.c_str()); m_pface->expressInterest(interest, bind(&Consumer::onData, this, _1, _2), bind(&Consumer::onNack, this, _1, _2), bind(&Consumer::onTimeout, this, _1)); // processEvents will block until the requested data received or timeout occurs m_pface->processEvents(); } catch (std::runtime_error& e) { m_pface = nullptr; BN_LOG_ERROR("get block date catch error:%s", e.what()); m_errormsg = "ylfd error"; } catch (...) { m_pface = nullptr; BN_LOG_ERROR("get block date catch unknow error:"); m_errormsg = "unknow ylfd error"; } } void Consumer::GetBlockData(const string& consumerMarket, const string& dataMarket, const string& blocklabel) { m_success = false; std::ostringstream s; s << m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + dataMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_GET_DATA + "/" + consumerMarket + "/" + dataMarket + blocklabel; expressInterestName(strName); // _LOG_ERROR("GetBlockData[name:" << strName << "]"); } void Consumer::GetTranInfo(const string& consumerMarket, const string& dataMarket, const string& blocklabel) { m_success = false; std::ostringstream s; s << m_pronum; string strName = PRIX_BSDR_PRODUCER + "/" + dataMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/" + TYPE_GET_TRAN + "/" + consumerMarket + "/" + dataMarket + blocklabel; // _LOG_TRACE("GetTranInfo[name:" << strName << "]"); Interest interest(Name(strName.c_str())); interest.setInterestLifetime(time::milliseconds(10000)); interest.setMustBeFresh(true); if(nullptr == m_pface) { m_pface = std::unique_ptr<Face>(new Face); } if (nullptr == m_pface) { BN_LOG_ERROR("et tran info error[new face failed]."); m_errormsg = "new face failed"; return; } try { BN_LOG_DEBUG("express interest:%s", strName.c_str()); m_pface->expressInterest(interest, bind(&Consumer::onTranData, this, _1, _2), bind(&Consumer::onNack, this, _1, _2), bind(&Consumer::onTimeout, this, _1)); m_pface->processEvents(); } catch (std::runtime_error& e) { BN_LOG_ERROR("get tran info catch error:%s", e.what()); m_errormsg = "ylfd error"; } catch (...) { BN_LOG_ERROR("get tran info catch unknow error"); m_errormsg = "unknow ylfd error"; } } void Consumer::GetTxID(const string& dataMarket, const string& blocklabel) { m_success = false; std::ostringstream s; s << m_pronum; string strName = "/yl/broadcast/egz/bsdr/producer/" + dataMarket + "/" + Config::Instance()->m_sMacAddr + "/" + s.str() + "/gettxid/" + dataMarket + blocklabel; // _LOG_ERROR("GetTxID[name:" << strName << "]"); Interest interest(Name(strName.c_str())); interest.setInterestLifetime(time::milliseconds(10000)); interest.setMustBeFresh(true); if(nullptr == m_pface) { m_pface = std::unique_ptr<Face>(new Face); } if (nullptr == m_pface) { BN_LOG_ERROR("get txid error[new face failed]."); m_errormsg = "new face failed"; return; } try { // _LOG_INFO("express interest:" << strName); m_pface->expressInterest(interest, bind(&Consumer::onTxIDData, this, _1, _2), bind(&Consumer::onNack, this, _1, _2), bind(&Consumer::onTimeout, this, _1)); m_pface->processEvents(); } catch (std::runtime_error& e) { BN_LOG_ERROR("get txid catch error:%s", e.what()); m_errormsg = "ylfd error"; } catch (...) { BN_LOG_ERROR("get txid catch unknow error."); m_errormsg = "unknow ylfd error"; } }*/ void Consumer::onData(const Interest& interest, const Data& data) { Name dataName(interest.getName()); Name::Component comType = dataName.get(POS_TYPE); std::string strType = comType.toUri(); Block bck = data.getContent(); size_t size = bck.value_size(); //begin decrypt the content by mali 20170606 add //128bits key. unsigned char key[KEY_BYTE_NUMBERS]; //Init vector. unsigned char iv[KEY_BYTE_NUMBERS]; memcpy(key, KEY, KEY_BYTE_NUMBERS); memcpy(iv, INITIAL_VECTOR, KEY_BYTE_NUMBERS); int decryptedtext_len, ciphertext_len; ciphertext_len = size; unsigned char *ciphertextbuf = (unsigned char *) bck.value(); // if (Config::Instance()->m_sCipherSwitch == 1) { // hexdump(stdout, "=======ciphertextbuf=======", ciphertextbuf, // ciphertext_len); // } unsigned char *decryptplaintextbuf = NULL; if (Config::Instance()->m_sCipherSwitch == 1) { decryptplaintextbuf = (unsigned char*) malloc( MAX_TEXT_SIZE * sizeof(char)); if(NULL==decryptplaintextbuf) { BN_LOG_ERROR("decryptplaintextbuf malloc failed"); m_errormsg = "failed to malloc memory space"; return; } try { decryptedtext_len = decrypt(ciphertextbuf, ciphertext_len, key, iv, decryptplaintextbuf); } catch (std::runtime_error& e) { BN_LOG_ERROR("producer catch nfd error:%s", e.what()); } catch(...) { BN_LOG_ERROR("producer process events catch unknow error."); } } // if (Config::Instance()->m_sCipherSwitch == 1) { // hexdump(stdout, "=======decryptplaintextbuf=======", // decryptplaintextbuf, decryptedtext_len); // } //end decrypt the content by mali 20170606 add if (m_pData != NULL) { free(m_pData); m_pData = NULL; } //begin decrypt the content by mali 20170606 modify if (Config::Instance()->m_sCipherSwitch == 1) { m_pData = (char *) malloc(decryptedtext_len * sizeof(char) + 1); if (NULL == m_pData) { m_errormsg = "failed to malloc memory space"; free(decryptplaintextbuf); return; } memset(m_pData, '\0', decryptedtext_len * sizeof(char) + 1); strncpy(m_pData, reinterpret_cast<const char*>(decryptplaintextbuf), decryptedtext_len); free(decryptplaintextbuf); } else { m_pData = (char *) malloc(size * sizeof(char) + 1); if (NULL == m_pData) { m_errormsg = "failed to malloc memory space"; return; } memset(m_pData, '\0', size * sizeof(char) + 1); strncpy(m_pData, reinterpret_cast<const char*>(bck.value()), size); } //end decrypt the content by mali 20170606 modify // _LOG_ERROR("m_pData:" << m_pData); m_success = true; // fprintf(stderr, "Consumer::onData[%s]\n", m_pData); } /*void Consumer::onTranData(const Interest& interest, const Data& data) { Name dataName(interest.getName()); Name::Component comType = dataName.get(POS_TYPE); std::string strType = comType.toUri(); Block bck = data.getContent(); size_t size = bck.value_size(); //begin decrypt the content by marty 20170620 add //128bits key. unsigned char key[KEY_BYTE_NUMBERS]; //Init vector. unsigned char iv[KEY_BYTE_NUMBERS]; memcpy(key, KEY, KEY_BYTE_NUMBERS); memcpy(iv, INITIAL_VECTOR, KEY_BYTE_NUMBERS); int decryptedtext_len, ciphertext_len; ciphertext_len = size; unsigned char *ciphertextbuf = (unsigned char *) bck.value(); // if (Config::Instance()->m_sCipherSwitch == 1) { // hexdump(stdout, "=======ciphertextbuf=======", ciphertextbuf, // ciphertext_len); // } unsigned char *decryptplaintextbuf = NULL; if (Config::Instance()->m_sCipherSwitch == 1) { decryptplaintextbuf = (unsigned char*) malloc(MAX_TEXT_SIZE * sizeof(char)); try { decryptedtext_len = decrypt(ciphertextbuf, ciphertext_len, key, iv, decryptplaintextbuf); } catch (std::runtime_error& e) { BN_LOG_ERROR("producer catch nfd error:%s", e.what()); } catch(...) { BN_LOG_ERROR("producer process events catch unknow error."); } } // if (Config::Instance()->m_sCipherSwitch == 1) { // hexdump(stdout, "=======decryptplaintextbuf=======", // decryptplaintextbuf, decryptedtext_len); // } //end decrypt the content by marty 20170620 add if (m_pData != NULL) { free(m_pData); m_pData = NULL; } //begin decrypt the content by marty 20170620 modify if (Config::Instance()->m_sCipherSwitch == 1) { m_pData = (char *) malloc(decryptedtext_len * sizeof(char) + 1); if (NULL == m_pData) { m_errormsg = "failed to malloc memory space"; free(decryptplaintextbuf); return; } memset(m_pData, '\0', decryptedtext_len * sizeof(char) + 1); strncpy(m_pData, reinterpret_cast<const char*>(decryptplaintextbuf), decryptedtext_len); free(decryptplaintextbuf); } else { m_pData = (char *) malloc(size * sizeof(char) + 1); if (NULL == m_pData) { m_errormsg = "failed to malloc memory space"; return; } memset(m_pData, '\0', size * sizeof(char) + 1); strncpy(m_pData, reinterpret_cast<const char*>(bck.value()), size); } //end decrypt the content by marty 20170620 modify // _LOG_ERROR("m_pData:" << m_pData); m_success = true; // fprintf(stderr, "Consumer::onTranData[%s]\n", m_pData); } */ void Consumer::onTxIDData(const Interest& interest, const Data& data) { Block bck = data.getContent(); size_t size = bck.value_size(); //begin decrypt the content by marty 20170620 add //128bits key. unsigned char key[KEY_BYTE_NUMBERS]; //Init vector. unsigned char iv[KEY_BYTE_NUMBERS]; memcpy(key, KEY, KEY_BYTE_NUMBERS); memcpy(iv, INITIAL_VECTOR, KEY_BYTE_NUMBERS); int decryptedtext_len, ciphertext_len; ciphertext_len = size; unsigned char *ciphertextbuf = (unsigned char *) bck.value(); // if (Config::Instance()->m_sCipherSwitch == 1) { // hexdump(stdout, "=======ciphertextbuf=======", ciphertextbuf, // ciphertext_len); // } unsigned char *decryptplaintextbuf = NULL; if (Config::Instance()->m_sCipherSwitch == 1) { decryptplaintextbuf = (unsigned char*) malloc(MAX_TEXT_SIZE * sizeof(char)); try { decryptedtext_len = decrypt(ciphertextbuf, ciphertext_len, key, iv, decryptplaintextbuf); } catch (std::runtime_error& e) { BN_LOG_ERROR("producer catch nfd error:%s", e.what()); } catch(...) { BN_LOG_ERROR("producer process events catch unknow error."); } } //end decrypt the content by marty 20170620 add if (m_pData != NULL) { free(m_pData); m_pData = NULL; } //begin decrypt the content by marty 20170620 modify if (Config::Instance()->m_sCipherSwitch == 1) { m_pData = (char *) malloc(decryptedtext_len * sizeof(char) + 1); if (NULL == m_pData) { m_errormsg = "failed to malloc memory space"; free(decryptplaintextbuf); return; } memset(m_pData, '\0', decryptedtext_len * sizeof(char) + 1); strncpy(m_pData, reinterpret_cast<const char*>(decryptplaintextbuf), decryptedtext_len); free(decryptplaintextbuf); } else { m_pData = (char *) malloc(size * sizeof(char) + 1); if (NULL == m_pData) { m_errormsg = "failed to malloc memory space"; return; } memset(m_pData, '\0', size * sizeof(char) + 1); strncpy(m_pData, reinterpret_cast<const char*>(bck.value()), size); } //end decrypt the content by marty 20170620 modify m_success = true; } void Consumer::onNack(const Interest& interest, const lp::Nack& nack) { m_errormsg = "Network Nack"; } void Consumer::onTimeout(const Interest& interest) { m_errormsg = "get data timeout"; }
/* * 思路:利用无序哈希表存储值到索引的映射 */ class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> ret; if(nums.empty()){ return ret; } unordered_map<int,int> M; for(int i=0; i<nums.size(); ++i){ M[nums[i]] = i; } for(int i=0; i<nums.size(); ++i){ int other = target - nums[i]; if(M.count(other) && M[other] != i){ ret.push_back(i); ret.push_back(M[other]); break; } } return ret; } };
#include "projectionlight.h" ProjectionLight::ProjectionLight(const Transform &t, const std::shared_ptr<QImage> &projectionMap, const Point3f &pLight,const Color3f &I, Float fov ):Light(t),projectionMap(projectionMap),pLight(pLight),I(I) { // Create _ProjectionLight_ MIP map Point2i resolution(400,400); // std::unique_ptr<RGBSpectrum[]> texels = ReadImage(texname, &resolution); // if (texels) // projectionMap.reset(new MIPMap<RGBSpectrum>(resolution, texels.get())); // Initialize _ProjectionLight_ projection matrix Float aspect = projectionMap ? (Float(resolution.x) / Float(resolution.y)) : 1; if (aspect > 1) screenBounds = Bounds2f(Point2f(-aspect, -1), Point2f(aspect, 1)); else screenBounds = Bounds2f(Point2f(-1, -1 / aspect), Point2f(1, 1 / aspect)); hither = 1e-3f; yon = 1e30f; lightProjection = Perspective(fov, hither, yon); // Compute cosine of cone surrounding projection directions Float opposite = std::tan(glm::radians(fov) / 2.f); Float tanDiag = opposite * std::sqrt(1 + 1 / (aspect * aspect)); cosTotalWidth = std::cos(std::atan(tanDiag)); } Color3f ProjectionLight::Sample_Li(const Intersection &ref, const Point2f &xi, Vector3f *wi, Float *pdf) const { *wi = glm::normalize(pLight - ref.point); *pdf = 1; return I * Projection(-*wi) / glm::distance2(pLight, ref.point); } Color3f ProjectionLight::Sample_Li(const Intersection &ref, const Point2f &xi, Vector3f *wi, Float *pdf, Intersection *lightsample) const { *wi = glm::normalize(pLight - ref.point); *pdf = 1; *lightsample = Intersection(pLight); return I * Projection(-*wi) / glm::distance2(pLight, ref.point); } Float ProjectionLight::Pdf_Li(const Intersection &ref, const Vector3f &wi) const { return 0.0f; } bool ProjectionLight::getPosition(Point3f *wi) const { *wi=pLight; return true; } Color3f ProjectionLight::Projection(const Vector3f &w) const { //Vector3f wl = WorldToLight(w); Vector3f wl = Vector3f(transform.invT()*glm::vec4(w,0)); // Discard directions behind projection light if (wl.z < hither) return Color3f(0.0f); // Project point onto projection plane and compute light //Point3f p = lightProjection(Point3f(wl.x, wl.y, wl.z)); Point3f p = Point3f(lightProjection*glm::vec4(wl,1)); if (!screenBounds.Inside(Point2f(p.x, p.y))) return Color3f(0.0f); if (!projectionMap) return Color3f(1.0f);; Point2f st = Point2f(screenBounds.Offset(Point2f(p.x, p.y))); //return Color3f(projectionMap->Lookup(st), SpectrumType::Illuminant); return GetImageColor(st,projectionMap.get()); } Matrix4x4 Perspective(Float fov, Float n, Float f) { //Perform projective divide for perspective projection 366 Matrix4x4 persp(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, f / (f - n), -f*n / (f - n), 0, 0, 1, 0); //Scale canonical perspective view to specified field of view 367 Float invTanAng = 1 / std::tan(glm::radians(fov) / 2); return Scale(invTanAng, invTanAng, 1) * persp; } Matrix4x4 Scale(Float x, Float y, Float z) { glm::mat4 result(0.0f); result[0][0]=x; result[1][1]=y; result[2][2]=z; result[0][0]=1.0; return result; }
#pragma once #include "ipc_medium.h" #include "message.h" #include <queue> #include <memory> namespace Petunia { class IPCInternalMedium; class IPCMediumDefault: public IPCMedium { public: IPCMediumDefault(std::string &channel, ConnectionRole connection_role = ConnectionRole::Auto); ~IPCMediumDefault(); bool ReceiveMessages(std::queue<std::shared_ptr<Message>> &inbox_queue) override; bool SendMessages(std::queue<std::shared_ptr<Message>> &outbox_queue) override; private: std::shared_ptr<IPCMedium> m_internal_medium; }; }
#include<iostream> #include<clocale> using namespace std; int** PereChislenie(int key); void Watch(int **M, int mM); void KonZap(); void menu(); int** InOne(int **A, int **B, int mA, int mB); // Объединение графиков int** Peresek(int **A, int **B, int mA, int mB); // Пересечение графиков int** Pa3HocTb(int **U, int **W, int mU, int mW); // Разность int** SimRas(int **A, int **B, int mA, int mB); // Симметричная разность A u B int** Inversion(int **M, int mM); // Инверсия int** Exposition(int **A, int **B, int mA, int mB); // Композиция графиков int main() { setlocale(LC_ALL, "rus"); cout << "Введите мощность графика А:\t"; int mA; cin >> mA; int **A = PereChislenie(mA); cout << "Введите мощность графика B:\t"; int mB; cin >> mB; int **B = PereChislenie(mB); KonZap(); while (true) { system("cls"); cout << "A = "; Watch(A, mA); cout << "B = "; Watch(B, mB); menu(); int Operaziya; cin >> Operaziya; system("cls"); switch (Operaziya) { case 1: // Пересечение графиков { cout << "Пересечение графиков :" << endl; int mD = mA + mB + 1; int **D = new int*[mD]; for (int i = 0; i <= mD; i++) D[i] = new int[3]; D = Peresek(A, B, mA, mB); mD = D[0][0]; Watch(D, mD); system("pause"); } break; case 2: // Объединение графиков { cout << "Объединение графиков :" << endl; int mC = mA + mB + 1; int **C = new int*[mC]; for (int i = 0; i <= mC; i++) C[i] = new int[3]; C = InOne(A, B, mA, mB); mC = C[0][0]; Watch(C, mC); system("pause"); } break; case 3: // Разность A и В { cout << "Разность A и В :" << endl; int mR = mA + 1; int **R = new int*[mR]; for (int i = 0; i <= mR; i++) R[i] = new int[3]; R = Pa3HocTb(A, B, mA, mB); mR = R[0][0]; Watch(R, mR); system("pause"); } break; case 4:// Симметричная разность A u B { cout << "Симметричная разность A u B :" << endl; int mS = mB + mA + 1; int **S = new int*[mS]; for (int i = 0; i <= mS; i++) S[i] = new int[3]; S = SimRas(B, A, mB, mA); mS = S[0][0]; Watch(S, mS); system("pause"); } break; case 5:// Инверсия А { cout << "Инверсия А :" << endl; int mI = mA; int **I = new int*[mI]; for (int i = 0; i <= mI; i++) I[i] = new int[3]; I = Inversion(A, mA); mI = I[0][0]; Watch(I, mI); system("pause"); } break; case 6:// Инверсия В { cout << "Инверсия B :" << endl; int mI = mB; int **I = new int*[mI]; for (int i = 0; i <= mI; i++) I[i] = new int[3]; I = Inversion(B, mB); mI = I[0][0]; Watch(I, mI); system("pause"); } break; case 7:// Композиция графиков A и B { cout << "Композиция графиков A и B :" << endl; int mK = mB*mA + 1; int **K = new int*[mK]; for (int i = 0; i <= mK; i++) K[i] = new int[3]; K = Exposition(A, B, mA, mB); mK = K[0][0]; Watch(K, mK); system("pause"); } break; case 0:// Выход return 0; } } } int** PereChislenie(int mM) { int **M; M = new int *[mM]; for (int i = 1; i <= mM; i++) M[i] = new int[3]; if (mM < 1) { cout << "Пустой график!" << endl; return M; } cout << "Введите пары графика:\n"; for (int i = 1; i <= mM; i++) { cout << "Пара №" << i << endl; for (int j = 1; j < 3; j++) { cin >> M[i][j]; } } cout << endl; return M; } void Watch(int **M, int mM) { cout << "{"; for (int i = 1; i <= mM; i++) { cout << "<"; for (int j = 1; j < 3; j++) { cout << M[i][j]; if (j == 1) cout << ", "; } cout << ">"; if (i < mM) cout << ", "; } cout << "}" << endl; } void KonZap() { cout << "Графики заполнены." << endl; system("pause"); system("cla"); } void menu() { cout << endl << "Выберите операцию:" << endl; cout << " 1. Пересечение графиков\n 2. Объединение графиков\n 3. Разность A и В\n 4. Симметричная разность A u B\n 5. Инверсия А\n 6. Инверсия В\n 7. Композиция графиков A и B\n 0. Выход\n"; cout << "-->"; } int** InOne(int **A, int **B, int mA, int mB) { int mC = mA + mB + 1; int i, j; int **C = new int*[mC]; for (int i = 0; i <= mC; i++) C[i] = new int[3]; if (mB == 0 && mA == 0) { cout << "Пустой график! - "; return C; } if (mA == 0) { for (i = 1; i <= mB; i++) { for (j = 1; j < 3; j++) { C[i][j] = B[i][j]; } } C[0][0] = mB; return C; } if (mB == 0) { for (i = 1; i <= mA; i++) { for (j = 1; j < 3; j++) { C[i][j] = A[i][j]; } } C[0][0] = mA; return C; } for (i = 1; i <= mA; i++) { for (j = 1; j < 3; j++) { C[i][j] = A[i][j]; } } for (int b = 1; b <= mB; b++) { for (int a = 1; a <= mA; a++) { if (B[b][1] == A[a][1] && B[b][2] == A[a][2]) break; if (B[b][1] != A[a][1] || B[b][2] != A[a][2]) { if (a == (mA)) { C[i][1] = B[b][1]; C[i][2] = B[b][2]; i++; } else continue; } } } C[0][0] = i - 1; return C; } int** Peresek(int **A, int **B, int mA, int mB) { int mD = mA + mB + 1; int **D = new int*[mD]; for (int i = 0; i <= mD; i++) D[i] = new int[3]; int i = 0; if (mA == 0 || mB == 0) { cout << "Пустой график! - "; return D; } for (int b = 1; b <= mB; b++) { for (int a = 1; a <= mA; a++) { if (B[b][1] == A[a][1] && B[b][2] == A[a][2]) { i++; D[i][1] = B[b][1]; D[i][2] = B[b][2]; } } } if (i == 0) cout << "Пустой график! - "; D[0][0] = i; return D; } int** Pa3HocTb(int **U, int **W, int mU, int mW) { int mR = mU + 1; int **R = new int*[mR]; for (int i = 0; i <= mR; i++) R[i] = new int[3]; int r = 0; if (mU == 0) { cout << "Пустой график! - "; return R; } if (mW == 0) { for (int i = 1; i <= mU; i++) { R[i][1] = U[i][1]; R[i][2] = U[i][2]; } R[0][0] = mU; return R; } for (int i = 1; i <= mU; i++) { for (int j = 1; j <= mW; j++) { if (U[i][1] == W[j][1] && U[i][2] == W[j][2]) break; if (j == (mW)) { r++; R[r][1] = U[i][1]; R[r][2] = U[i][2]; } } } if (r == 0) cout << "Пустой график! - "; R[0][0] = r; return R; } int** SimRas(int **A, int **B, int mA, int mB) { int mS = mA * mB + 2; int **S = new int*[mS]; for (int i = 0; i <= mS; i++) S[i] = new int[3]; int s = 0, o = 0; if (mA == 0 && mB == 0) { cout << "Пустой график!"; return S; } if (mA == 0) { for (int i = 1; i <= mB; i++) { S[i][1] = B[i][1]; S[i][2] = B[i][2]; } S[0][0] = mB; return S; } if (mB == 0) { for (int i = 1; i <= mA; i++) { S[i][1] = A[i][1]; S[i][2] = A[i][2]; } S[0][0] = mA; return S; } for (int i = 1; i <= mA; i++) { for (int j = 1; j <= mB; j++) { o = 0; if (A[i][1] == B[j][1] && A[i][2] == B[j][2]) continue; for (int l = 1; l <= s; l++) { if (S[l][1] == A[i][1] && S[l][2] == A[i][2]) { o = 1; break; } } for (int v = 1; v <= mB; v++) { if (A[i][1] == B[v][1] && A[i][2] == B[v][2]) { o = 1; break; } } if (o == 1) continue; s++; S[s][1] = A[i][1]; S[s][2] = A[i][2]; } } for (int i = 1; i <= mB; i++) { for (int j = 1; j <= mA; j++) { o = 0; if (B[i][1] == A[j][1] && B[i][2] == A[j][2]) continue; for (int l = 1; l <= s; l++) { if (S[l][1] == B[i][1] && S[l][2] == B[i][2]) { o = 1; break; } } for (int v = 1; v <= mA; v++) { if (B[i][1] == A[v][1] && B[i][2] == A[v][2]) { o = 1; break; } } if (o == 1) continue; s++; S[s][1] = B[i][1]; S[s][2] = B[i][2]; } } if (s == 0) cout << "Пустой график! - "; S[0][0] = s; return S; } int** Inversion(int **M, int mM) { int **I = new int*[mM]; int i = 0; for (int l = 0; l <= mM; l++) I[l] = new int[3]; if (mM == 0) { cout << "Пустой график! - "; return I; } for (i = 1; i <= mM; i++) { I[i][1] = M[i][2]; I[i][2] = M[i][1]; } I[0][0] = mM; return I; } int** Exposition(int **A, int **B, int mA, int mB) { int mO = mA * mB + 1; int **K = new int*[mO]; int k = 0; for (int p = 0; p <= mO; p++) K[p] = new int[3]; if (mA == 0 || mB == 0) { cout << "Пустой график! - "; return K; } for (int i = 1; i <= mA; i++) { for (int j = 1; j <= mB; j++) { int o = 0; if (A[i][2] != B[j][1]) continue; for (int l = 1; l <= k; l++) if (A[i][1] == K[l][1] && B[j][2] == K[l][2]) { o = 1; break; } if (o == 1) continue; k++; K[k][1] = A[i][1]; K[k][2] = B[j][2]; o = 0; } } if (k == 0) cout << "Пустой график! - "; K[0][0] = k; return K; }
#pragma once #include "utils.hpp" #include "utils/ptts.hpp" #include "proto/config_rank.pb.h" using namespace std; namespace pc = proto::config; namespace nora { namespace config { using rank_reward_ptts = ptts<pc::rank_reward>; rank_reward_ptts& rank_reward_ptts_instance(); void rank_reward_ptts_set_funcs(); using rank_logic_ptts = ptts<pc::rank_logic>; rank_logic_ptts& rank_logic_ptts_instance(); void rank_logic_ptts_set_funcs(); } }
#ifndef DATABASE_H #define DATABASE_H #include <QString> class DataBase { public: DataBase(); void initDataBase(); //初始化数据库 int dealLand(QString id,QString password); }; #endif // DATABASE_H
#include <iostream> #include <sstream> #include <vector> #include <queue> #include <stack> #include <list> #include <iomanip> #include <set> #include <complex> #include <cstring> #include <cstdio> using namespace std; #define endl '\n' typedef pair<int, int> pii; typedef long double ld; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; const int INF = 0x3f3f3f3f; const double pi = acos(-1.0); const double eps = 1e-9; const int maxn = 10010; int n; int a[maxn]; struct Edge { int to; int next; } edge[maxn * 2]; int head[maxn], tot; //图 int sz[maxn]; //sz[v]为以v为根的子树的size int dep[maxn];//v的深度 int top[maxn];//v所在的重链的顶端节点 int son[maxn];//v的重儿子 int fa[maxn];//v的父节点 int w[maxn];//v和父节点的连边在线段树的位置 int val[maxn];//剖分后的边的权值 int pos; int e[maxn][4]; void init () { tot = 0; memset(head, -1, sizeof(head)); pos = 0; memset(son, 0, sizeof(son)); memset(top, 0, sizeof(top)); } void addedge (int u, int v) { edge[++tot].to = v; edge[tot].next = head[u]; head[u] = tot; }; void dfs1 (int u, int pre, int d) { dep[u] = d; fa[u] = pre; sz[u] = 1; for (int i = head[u]; i != -1; i = edge[i].next) { int v = edge[i].to; if (v != pre) { dfs1(v, u, d + 1); sz[u] += sz[v]; if (son[u] == 0 || sz[v] > sz[son[u]]) { son[u] = v; } } } } void dfs2 (int u, int tp) { top[u] = tp;//记录u所在重链的头结点 w[u] = ++pos; if (son[u] != 0) dfs2(son[u], top[u]); for (int i = head[u]; i != -1; i = edge[i].next) { if (edge[i].to != son[u] && edge[i].to != fa[u]) { dfs2(edge[i].to, edge[i].to); } } } template<class T> struct Segtree { #define ls (o<<1) #define rs (o<<1)|1 T data[maxn << 2]; T data1[maxn << 2]; T lazy[maxn << 2]; void pushup (int o) { data[o] = max(data[ls], data[rs]); data1[o] = min(data1[ls], data1[rs]); } void setlazy (int o) { lazy[o] ^= 1; swap(data[o],data1[o]); data[o]*=-1; data1[o]*=-1; } void pushdown (int o) { if (lazy[o]) { setlazy(ls); setlazy(rs); lazy[o] = 0; } } void build (int o, int l, int r) { lazy[o] = 0; if (l == r) { data[o] = val[l]; data1[o] = val[l]; return; } int mid = (l + r) >> 1; build(ls, l, mid); build(rs, mid + 1, r); pushup(o); } void update (int o, int l, int r, int x, int y) { if (l >= x && r <= y) { setlazy(o); return; } pushdown(o); int mid = (l + r) >> 1; if (x <= mid) update(ls, l, mid, x, y); if (y > mid) update(rs, mid + 1, r, x, y); pushup(o); } void updateone (int o, int l, int r, int index, T v) { if (l == r) { data[o] = v; data1[o] = v; return; } pushdown(o); int mid = (l + r) >> 1; if (index <= mid) updateone(ls, l, mid, index, v); else updateone(rs, mid + 1, r, index, v); pushup(o); } T query (int o, int l, int r, int x, int y) { if (l >= x && r <= y) { return data[o]; } pushdown(o); int mid = (l + r) >> 1; if (y <= mid) return query(ls, l, mid, x, y); if (x > mid) return query(rs, mid + 1, r, x, y); return max(query(ls, l, mid, x, y), query(rs, mid + 1, r, x, y)); } }; Segtree<int> tree; void solve (int va, int vb) { int f1 = top[va]; int f2 = top[vb]; // printf("f1=%d f2=%d\n",f1,f2); while (f1 != f2) { if (dep[f1] < dep[f2]) { swap(f1, f2); swap(va, vb); } tree.update(1, 1, pos, w[f1], w[va]); va = fa[f1]; f1 = top[va]; } if (va == vb) { return; } if (dep[va] > dep[vb]) swap(va, vb); // printf("va=%d vb=%d\n",va,vb); tree.update(1, 1, pos, w[son[va]], w[vb]); return; } int solve1 (int va, int vb) { // printf("query:\n"); int f1 = top[va]; int f2 = top[vb]; // printf("f1=%d f2=%d\n",f1,f2); int res = -INF; while (f1 != f2) { if (dep[f1] < dep[f2]) { swap(f1, f2); swap(va, vb); } res = max(res, tree.query(1, 1, pos, w[f1], w[va])); va = fa[f1]; f1 = top[va]; } if (va == vb) { return res; } if (dep[va] > dep[vb]) swap(va, vb); // printf("va=%d vb=%d\n",va,vb); res = max(res, tree.query(1, 1, pos, w[son[va]], w[vb])); return res; } int main () { int T; scanf("%d", &T); while (T--) { init(); scanf("%d", &n); for (int i = 1; i < n; i++) { scanf("%d%d%d", &e[i][0], &e[i][1], &e[i][2]); addedge(e[i][0], e[i][1]); addedge(e[i][1], e[i][0]); } // printf("222\n"); dfs1(1, 0, 0); dfs2(1, 0); for (int i = 1; i < n; i++) { if (dep[e[i][0]] < dep[e[i][1]]) swap(e[i][0], e[i][1]); val[w[e[i][0]]] = e[i][2]; } son[0]=1; tree.build(1, 1, pos); // printf("111\n"); char op[10]; int _1, _2; while (~scanf("%s", op)) { if (op[0] == 'D') { break; } if (op[0] == 'C') { scanf("%d%d", &_1, &_2); tree.updateone(1, 1, pos, w[e[_1][0]], _2); } else if (op[0] == 'N') { scanf("%d%d", &_1, &_2); solve(_1, _2); } else if (op[0] == 'Q') { scanf("%d%d", &_1, &_2); int ans = solve1(_1, _2); printf("%d\n", ans); } } } return 0; } /* 1 3 1 2 1 2 3 2 QUERY 1 2 CHANGE 1 3 NEGATE 1 3 QUERY 1 2 DONE */
#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include <queue> #include <vector> using namespace cv; using namespace std; Vec3b empty(182,189,186); Vec3b hover(198,206,202); Vec3b full(220,222,222); Vec3b black(0,0,0); vector<int> search(Mat_<Vec3b> &img, int rows, int cols, int x, int y, Vec3b c) { int lmaxx = x; int lmaxy = y; int lminx = x; int lminy = y; img(x,y) = black; queue<pair<int,int>> q; q.push(make_pair(x,y)); int count = 1; while(!q.empty()) { x=q.front().first; y=q.front().second; q.pop(); if(x>lmaxx) lmaxx=x; if(x<lminx) lminx=x; if(y>lmaxy) lmaxy=y; if(y<lminy) lminy=y; if(x>0 && img(x-1,y) == c) { q.push(make_pair(x-1,y)); count++; img(x-1,y) = black; } if(y>0 && img(x,y-1) == c) { q.push(make_pair(x,y-1)); count++; img(x,y-1) = black; } if(x<rows-1 && img(x+1,y) == c) { q.push(make_pair(x+1,y)); count++; img(x+1,y) = black; } if(y<cols-1 && img(x,y+1) == c) { q.push(make_pair(x,y+1)); count++; img(x,y+1) = black; } } return {count, lmaxx, lminx, lmaxy, lminy}; } int main( int argc, char** argv ) { if( argc != 2) { cerr <<" Usage: display_image ImageToLoadAndDisplay" << endl; return -1; } Mat image; image = imread(argv[1], CV_LOAD_IMAGE_COLOR); // Read the file if(! image.data ) // Check for invalid input { cerr << "Could not open or find the image" << std::endl ; return -1; } int maxx=0; int maxy=0; int minx=image.rows; int miny=image.cols; Mat_<Vec3b> _I = image; Vec3b v(7,10,254); // v[0] = 182; v[1]= 189; v[2]=186; for( int i = 0; i < image.rows; ++i) for( int j = 0; j < image.cols; ++j ) { Vec3b act = _I(i,j); if (act == empty || act==hover || act == full) { vector<int> v = search(_I, image.rows, image.cols, i, j, act); if(v[0]>100) { maxx = max(maxx, v[1]); minx = min(minx, v[2]); maxy = max(maxy, v[3]); miny = min(miny, v[4]); } } } if(maxx - minx < 30 || maxy - miny < 30) { return -1; } cout << maxy-miny + 1 << "x" << maxx - minx + 1 << "+" << miny << "+" << minx << endl; // image = _I; // // namedWindow( "Display window", WINDOW_AUTOSIZE );// Create a window for display. // imshow( "Display window", image ); // Show our image inside it. // // waitKey(0); // Wait for a keystroke in the window return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- * * 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. * * Author: Petter Nilsen */ #include "core/pch.h" #include "modules/pi/OpSystemInfo.h" #include "WindowsOpLowLevelFile.h" #include "WindowsOpDesktopResources.h" #include <share.h> #include <io.h> OP_STATUS OpLowLevelFile::Create(OpLowLevelFile** new_file, const uni_char* path, BOOL serialized) { OpString new_path; if (serialized) { // If this asserts goes off, core is not initialized. Core is needed for serialized paths. // Please correct the calling code, to either not use serialized path, or don't use OpLowLevelFile. OP_ASSERT(g_opera && g_op_system_info); RETURN_IF_ERROR(g_op_system_info->ExpandSystemVariablesInString(path, &new_path)); } else RETURN_IF_ERROR(new_path.Set(path)); OP_ASSERT(new_file != NULL); *new_file = OP_NEW(WindowsOpLowLevelFile, ()); if (*new_file == NULL) return OpStatus::ERR_NO_MEMORY; OP_STATUS res; res = ((WindowsOpLowLevelFile*)(*new_file))->Construct(new_path.CStr()); if (OpStatus::IsError(res)) { OP_DELETE(*new_file); *new_file = NULL; } return res; } WindowsOpLowLevelFile::WindowsOpLowLevelFile() : m_fp(NULL), m_file_open_mode(0), m_commit_mode(FALSE), m_text_mode(FALSE), m_filepos_dirty(FALSE), m_thread_handle(NULL), m_event_quit(NULL), m_event_quit_done(NULL), m_event_file(NULL), m_event_sync_done(NULL) { } WindowsOpLowLevelFile::~WindowsOpLowLevelFile() { #ifdef PI_ASYNC_FILE_OP // clean up async thread, if it exists ShutdownThread(); #endif // PI_ASYNC_FILE_OP Close(); } OP_STATUS WindowsOpLowLevelFile::Construct(const uni_char* path) { RETURN_IF_ERROR(m_path.Set(path)); // Remove trailing (back)slashes int len = m_path.Length(); if (len && (m_path[len-1] == '\\' || m_path[len-1] == '/')) { if (len == 1 || m_path[len-2] != ':') { m_path.Delete(len-1); } } return OpStatus::OK; } OP_STATUS WinErrToOpStatus(DWORD error) { switch (error) { case ERROR_SUCCESS: // == NO_ERROR return OpStatus::OK; case ERROR_DISK_FULL: return OpStatus::ERR_NO_DISK; case ERROR_NOT_ENOUGH_MEMORY: case ERROR_OUTOFMEMORY: return OpStatus::ERR_NO_MEMORY; case ERROR_SHARING_VIOLATION: case ERROR_LOCK_VIOLATION: case ERROR_WRONG_DISK: case ERROR_ACCESS_DENIED: case ERROR_BAD_NET_RESP: // When trying to check properties on a share case ERROR_DIR_NOT_EMPTY: return OpStatus::ERR_NO_ACCESS; case ERROR_FILE_NOT_FOUND: case ERROR_INVALID_NAME: case ERROR_PATH_NOT_FOUND: return OpStatus::ERR_FILE_NOT_FOUND; case ERROR_SHARING_BUFFER_EXCEEDED: // Too many files open for sharing return OpStatus::ERR; case ERROR_INVALID_HANDLE: return OpStatus::ERR_BAD_FILE_NUMBER; default: OP_ASSERT(FALSE); // Unknown error. Please check and add it above. return OpStatus::ERR; } } OP_STATUS WindowsOpLowLevelFile::GetWindowsLastError() const { DWORD error = GetLastError(); return WinErrToOpStatus(error); } OP_STATUS WindowsOpLowLevelFile::ErrNoToStatus(int err) { switch (err) { case ENOMEM: return OpStatus::ERR_NO_MEMORY; case ENOENT: return OpStatus::ERR_FILE_NOT_FOUND; case EACCES: return OpStatus::ERR_NO_ACCESS; case ENOSPC: return OpStatus::ERR_NO_DISK; case 0: return OpStatus::OK; } return OpStatus::ERR; } OP_STATUS WindowsOpLowLevelFile::GetFileInfo(OpFileInfo* info) { int f = info->flags; if (f & OpFileInfo::FULL_PATH) { info->full_path = GetFullPath(); } if (f & OpFileInfo::SERIALIZED_NAME) { info->serialized_name = GetSerializedName(); } if (f & OpFileInfo::WRITABLE) { info->writable = IsWritable(); } if (f & OpFileInfo::OPEN) { info->open = IsOpen(); } #ifdef PI_CAP_FILE_HIDDEN if (f & OpFileInfo::HIDDEN) { // this has to be modified to check if the file is really hidden or not info->hidden = IsHidden(); } #endif // PI_CAP_FILE_HIDDEN if (f & OpFileInfo::LENGTH) { RETURN_IF_ERROR(GetFileLength(&info->length)); } if (f & OpFileInfo::POS) { RETURN_IF_ERROR(GetFilePos(&info->pos)); } if (f & OpFileInfo::LAST_MODIFIED || f & OpFileInfo::MODE || f & OpFileInfo::CREATION_TIME) { struct _stat buf; if (Stat(&buf) == OpStatus::OK) { if (f & OpFileInfo::LAST_MODIFIED) { info->last_modified = buf.st_mtime; } if (f & OpFileInfo::MODE) { if (buf.st_mode & _S_IFDIR) { info->mode = OpFileInfo::DIRECTORY; } else { info->mode = OpFileInfo::FILE; } } if(f & OpFileInfo::CREATION_TIME) { info->creation_time = buf.st_ctime; } } else { OP_ASSERT(FALSE); // File not found return OpStatus::ERR; } } return OpStatus::OK; } /** Change file information. * * Only applicable to existing files that are closed. OpStatus::ERR is * returned otherwise. * * The 'flags' member of the given OpFileInfoChange object chooses which * pieces of information to change. Before making any changes to the file, * the implementation will check if all requested operations are supported, * and, if that is not the case, return OpStatus::ERR_NOT_SUPPORTED * immediately. * * @param changes What to change ('changes.flags'), and what to change it * to (the other member variables of 'changes'). * * @return OK if successful, ERR_NO_MEMORY on OOM, ERR_NO_ACCESS if write * access was denied, ERR_FILE_NOT_FOUND if the file does not exist, * ERR_NOT_SUPPORTED if (the file exists, but) at least one of the flags * set is not supported by the platform or file system, ERR for other * errors. */ #ifdef SUPPORT_OPFILEINFO_CHANGE void TimetToFileTime( time_t t, LPFILETIME pft ) { LONGLONG ll = Int32x32To64(t, 10000000) + 116444736000000000; pft->dwLowDateTime = (DWORD) ll; pft->dwHighDateTime = ll >>32; } OP_STATUS WindowsOpLowLevelFile::ChangeFileInfo(const OpFileInfoChange* changes) { BOOL exists = FALSE; if(m_fp || !m_path.HasContent() || !changes) { // not allowed on open files return OpStatus::ERR; } RETURN_IF_ERROR(Exists(&exists)); if(!exists) { return OpStatus::ERR_FILE_NOT_FOUND; } if(changes->flags & OpFileInfoChange::LAST_MODIFIED || changes->flags & OpFileInfoChange::CREATION_TIME) { HANDLE file = CreateFile(m_path.CStr(), GENERIC_READ | FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(file) { FILETIME ft; BOOL success = TRUE; if(changes->flags & OpFileInfoChange::LAST_MODIFIED) { TimetToFileTime(changes->last_modified, &ft); success = SetFileTime(file, NULL, NULL, &ft); } if(changes->flags & OpFileInfoChange::CREATION_TIME) { TimetToFileTime(changes->creation_time, &ft); success = SetFileTime(file, &ft, NULL, NULL); } CloseHandle(file); if(!success) { OpStatus::ERR; } } else { return OpStatus::ERR_NO_ACCESS; } } if(changes->flags & OpFileInfoChange::WRITABLE) { int retval = _wchmod(m_path.CStr(), changes->writable ? _S_IWRITE : 0); if(retval < 0) { return OpStatus::ERR; } } return OpStatus::OK; } #endif // SUPPORT_OPFILEINFO_CHANGE const uni_char* WindowsOpLowLevelFile::GetFullPath() const { return m_path.CStr(); } const uni_char* WindowsOpLowLevelFile::GetSerializedName() const { //julienp: This function is correct. We are using long names for serialized paths because of a mixup // that happened with the short versions. Do not touch this function without talking to me or // adamm first. if (m_serialized_path.IsEmpty()) { if(OpStatus::IsError(MakeSerializedName())) { m_serialized_path.Empty(); return m_path.CStr(); } } return m_serialized_path.CStr(); } OP_STATUS WindowsOpLowLevelFile::MakeSerializedName() const { // If this asserts goes off, core is not initialized. Core is needed for serialized paths. // Please correct the calling code, to either not use serialized path, or don't use OpLowLevelFile. OP_ASSERT(g_opera && g_folder_manager); RETURN_IF_ERROR(m_serialized_path.Set(m_path)); int path_len = m_path.Length(); BOOL serialized = FALSE; WindowsOpDesktopResources resources; const uni_char* folder = 0; OpString folder_opstring; RETURN_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_HOME_FOLDER, folder_opstring)); folder = folder_opstring.CStr(); RETURN_OOM_IF_NULL(folder); int folder_len = uni_strlen(folder); if (folder[folder_len - 1] == PATHSEPCHAR && path_len == folder_len - 1) { folder_len--; } if (m_serialized_path.CompareI(folder, folder_len) == 0) { m_serialized_path.Delete(0, folder_len); RETURN_IF_ERROR(m_serialized_path.Insert(0, "{SmallPreferences}")); serialized = TRUE; } RETURN_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_LOCAL_HOME_FOLDER, folder_opstring)); folder = folder_opstring.CStr(); RETURN_OOM_IF_NULL(folder); folder_len = uni_strlen(folder); if (folder[folder_len - 1] == PATHSEPCHAR && path_len == folder_len - 1) { folder_len--; } if (m_serialized_path.CompareI(folder, folder_len) == 0) { m_serialized_path.Delete(0, folder_len); RETURN_IF_ERROR(m_serialized_path.Insert(0, "{LargePreferences}")); serialized = TRUE; } RETURN_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_RESOURCES_FOLDER, folder_opstring)); folder = folder_opstring.CStr(); RETURN_OOM_IF_NULL(folder); folder_len = uni_strlen(folder); if (folder[folder_len - 1] == PATHSEPCHAR && path_len == folder_len - 1) { folder_len--; } if (m_serialized_path.CompareI(folder, folder_len) == 0) { m_serialized_path.Delete(0, folder_len); RETURN_IF_ERROR(m_serialized_path.Insert(0, "{Resources}")); serialized = TRUE; } OpString home_folder; if (OpStatus::IsSuccess(resources.GetHomeFolder(home_folder))) { if (home_folder[home_folder.Length() - 1] != '\\') RETURN_IF_ERROR(home_folder.Append(UNI_L("\\"))); folder = home_folder.CStr(); folder_len = uni_strlen(folder); if (folder[folder_len - 1] == PATHSEPCHAR && path_len == folder_len - 1) { folder_len--; } if (m_serialized_path.CompareI(folder, folder_len) == 0) { m_serialized_path.Delete(0, folder_len); RETURN_IF_ERROR(m_serialized_path.Insert(0, "{Home}")); serialized = TRUE; } } if (serialized) { uni_char* c = m_serialized_path.CStr() + m_serialized_path.FindFirstOf('}'); while (*(++c)) if(*c == '\\') *c ='/'; } return OpStatus::OK; } BOOL WindowsOpLowLevelFile::IsWritable() const { DWORD ret = GetFileAttributes(m_path.CStr()); if (ret == 0xFFFFFFFF) { return TRUE; } if (ret & FILE_ATTRIBUTE_READONLY) { return FALSE; } return TRUE; } BOOL WindowsOpLowLevelFile::IsHidden() const { DWORD ret = GetFileAttributes(m_path.CStr()); if (ret == 0xFFFFFFFF) { return FALSE; } if (ret & FILE_ATTRIBUTE_HIDDEN) { return TRUE; } return FALSE; } static OP_STATUS MakeDir(const uni_char* path) { DWORD err; // C: etc. should never fail if (((path[0] >= 'A' && path[0] <= 'Z') || (path[0] >= 'a' && path[0] <= 'z')) && path[1] == ':' && path[2] == 0) { return OpStatus::OK; } if (!CreateDirectory(path, NULL) && (err = GetLastError()) != ERROR_ALREADY_EXISTS) { return WinErrToOpStatus(err); } return OpStatus::OK; } static OP_STATUS MakePath(uni_char* path) { int len = path ? uni_strlen(path) : 0; for (int i=0; i < len; ++i) { if (path[i] == '\\' || path[i] == '/') { path[i] = 0; OP_STATUS res = MakeDir(path); path[i] = PATHSEPCHAR; if (OpStatus::IsMemoryError(res)) { return res; } } } return len ? MakeDir(path) : OpStatus::OK; } static OP_STATUS MakeParentFolderPath(uni_char* path) { if (!path) { return OpStatus::ERR_NULL_POINTER; } int len = uni_strlen(path); while (--len >= 0) { if (path[len] == '\\' || path[len] == '/') { path[len] = 0; break; } } OP_STATUS err = MakePath(path); if (len >= 0) { path[len] = PATHSEPCHAR; } return err; } /* Test for filename validity on Win32. The list of tests come from http://en.wikipedia.org/wiki/Filename The tests are: 1) total path length greater than MAX_PATH 2) anything using the octets 0-31 or characters " < > | : (these are reserved for Windows use in filenames. In addition each file system has its own additional characters that are invalid. See KB article Q100108 for more details). 3) anything ending in "." (no matter how many) (filename doc, doc. and doc... all refer to the same file) 4) any segment in which the basename (before first period) matches one of the DOS device names (the list comes from KB article Q100108 although some people reports that additional names such as "COM5" are also special devices). If the path fails ANY of these tests, the result must be to deny access. */ BOOL IsWin32FilenameValid(OpString& path) { static const uni_char * const invalid_characters = UNI_L("?\"<>*|:"); static const uni_char * const invalid_filenames[] = { UNI_L("CON"), UNI_L("AUX"), UNI_L("COM1"), UNI_L("COM2"), UNI_L("COM3"), UNI_L("COM4"), UNI_L("LPT1"), UNI_L("LPT2"), UNI_L("LPT3"), UNI_L("PRN"), UNI_L("NUL"), NULL }; const uni_char *segment_start; unsigned int segment_length; const uni_char *pos; // test 1 if(!path.HasContent() || path.Length() >= MAX_PATH) { /* Path too long (or missing) for Windows. Note that this test is not valid * if the path starts with //?/ or \\?\. */ OP_ASSERT(!"Invalid filename provided"); return FALSE; } pos = path.CStr(); /* Skip any leading non-path components. This can be either a drive letter such as C:, or a UNC path such as \\SERVER\SHARE\. */ if (pos[0] && pos[1] == ':') { /* Skip leading drive letter */ pos += 2; } else { if ((pos[0] == '\\' || pos[0] == '/') && (pos[1] == '\\' || pos[1] == '/')) { /* Is a UNC, so skip the server name and share name */ pos += 2; while (*pos && *pos != '/' && *pos != '\\') { pos++; } if (!*pos) { /* No share name */ OP_ASSERT(!"Invalid filename provided"); return FALSE; } /* Move to start of share name */ pos++; while (*pos && *pos != '/' && *pos != '\\') { pos++; } if (!*pos) { /* No path information */ OP_ASSERT(!"Invalid filename provided"); return FALSE; } } } while (*pos) { unsigned int idx; unsigned int base_length; while (*pos == '/' || *pos == '\\') { pos++; } if (*pos == '\0') { break; } segment_start = pos; /* start of segment */ while (*pos && *pos != '/' && *pos != '\\') { pos++; } segment_length = pos - segment_start; /* Now we have a segment of the path, starting at position "segment_start" and length "segment_length" */ /* Test 2 */ for(idx = 0; idx < segment_length; idx++) { if ((segment_start[idx] > 0 && segment_start[idx] < 32) || uni_strchr(invalid_characters, segment_start[idx])) { OP_ASSERT(!"Invalid filename provided"); return FALSE; } } /* Test 3 */ if (segment_start[segment_length - 1] == '.') { OP_ASSERT(!"Invalid filename provided"); return FALSE; } /* Test 4 */ for (base_length = 0; base_length < segment_length; base_length++) { if (segment_start[base_length] == '.') { break; } } /* base_length is the number of characters in the base path of the segment (which could be the same as the whole segment length, if it does not include any dot characters). */ if (base_length == 3 || base_length == 4) { for (idx = 0; invalid_filenames[idx]; idx++) { if (uni_strlen(invalid_filenames[idx]) == base_length && !uni_strnicmp(invalid_filenames[idx], segment_start, base_length)) { OP_ASSERT(!"Invalid filename provided"); return FALSE; } } } } return TRUE; } /* * At least one of the following flags must be set: OPFILE_READ, * OPFILE_WRITE, OPFILE_APPEND, OPFILE_UPDATE. */ OP_STATUS WindowsOpLowLevelFile::Open(int mode) { static const UINT MODE_STR_LEN = 6; m_file_open_mode = mode; uni_char mode_string[MODE_STR_LEN]; uni_char* p = mode_string; BOOL create_path = FALSE; if(!IsWin32FilenameValid(m_path)) { return OpStatus::ERR_BAD_FILE_NUMBER; } // check that we have all the flags we need if(!(mode & OPFILE_READ || mode & OPFILE_WRITE || mode & OPFILE_APPEND || mode & OPFILE_UPDATE)) { // missing Open flags, abort OP_ASSERT(!"disallowed combination"); return OpStatus::ERR; } if((mode & OPFILE_APPEND) && (mode & OPFILE_WRITE)) { OP_ASSERT(!"disallowed combination"); return OpStatus::ERR; } if((mode & OPFILE_UPDATE) && ((mode & OPFILE_UPDATE) != OPFILE_UPDATE)) { OP_ASSERT(!"disallowed combination"); return OpStatus::ERR; } if (mode & OPFILE_UPDATE) { *p++ = 'r'; *p++ = '+'; OP_ASSERT(!(mode & OPFILE_WRITE) && !(mode & OPFILE_APPEND)); } else if (mode & OPFILE_APPEND) { *p++ = 'a'; if (mode & OPFILE_READ) { *p++ = '+'; } OP_ASSERT(!(mode & OPFILE_WRITE) && !(mode & OPFILE_UPDATE)); } else if (mode & OPFILE_WRITE) { *p++ = 'w'; if (mode & OPFILE_READ) { *p++ = '+'; } } else { *p++ = 'r'; } // if any of the file create flags are set, then create the path if(mode & (OPFILE_WRITE | OPFILE_APPEND | OPFILE_UPDATE)) { create_path = TRUE; } if (mode & OPFILE_TEXT) { *p++ = 't'; } else { *p++ = 'b'; } if (mode & OPFILE_COMMIT) { *p++ = 'c'; //Microsoft-extension. "the contents of the file buffer are written directly to disk if either fflush or _flushall is called" } // none of our file handles should be inherited by other sub processes - DSK-281397 *p++ = 'N'; *p = 0; // If this assert goes off. Either you have added the possibility to have // more than 5 access constants, and therefore need to increase MODE_STR_LEN. // Or the pointer p is just not where it should be, and you need to find out why it is // not writing inside the mode_string array yourself. OP_ASSERT(&mode_string[MODE_STR_LEN] > p && p > &mode_string[0]); int shflag = _SH_DENYNO; if (mode & OPFILE_SHAREDENYWRITE && mode & OPFILE_SHAREDENYREAD) { shflag = _SH_DENYRW; } else if (mode & OPFILE_SHAREDENYWRITE) { shflag = _SH_DENYWR; } else if (mode & OPFILE_SHAREDENYREAD) { shflag = _SH_DENYRD; } if (m_path.CStr()) { // avoid dialogs if we try to access files on volumes not containing any mounted disk, // eg. memory card readers and CD-ROMs. See DSK-166772 UINT error_mode = SetErrorMode(SEM_FAILCRITICALERRORS); m_fp = _wfsopen(m_path.CStr(), mode_string, shflag); if (!m_fp && create_path) { // [pettern 25102005] // ignore this on purpose as open will fail further down anyway. MakePath() might // fail on valid paths (like "F:"). OpStatus::Ignore(MakeParentFolderPath(m_path.CStr())); m_fp = _wfsopen(m_path.CStr(), mode_string, shflag); } SetErrorMode(error_mode); } if (m_fp != NULL) { return OpStatus::OK; } else { const OP_STATUS status = ErrNoToStatus(errno); return OpStatus::IsError(status) ? status : OpStatus::ERR; } } OP_STATUS WindowsOpLowLevelFile::Close() { OP_STATUS result = OpStatus::OK; if (m_fp) { if (fclose(m_fp) != 0) result = OpStatus::ERR; m_fp = NULL; m_file_open_mode = 0; } return result; } OP_STATUS WindowsOpLowLevelFile::MakeDirectory() { if (m_path.Length() >= MAX_PATH) { return OpStatus::ERR; } if (PathIsDirectory(m_path.CStr())) { return OpStatus::OK; } if (PathFileExists(m_path.CStr())) { return OpStatus::ERR; } uni_char path_copy[MAX_PATH]; uni_strncpy(path_copy, m_path, MAX_PATH); uni_char* next_path; //If this is not a relative path, we should just skip the root if (PathIsRelative(path_copy)) { next_path = path_copy; } else { next_path = uni_strchr(path_copy, '\\') + 1; } while (next_path && (next_path = uni_strchr(next_path, '\\')) != NULL ) { *next_path = '\0'; if (!PathIsDirectory(path_copy) && !CreateDirectory(path_copy, NULL)) { if (GetLastError() == ERROR_ACCESS_DENIED) { return OpStatus::ERR_NO_ACCESS; } else { return OpStatus::ERR; } } *next_path = '\\'; next_path++; } if (!CreateDirectory(m_path.CStr(), NULL)) { if (GetLastError() == ERROR_ACCESS_DENIED) { return OpStatus::ERR_NO_ACCESS; } else { return OpStatus::ERR; } } return OpStatus::OK; } BOOL WindowsOpLowLevelFile::Eof() const { OP_ASSERT(m_fp); if(feof(m_fp)) { return TRUE; } return FALSE; } OP_STATUS WindowsOpLowLevelFile::Exists(BOOL* exists) const { *exists = FALSE; if (m_path.IsEmpty()) { return OpStatus::OK; } // avoid dialogs if we try to access files on volumes not containing any mounted disk, // eg. memory card readers and CD-ROMs. See DSK-166772 UINT error_mode = SetErrorMode(SEM_FAILCRITICALERRORS); DWORD ret = GetFileAttributes(m_path.CStr()); SetErrorMode(error_mode); if (ret != 0xFFFFFFFF) { *exists = TRUE; return OpStatus::OK; } switch (GetLastError()) { case ERROR_ACCESS_DENIED: return OpStatus::ERR_NO_ACCESS; default: return OpStatus::OK; } } OP_STATUS WindowsOpLowLevelFile::GetFilePos(OpFileLength* pos) const { if(pos == NULL || m_fp == NULL) { return OpStatus::ERR; } __int64 result = _ftelli64(m_fp); if(result == -1L) { return OpStatus::ERR; } *pos = (OpFileLength)result; return OpStatus::OK; } OP_STATUS WindowsOpLowLevelFile::SetFilePos(OpFileLength pos, OpSeekMode seek_mode) { if(m_fp == NULL) { return OpStatus::ERR_BAD_FILE_NUMBER; } int whence = SEEK_CUR; switch (seek_mode) { case SEEK_FROM_START: whence = SEEK_SET; break; case SEEK_FROM_END: whence = SEEK_END; break; case SEEK_FROM_CURRENT: whence = SEEK_CUR; break; } int result = _fseeki64(m_fp, pos, whence); if(result != 0) { return OpStatus::ERR; } return OpStatus::OK; } typedef BOOL (WINAPI *lpGetFileAttributesEx)(LPCTSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId, LPVOID lpFileInformation); lpGetFileAttributesEx fpGetFileAttributesEx; OP_STATUS WindowsOpLowLevelFile::GetFileLength(OpFileLength* len) const { OpFileLength result = 0; OP_STATUS status = OpStatus::OK; if (m_fp) { OpFileLength old = _ftelli64(m_fp); if (_fseeki64(m_fp, 0, SEEK_END) == 0) { result = _ftelli64(m_fp); if (_fseeki64(m_fp, old, SEEK_SET) != 0) { status = OpStatus::ERR; } } else { status = OpStatus::ERR; } } else { /* Opera won't start with GetFileAttributesEx() on W95, so we need to use GetProcAddress() */ HMODULE hModule; if(!fpGetFileAttributesEx) { hModule = GetModuleHandleA("KERNEL32"); fpGetFileAttributesEx = (lpGetFileAttributesEx) GetProcAddress(hModule, "GetFileAttributesExW"); OP_ASSERT(fpGetFileAttributesEx != NULL); } WIN32_FILE_ATTRIBUTE_DATA data; BOOL ok = (*fpGetFileAttributesEx)(m_path.CStr(), GetFileExInfoStandard, &data); if (ok) { result = (((OpFileLength) data.nFileSizeHigh) << 32) | ((OpFileLength) data.nFileSizeLow); } else { status = GetWindowsLastError(); } } *len = result; return status; } OP_STATUS WindowsOpLowLevelFile::Write(const void* data, OpFileLength len) { if (!m_fp) { return OpStatus::ERR_BAD_FILE_NUMBER; } OpFileLength bytes_written = fwrite(data, 1, (size_t) len, m_fp); // fwrite returns 0 when nothing written, not a negative number if (bytes_written < len) { if (ferror(m_fp)) { const OP_STATUS status = ErrNoToStatus(errno); return OpStatus::IsError(status) ? status : OpStatus::ERR; } } return OpStatus::OK; } #ifdef PI_CAP_FILE_PRINTF void WindowsOpLowLevelFile::Print(const char *fmt,va_list marker) { if(m_fp) ::vfprintf(m_fp, fmt, marker); } #endif OP_STATUS WindowsOpLowLevelFile::Read(void* data, OpFileLength len, OpFileLength* bytes_read) { OP_ASSERT(m_fp); if(!IsOpen()) { return OpStatus::ERR_BAD_FILE_NUMBER; } OpFileLength num_read = fread(data, 1, (size_t) len, m_fp); if (num_read < len) { if (ferror(m_fp)) { const OP_STATUS status = ErrNoToStatus(errno); return OpStatus::IsError(status) ? status : OpStatus::ERR; } } if (bytes_read) { *bytes_read = num_read; } return OpStatus::OK; } #define READLINE_BUF_SIZE 4096 OP_STATUS WindowsOpLowLevelFile::ReadLine(char** data) { if (!m_fp || !data) { return OpStatus::ERR_NULL_POINTER; } char buf[READLINE_BUF_SIZE]; OpString8 temp; // fgets() converts DOS-style CRLF newlines to LF only if file was opened with OPFILE_TEXT, so check both while (fgets(buf, READLINE_BUF_SIZE, m_fp) == buf) { RETURN_IF_ERROR(temp.Append(buf)); int str_len = temp.Length(); if (str_len) { // don't store newline character in the result string if (temp[str_len - 1] == '\n') { temp[str_len - 1] = '\0'; if (str_len > 1 && temp[str_len - 2] == '\r') { temp[str_len - 2] = '\0'; } } else { str_len = 0; } } if (str_len || feof(m_fp)) { *data = SetNewStr(temp.CStr()); return *data ? OpStatus::OK : OpStatus::ERR_NO_MEMORY; } } if (!feof(m_fp) || ferror(m_fp)) { *data = 0; return OpStatus::ERR; } // end of file needs empty string. *data = OP_NEWA(char, (1)); if (!*data) { return OpStatus::ERR_NO_MEMORY; } **data = 0; return OpStatus::OK; } OP_STATUS WindowsOpLowLevelFile::SafeClose() { if (!IsOpen()) { return OpStatus::OK; } RETURN_IF_ERROR(Flush()); if (!(m_file_open_mode & OPFILE_COMMIT)) { if (_commit(fileno(m_fp)) != 0) { return OpStatus::ERR; } } return Close(); } OP_STATUS WindowsOpLowLevelFile::SafeReplace(OpLowLevelFile* new_file) { // Check if new_file really exists BOOL exists; RETURN_IF_ERROR(new_file->Exists(&exists)); if (!exists) { return OpStatus::ERR; } // Make sure everything is flushed, Close() calls fflush() explicitly if (new_file->IsOpen()) { new_file->Close(); } // Rename the file if (!MoveFileEx(new_file->GetFullPath(), GetFullPath(), MOVEFILE_REPLACE_EXISTING)) return GetWindowsLastError(); return OpStatus::OK; } OP_STATUS WindowsOpLowLevelFile::Delete() { DWORD attr; attr = GetFileAttributes(m_path.CStr()); if (attr != 0xFFFFFFFF && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { if (RemoveDirectory(m_path.CStr())) { return OpStatus::OK; } else { return GetWindowsLastError(); } } if (DeleteFile(m_path.CStr())) { return OpStatus::OK; } else { return GetWindowsLastError(); } } OP_STATUS WindowsOpLowLevelFile::Flush() { OP_STATUS result = OpStatus::ERR; if (m_fp) { if (fflush(m_fp) == 0) { result = OpStatus::OK; } } return result; } OP_STATUS WindowsOpLowLevelFile::SetFileLength(OpFileLength len) { if (!m_fp) { return OpStatus::ERR; } RETURN_IF_ERROR(Flush()); int result = _chsize_s(_fileno(m_fp), len); if (result == 0) { return OpStatus::OK; } else { return OpStatus::ERR; } } OP_STATUS WindowsOpLowLevelFile::Move(const class DesktopOpLowLevelFile *new_file) { // Move the file OpString &new_name = ((WindowsOpLowLevelFile *) new_file)->m_path; if (0 == MoveFile(m_path.CStr(), new_name.CStr())) { DWORD err = GetLastError(); if (err == ERROR_NOT_ENOUGH_MEMORY || err == ERROR_OUTOFMEMORY) { return OpStatus::ERR_NO_MEMORY; } else { return OpStatus::ERR; } } // Change the name of the file return m_path.Set(new_name); } OP_STATUS WindowsOpLowLevelFile::Stat(struct _stat *buffer) { if (!buffer) { return OpStatus::ERR_NULL_POINTER; } int retval; retval = _wstat(GetFullPath(), buffer); if (retval == -1) { return OpStatus::ERR_FILE_NOT_FOUND; } return OpStatus::OK; } OP_STATUS WindowsOpLowLevelFile::ReadLine(char *string, int max_length) { if (!string || !m_fp) { return OpStatus::ERR_NULL_POINTER; } *string = 0; if (fgets(string, max_length, m_fp) == NULL) { return (feof(m_fp)!=0 && ferror(m_fp)==0) ? OpStatus::OK : OpStatus::ERR; } return OpStatus::OK; } OpLowLevelFile* WindowsOpLowLevelFile::CreateCopy() { OP_ASSERT(m_path.CStr() != NULL); WindowsOpLowLevelFile* copy = OP_NEW(WindowsOpLowLevelFile, ()); if (copy && m_path.CStr() != NULL) { if (OpStatus::IsError(copy->m_path.Set(m_path))) { OP_DELETE(copy); copy = NULL; } } return copy; } OpLowLevelFile* WindowsOpLowLevelFile::CreateTempFile(const uni_char* prefix) { OpString path; if (OpStatus::IsError(path.Set(m_path.CStr()))) return NULL; int slash = path.FindLastOf('\\'); if (slash != KNotFound) { path.Delete(slash+1); } uni_char new_filename[MAX_PATH]; if (0 == GetTempFileName(path.CStr(), prefix, 0, new_filename)) { //Is missing directory cause of error? if (GetFileAttributes(path.CStr()) == 0xFFFFFFFF) { DWORD error = GetLastError(); if(error == ERROR_PATH_NOT_FOUND || error == ERROR_FILE_NOT_FOUND) { //Create folder and try again OpStatus::Ignore(MakeParentFolderPath(path.CStr())); if (0 == GetTempFileName(path.CStr(), prefix, 0, new_filename)) { return NULL; } } else { return NULL; } } else { return NULL; } } WindowsOpLowLevelFile* new_file = new WindowsOpLowLevelFile(); if (new_file == NULL || OpStatus::IsError(new_file->Construct(new_filename))) { return NULL; } return new_file; } OP_STATUS WindowsOpLowLevelFile::CopyContents(const OpLowLevelFile* source) { OP_ASSERT(source != NULL); if (source == NULL) { return OpStatus::ERR; } if (IsOpen() || source->IsOpen()) { return OpStatus::ERR; } // Must read through OpLowLevelFile::Read(). source->GetFullPath() is not // guaranteed to point to a physical file. (DSK-302759) // FIXME: But that means we have to use non-const methods of it! OpLowLevelFile* mutable_source = const_cast<OpLowLevelFile*>(source); RETURN_IF_ERROR(mutable_source->Open(OPFILE_READ)); OP_STATUS result = OpStatus::ERR; const uni_char mode[] = UNI_L("wbN"); const int share_flag = _SH_DENYWR; FILE* dest = _wfsopen(m_path.CStr(), mode, share_flag); if (dest == NULL) { OpStatus::Ignore(MakeParentFolderPath(m_path.CStr())); errno = 0; dest = _wfsopen(m_path.CStr(), mode, share_flag); } if (dest == NULL) { result = ErrNoToStatus(errno); } else { // Should this be a tweak maybe? const size_t buffer_size = 0x8000; char buffer[buffer_size]; OpFileLength bytes_read; do { bytes_read = 0; result = mutable_source->Read(buffer, buffer_size, &bytes_read); if (OpStatus::IsError(result)) { break; } if (bytes_read > 0) { errno = 0; if (fwrite(buffer, 1, bytes_read, dest) != bytes_read) { result = ErrNoToStatus(errno); break; } } } while (!source->Eof()); if (OpStatus::IsSuccess(result) && ferror(dest) != 0) { result = OpStatus::ERR; } errno = 0; if (fclose(dest) != 0 && OpStatus::IsSuccess(result)) { result = ErrNoToStatus(errno); } } const OP_STATUS close_result = mutable_source->Close(); if (OpStatus::IsSuccess(result)) { result = close_result; } return result; } #ifdef PI_ASYNC_FILE_OP /* static */ unsigned __stdcall WindowsOpLowLevelFile::FileThreadFunc( void* pArguments ) { WindowsOpLowLevelFile* sync_file = NULL; OP_STATUS status = OpStatus::OK; BOOL abort = FALSE; // get the class we will operate on WindowsOpLowLevelFile* file = (WindowsOpLowLevelFile *)pArguments; // get a reference to all the data will we deal with OpVector<WindowsOpLowLevelFile::FileThreadData> *data_collection = &file->m_thread_data; // set up out events to wait for notifications on HANDLE ahEvents[] = { file->m_event_quit, file->m_event_file}; while(!abort) { // wait for any of the events to be triggered DWORD res = ::WaitForMultipleObjects(2, ahEvents, FALSE, INFINITE); switch (res) { case WAIT_OBJECT_0: // Shut down! abort = TRUE; break; case (WAIT_OBJECT_0 + 1): // data is ready to be read/written/deleted { OpFileLength old_pos = 0; BOOL have_data = FALSE; WindowsOpLowLevelFile::FileThreadData *data = NULL; // Protect all access to the m_thread_data collection, try to keep the critical sections as short as possible. // The assumption is that no outside code modifies the items inside the collection, but only the collection itself, // and that all items are added at the end of the collection ::EnterCriticalSection(&file->m_thread_cs); have_data = data_collection->GetCount() != 0; if(have_data) { data = data_collection->Get(0); } ::LeaveCriticalSection(&file->m_thread_cs); while(have_data) { if(data->m_seek_pos != FILE_LENGTH_NONE) { // get the old position. We need to set the position back after finishing the operating, as per the specification status = data->m_file->GetFilePos(&old_pos); if(OpStatus::IsSuccess(status)) { // do the seek first status = data->m_file->SetFilePos(data->m_seek_pos, SEEK_FROM_START); } if(OpStatus::IsError(status)) { // we had an error, let's call off the operation now switch(data->m_operation) { case WindowsOpLowLevelFile::FileThreadData::THREAD_OP_READ: g_thread_tools->PostMessageToMainThread(MSG_ASYNC_FILE_READ, (MH_PARAM_1)new FileNotification(data->m_operation, data->m_file, data->m_listener, status, 0), NULL); break; case WindowsOpLowLevelFile::FileThreadData::THREAD_OP_WRITE: g_thread_tools->PostMessageToMainThread(MSG_ASYNC_FILE_WRITTEN, (MH_PARAM_1)new FileNotification(data->m_operation, data->m_file, data->m_listener, status, 0), NULL); break; } } } // search went fine, do the operation if(OpStatus::IsSuccess(status)) { OpFileLength read; switch(data->m_operation) { case WindowsOpLowLevelFile::FileThreadData::THREAD_OP_SYNC: sync_file = data->m_file; break; case WindowsOpLowLevelFile::FileThreadData::THREAD_OP_READ: status = data->m_file->Read((void *)data->m_buffer, data->m_data_len, &read); if(old_pos) { status = data->m_file->SetFilePos(old_pos, SEEK_FROM_START); } g_thread_tools->PostMessageToMainThread(MSG_ASYNC_FILE_READ, (MH_PARAM_1)new FileNotification(data->m_operation, data->m_file, data->m_listener, status, read), NULL); break; case WindowsOpLowLevelFile::FileThreadData::THREAD_OP_WRITE: status = data->m_file->Write((void *)data->m_buffer, data->m_data_len); if(old_pos) { status = data->m_file->SetFilePos(old_pos, SEEK_FROM_START); } g_thread_tools->PostMessageToMainThread(MSG_ASYNC_FILE_WRITTEN, (MH_PARAM_1)new FileNotification(data->m_operation, data->m_file, data->m_listener, status, 0), NULL); break; case WindowsOpLowLevelFile::FileThreadData::THREAD_OP_DELETE: status = data->m_file->Delete(); g_thread_tools->PostMessageToMainThread(MSG_ASYNC_FILE_DELETED, (MH_PARAM_1)new FileNotification(data->m_operation, data->m_file, data->m_listener, status, 0), NULL); break; case WindowsOpLowLevelFile::FileThreadData::THREAD_OP_FLUSH: status = data->m_file->Flush(); g_thread_tools->PostMessageToMainThread(MSG_ASYNC_FILE_FLUSHED, (MH_PARAM_1)new FileNotification(data->m_operation, data->m_file, data->m_listener, status, 0), NULL); break; } } status = OpStatus::OK; ::EnterCriticalSection(&file->m_thread_cs); // delete the item data_collection->Delete(0, 1); have_data = data_collection->GetCount() != 0; if(have_data) { data = data_collection->Get(0); } ::LeaveCriticalSection(&file->m_thread_cs); } if(sync_file) { // event was fired based on a Sync() request, so signal the main thread that we're done now g_thread_tools->PostMessageToMainThread(MSG_ASYNC_FILE_SYNC, (MH_PARAM_1)sync_file, NULL); } } break; case WAIT_FAILED: // something wrong! default: OP_ASSERT(0); } } // signal main thread that we are quitting SetEvent(file->m_event_quit_done); _endthreadex(0); return 0; } OP_STATUS WindowsOpLowLevelFile::InitThread() { // If this asserts goes off, core is not initialized. Core is needed for serialized paths. // Please correct the calling code, to either not use serialized path, or don't use OpLowLevelFile. OP_ASSERT(g_opera && g_thread_tools); if(!m_event_quit) { m_event_quit = CreateEvent(NULL, FALSE, FALSE, NULL); } if(!m_event_quit_done) { m_event_quit_done = CreateEvent(NULL, FALSE, FALSE, NULL); } if(!m_event_file) { m_event_file = CreateEvent(NULL, FALSE, FALSE, NULL); } if(!m_event_sync_done) { m_event_sync_done = CreateEvent(NULL, FALSE, FALSE, NULL); } if(!m_event_quit || !m_event_quit_done || !m_event_file || !m_event_sync_done) { return OpStatus::ERR_NO_MEMORY; } // Create the thread. if(!m_thread_handle) { ::InitializeCriticalSection(&m_thread_cs); m_thread_handle = (HANDLE)_beginthreadex( NULL, 0, &FileThreadFunc, (void *)this, 0, NULL); if(!m_thread_handle) { return OpStatus::ERR_NO_MEMORY; } } return OpStatus::OK; } OP_STATUS WindowsOpLowLevelFile::ReadAsync(OpLowLevelFileListener* listener, void* data, OpFileLength len, OpFileLength abs_pos) { OP_STATUS status = OpStatus::OK; status = InitThread(); if(OpStatus::IsError(status)) { return status; } FileThreadData *thread_data = new FileThreadData(); if(!thread_data) { return OpStatus::ERR_NO_MEMORY; } thread_data->m_seek_pos = abs_pos; thread_data->m_buffer = data; thread_data->m_file = this; thread_data->m_data_len = len; thread_data->m_listener = listener; thread_data->m_operation = FileThreadData::THREAD_OP_READ; // protect all access to the m_thread_data collection ::EnterCriticalSection(&m_thread_cs); if(OpStatus::IsError(m_thread_data.Add(thread_data))) { ::LeaveCriticalSection(&m_thread_cs); return OpStatus::ERR_NO_MEMORY; } ::LeaveCriticalSection(&m_thread_cs); // signal the thread to start the operation SetEvent(m_event_file); return OpStatus::OK; } OP_STATUS WindowsOpLowLevelFile::WriteAsync(OpLowLevelFileListener* listener, const void* data, OpFileLength len, OpFileLength pos) { OP_STATUS status = OpStatus::OK; status = InitThread(); if(OpStatus::IsError(status)) { return status; } FileThreadData *thread_data = new FileThreadData(); if(!thread_data) { return OpStatus::ERR_NO_MEMORY; } thread_data->m_seek_pos = pos; thread_data->m_buffer = data; thread_data->m_file = this; thread_data->m_data_len = len; thread_data->m_listener = listener; thread_data->m_operation = FileThreadData::THREAD_OP_WRITE; // protect all access to the m_thread_data collection ::EnterCriticalSection(&m_thread_cs); if(OpStatus::IsError(m_thread_data.Add(thread_data))) { ::LeaveCriticalSection(&m_thread_cs); return OpStatus::ERR_NO_MEMORY; } ::LeaveCriticalSection(&m_thread_cs); // signal the thread to start the operation SetEvent(m_event_file); return OpStatus::OK; } OP_STATUS WindowsOpLowLevelFile::FlushAsync(OpLowLevelFileListener* listener) { OP_STATUS status = OpStatus::OK; status = InitThread(); if(OpStatus::IsError(status)) { return status; } FileThreadData *thread_data = new FileThreadData(); if(!thread_data) { return OpStatus::ERR_NO_MEMORY; } thread_data->m_file = this; thread_data->m_listener = listener; thread_data->m_operation = FileThreadData::THREAD_OP_FLUSH; // protect all access to the m_thread_data collection ::EnterCriticalSection(&m_thread_cs); if(OpStatus::IsError(m_thread_data.Add(thread_data))) { ::LeaveCriticalSection(&m_thread_cs); return OpStatus::ERR_NO_MEMORY; } ::LeaveCriticalSection(&m_thread_cs); // signal the thread to start the operation SetEvent(m_event_file); return OpStatus::OK; } OP_STATUS WindowsOpLowLevelFile::DeleteAsync(OpLowLevelFileListener* listener) { OP_STATUS status = OpStatus::OK; status = InitThread(); if(OpStatus::IsError(status)) { return status; } FileThreadData *thread_data = new FileThreadData(); if(!thread_data) { return OpStatus::ERR_NO_MEMORY; } thread_data->m_file = this; thread_data->m_listener = listener; thread_data->m_operation = FileThreadData::THREAD_OP_DELETE; // protect all access to the m_thread_data collection ::EnterCriticalSection(&m_thread_cs); if(OpStatus::IsError(m_thread_data.Add(thread_data))) { ::LeaveCriticalSection(&m_thread_cs); return OpStatus::ERR_NO_MEMORY; } ::LeaveCriticalSection(&m_thread_cs); // signal the thread to start the operation SetEvent(m_event_file); return OpStatus::OK; } BOOL WindowsOpLowLevelFile::IsAsyncInProgress() { ::EnterCriticalSection(&m_thread_cs); BOOL in_progress = m_thread_data.GetCount() != 0; ::LeaveCriticalSection(&m_thread_cs); return in_progress; } OP_STATUS WindowsOpLowLevelFile::Sync() { // signal thread to dump all data if(!m_thread_handle) { return OpStatus::OK; } FileThreadData *thread_data = new FileThreadData(); if(!thread_data) { return OpStatus::ERR_NO_MEMORY; } thread_data->m_file = this; thread_data->m_operation = FileThreadData::THREAD_OP_SYNC; // protect all access to the m_thread_data collection ::EnterCriticalSection(&m_thread_cs); if(OpStatus::IsError(m_thread_data.Add(thread_data))) { ::LeaveCriticalSection(&m_thread_cs); return OpStatus::ERR_NO_MEMORY; } ::LeaveCriticalSection(&m_thread_cs); // signal the thread to start the operation SetEvent(m_event_file); // wait for completion HANDLE ahEvents[] = { m_event_sync_done }; while(TRUE) { // wait for any of the events to be triggered DWORD res = ::MsgWaitForMultipleObjects(1, ahEvents, FALSE, 1000*30, QS_ALLINPUT); if(res == WAIT_OBJECT_0) { break; } else if(res == WAIT_OBJECT_0 + 1) { MSG msg ; // Read all of the messages in this next loop, // removing each message as we read it. while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { // Dispatch the message. DispatchMessage(&msg); } // End of PeekMessage while loop. } else { // timeout OP_ASSERT(FALSE); break; } } return OpStatus::OK; } #endif // PI_ASYNC_FILE_OP // called from WindowsOpThreadTools.cpp void HandleAsyncFileMessages(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { #ifdef PI_ASYNC_FILE_OP switch(msg) { case MSG_ASYNC_FILE_WRITTEN: { WindowsOpLowLevelFile::FileNotification *data = (WindowsOpLowLevelFile::FileNotification *)par1; if(data) { data->m_listener->OnDataWritten(data->m_file, data->m_status, 0); } else { OP_ASSERT(FALSE); } delete data; } break; case MSG_ASYNC_FILE_READ: { WindowsOpLowLevelFile::FileNotification *data = (WindowsOpLowLevelFile::FileNotification *)par1; if(data) { data->m_listener->OnDataRead(data->m_file, data->m_status, data->m_data_len); } else { OP_ASSERT(FALSE); } delete data; } break; case MSG_ASYNC_FILE_DELETED: { WindowsOpLowLevelFile::FileNotification *data = (WindowsOpLowLevelFile::FileNotification *)par1; if(data) { data->m_listener->OnDeleted(data->m_file, data->m_status); } else { OP_ASSERT(FALSE); } delete data; } break; case MSG_ASYNC_FILE_FLUSHED: { WindowsOpLowLevelFile::FileNotification *data = (WindowsOpLowLevelFile::FileNotification *)par1; if(data) { data->m_listener->OnFlushed(data->m_file, data->m_status); } else { OP_ASSERT(FALSE); } delete data; } break; case MSG_ASYNC_FILE_SYNC: { WindowsOpLowLevelFile *file = (WindowsOpLowLevelFile *)par1; SetEvent(file->m_event_sync_done); } break; } #endif // PI_ASYNC_FILE_OP } void WindowsOpLowLevelFile::ShutdownThread() { #ifdef PI_ASYNC_FILE_OP Sync(); // signal thread to quit if(m_event_quit) { SetEvent(m_event_quit); // wait for thread to signal it will quit if(WAIT_OBJECT_0 != (WaitForSingleObject(m_event_quit_done, 1000*15))) // wait max 15 seconds { OP_ASSERT(FALSE); } } if(m_thread_handle) { CloseHandle(m_thread_handle); m_thread_handle = NULL; ::DeleteCriticalSection(&m_thread_cs); } if(m_event_quit) { CloseHandle(m_event_quit); m_event_quit = NULL; } if(m_event_quit_done) { CloseHandle(m_event_quit_done); m_event_quit_done = NULL; } if(m_event_file) { CloseHandle(m_event_file); m_event_file = NULL; } if(m_event_sync_done) { CloseHandle(m_event_sync_done); m_event_sync_done = NULL; } #endif // PI_ASYNC_FILE_OP }
#include "../include/basic.h" User::User() { ; } std::list<User *> User::getAll() { std::string delimiter = DELIMITER; std::ifstream file("users.txt"); std::string line; std::string properties[NUMBER_USER_PROPERTIES]; std::list<User *> users; while (std::getline(file, line)) { std::stringstream ssin(line); int index_properties = 0; size_t position = 0; while ((position = line.find(delimiter)) != std::string::npos) { std::string value = line.substr(0, position); properties[index_properties] = value; ++index_properties; line.erase(0, position + delimiter.length()); } properties[index_properties] = line; User *const user = new User(); user->setID(std::stoi(properties[0])); user->setDNI(std::stol(properties[1])); user->setPhone(std::stol(properties[2])); user->setFirstName(properties[3]); user->setLastName(properties[4]); user->setEmail(properties[5]); user->setAddress(properties[6]); user->setUsername(properties[7]); user->setPassword(properties[8]); user->setRoleId(std::stoi(properties[9])); users.push_front(user); } return users; }
#include "OPENGL_Include.h" #include "OpenGLDrvPrivate.h" #include <iostream> #include <string> #include <algorithm> using namespace std; #include "OpenGLES31.h" static void printGLString(const char *name, GLenum s) { const char *v = (const char *)glGetString(s); #ifdef ANDROID LOGI("%s", v); #else cout <<endl<<name<<" "<< v <<endl; #endif } static void printGLExtension() { const char *v = (const char *)glGetString(GL_EXTENSIONS); string s(v); replace(s.begin(), s.end(), ' ', '\n'); #ifdef ANDROID LOGI("%s", s.c_str()); #else cout <<endl<<"Extensions: "<<endl<< s << endl; #endif } static void LogOpenglInfo() { printGLString("Version", GL_VERSION); printGLString("Vendor", GL_VENDOR); printGLString("Renderer", GL_RENDERER); printGLExtension(); } static void InitGLFormat(); void FOpenGLDynamicRHI::Init() { LogOpenglInfo(); InitGLFormat(); const string e; FOpenGL::ProcessExtensions(e); InitializeStateResources(); //init use GLFW } void FOpenGLDynamicRHI::Shutdown() { //not implement } FOpenGLContextState& FOpenGLDynamicRHI::GetContextStateForCurrentContext() { return RenderingContextState; } FOpenGLTextureFormat GOpenGLTextureFormats[PF_MAX]; extern FPixelFormatInfo GPixelFormats[PF_MAX]; bool GDisableOpenGLDebugOutput = false; static inline void SetupTextureFormat(EPixelFormat Format, const FOpenGLTextureFormat& GLFormat) { GOpenGLTextureFormats[Format] = GLFormat; GPixelFormats[Format].Supported = (GLFormat.Format != GL_NONE && (GLFormat.InternalFormat[0] != GL_NONE || GLFormat.InternalFormat[1] != GL_NONE)); } static void InitGLFormat() { for (int32 PF = 0; PF < PF_MAX; ++PF) { SetupTextureFormat(EPixelFormat(PF), FOpenGLTextureFormat()); } GLenum DepthFormat = FOpenGL::GetDepthFormat(); GLenum ShadowDepthFormat = FOpenGL::GetShadowDepthFormat(); // Initialize the platform pixel format map. InternalFormat InternalFormatSRGB Format Type bCompressed bBGRA SetupTextureFormat(PF_Unknown, FOpenGLTextureFormat()); SetupTextureFormat(PF_A32B32G32R32F, FOpenGLTextureFormat(GL_RGBA32F, GL_NONE, GL_RGBA, GL_FLOAT, false, false)); SetupTextureFormat(PF_UYVY, FOpenGLTextureFormat()); //@todo: ES2 requires GL_OES_depth_texture extension to support depth textures of any kind. SetupTextureFormat(PF_ShadowDepth, FOpenGLTextureFormat(ShadowDepthFormat, GL_NONE, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false, false)); SetupTextureFormat(PF_D24, FOpenGLTextureFormat(DepthFormat, GL_NONE, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false, false)); SetupTextureFormat(PF_A16B16G16R16, FOpenGLTextureFormat(GL_RGBA16, GL_RGBA16, GL_RGBA, GL_UNSIGNED_SHORT, false, false)); SetupTextureFormat(PF_A1, FOpenGLTextureFormat()); SetupTextureFormat(PF_R16G16B16A16_UINT, FOpenGLTextureFormat(GL_RGBA16UI, GL_NONE, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT, false, false)); SetupTextureFormat(PF_R16G16B16A16_SINT, FOpenGLTextureFormat(GL_RGBA16I, GL_NONE, GL_RGBA_INTEGER, GL_SHORT, false, false)); SetupTextureFormat(PF_R5G6B5_UNORM, FOpenGLTextureFormat()); { // Not supported for rendering: SetupTextureFormat(PF_G16, FOpenGLTextureFormat(GL_R16, GL_R16, GL_RED, GL_UNSIGNED_SHORT, false, false)); SetupTextureFormat(PF_R32_FLOAT, FOpenGLTextureFormat(GL_R32F, GL_R32F, GL_RED, GL_FLOAT, false, false)); SetupTextureFormat(PF_G16R16F, FOpenGLTextureFormat(GL_RG16F, GL_RG16F, GL_RG, GL_HALF_FLOAT, false, false)); SetupTextureFormat(PF_G16R16F_FILTER, FOpenGLTextureFormat(GL_RG16F, GL_RG16F, GL_RG, GL_HALF_FLOAT, false, false)); SetupTextureFormat(PF_G32R32F, FOpenGLTextureFormat(GL_RG32F, GL_RG32F, GL_RG, GL_FLOAT, false, false)); SetupTextureFormat(PF_A2B10G10R10, FOpenGLTextureFormat(GL_RGB10_A2, GL_RGB10_A2, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, false, false)); SetupTextureFormat(PF_R16F, FOpenGLTextureFormat(GL_R16F, GL_R16F, GL_RED, GL_HALF_FLOAT, false, false)); SetupTextureFormat(PF_R16F_FILTER, FOpenGLTextureFormat(GL_R16F, GL_R16F, GL_RED, GL_HALF_FLOAT, false, false)); if (FOpenGL::SupportsR11G11B10F()) { // Note: Also needs to include support for compute shaders to be defined here (e.g. glBindImageTexture) SetupTextureFormat(PF_FloatRGB, FOpenGLTextureFormat(GL_R11F_G11F_B10F, GL_R11F_G11F_B10F, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, false, false)); SetupTextureFormat(PF_FloatR11G11B10, FOpenGLTextureFormat(GL_RGBA16F, GL_RGBA16F, GL_RGB, GL_HALF_FLOAT, false, false)); } else { SetupTextureFormat(PF_FloatRGB, FOpenGLTextureFormat(GL_RGBA16F, GL_RGBA16F, GL_RGB, GL_HALF_FLOAT, false, false)); SetupTextureFormat(PF_FloatR11G11B10, FOpenGLTextureFormat(GL_R11F_G11F_B10F, GL_R11F_G11F_B10F, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, false, false)); } SetupTextureFormat(PF_V8U8, FOpenGLTextureFormat(GL_RG8_SNORM, GL_NONE, GL_RG, GL_BYTE, false, false)); SetupTextureFormat(PF_R8G8, FOpenGLTextureFormat(GL_RG8, GL_NONE, GL_RG, GL_UNSIGNED_BYTE, false, false)); SetupTextureFormat(PF_BC5, FOpenGLTextureFormat(GL_COMPRESSED_RG_RGTC2, GL_COMPRESSED_RG_RGTC2, GL_RG, GL_UNSIGNED_BYTE, true, false)); SetupTextureFormat(PF_BC4, FOpenGLTextureFormat(GL_COMPRESSED_RED_RGTC1, GL_COMPRESSED_RED_RGTC1, GL_RED, GL_UNSIGNED_BYTE, true, false)); SetupTextureFormat(PF_A8, FOpenGLTextureFormat(GL_R8, GL_NONE, GL_RED, GL_UNSIGNED_BYTE, false, false)); SetupTextureFormat(PF_R32_UINT, FOpenGLTextureFormat(GL_R32UI, GL_NONE, GL_RED_INTEGER, GL_UNSIGNED_INT, false, false)); SetupTextureFormat(PF_R32_SINT, FOpenGLTextureFormat(GL_R32I, GL_NONE, GL_RED_INTEGER, GL_INT, false, false)); SetupTextureFormat(PF_R16_UINT, FOpenGLTextureFormat(GL_R16UI, GL_NONE, GL_RED_INTEGER, GL_UNSIGNED_SHORT, false, false)); SetupTextureFormat(PF_R16_SINT, FOpenGLTextureFormat(GL_R16I, GL_NONE, GL_RED_INTEGER, GL_SHORT, false, false)); SetupTextureFormat(PF_FloatRGBA, FOpenGLTextureFormat(GL_RGBA16F, GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, false, false)); SetupTextureFormat(PF_G8, FOpenGLTextureFormat(GL_R8, GL_R8, GL_RED, GL_UNSIGNED_BYTE, false, false)); SetupTextureFormat(PF_B8G8R8A8, FOpenGLTextureFormat(GL_RGBA8, GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, false, true)); SetupTextureFormat(PF_R8G8B8A8, FOpenGLTextureFormat(GL_RGBA8, GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, false, false)); SetupTextureFormat(PF_R8G8B8, FOpenGLTextureFormat(GL_RGB8, GL_SRGB8, GL_RGB, GL_UNSIGNED_BYTE, false, false)); if (FOpenGL::SupportsRG16UI()) { // The user should check for support for PF_G16R16 and implement a fallback if it's not supported! SetupTextureFormat(PF_G16R16, FOpenGLTextureFormat(GL_RG16, GL_RG16, GL_RG, GL_UNSIGNED_SHORT, false, false)); } { SetupTextureFormat(PF_G8, FOpenGLTextureFormat(GL_R8, GL_SRGB8, GL_RED, GL_UNSIGNED_BYTE, false, false)); //SetupTextureFormat(PF_B8G8R8A8, FOpenGLTextureFormat(GL_RGBA8, GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, false, false)); // SetupTextureFormat(PF_R8G8B8A8, FOpenGLTextureFormat(GL_RGBA8, GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, false, false)); SetupTextureFormat(PF_G16R16, FOpenGLTextureFormat(GL_RG16, GL_RG16, GL_RG, GL_UNSIGNED_SHORT, false, false)); } if (FOpenGL::SupportsPackedDepthStencil()) { SetupTextureFormat(PF_DepthStencil, FOpenGLTextureFormat(GL_DEPTH24_STENCIL8, GL_NONE, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, false, false)); } else { // @todo android: This is cheating by not setting a stencil anywhere, need that! And Shield is still rendering black scene SetupTextureFormat(PF_DepthStencil, FOpenGLTextureFormat(DepthFormat, GL_NONE, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false, false)); } } { // ES2-based cases GLuint BGRA8888 = GL_RGBA; GLuint RGBA8 = GL_RGBA; //SetupTextureFormat(PF_B8G8R8A8, FOpenGLTextureFormat(GL_BGRA, FOpenGL::SupportsSRGB() ? GL_SRGB_ALPHA_EXT : GL_BGRA, BGRA8888, GL_UNSIGNED_BYTE, false, false)); //SetupTextureFormat(PF_B8G8R8A8, FOpenGLTextureFormat(GL_RGBA, FOpenGL::SupportsSRGB() ? GL_SRGB_ALPHA_EXT : GL_RGBA, GL_BGRA8_EXT, FOpenGL::SupportsSRGB() ? GL_SRGB8_ALPHA8_EXT : GL_BGRA8_EXT, BGRA8888, GL_UNSIGNED_BYTE, false, false)); SetupTextureFormat(PF_R8G8B8A8, FOpenGLTextureFormat(RGBA8, FOpenGL::SupportsSRGB() ? GL_SRGB_ALPHA_EXT : RGBA8, GL_RGBA8, FOpenGL::SupportsSRGB() ? GL_SRGB8_ALPHA8_EXT : GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, false, false)); SetupTextureFormat(PF_G8, FOpenGLTextureFormat(GL_LUMINANCE, GL_LUMINANCE, GL_LUMINANCE, GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE, false, false)); SetupTextureFormat(PF_A8, FOpenGLTextureFormat(GL_ALPHA, GL_ALPHA, GL_ALPHA, GL_ALPHA, GL_ALPHA, GL_UNSIGNED_BYTE, false, false)); { SetupTextureFormat(PF_FloatRGBA, FOpenGLTextureFormat(GL_RGBA, GL_RGBA, GL_RGBA, GL_HALF_FLOAT, false, false)); } { SetupTextureFormat(PF_FloatRGBA, FOpenGLTextureFormat(GL_RGBA, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, false, false)); } { // @todo android: This is cheating by not setting a stencil anywhere, need that! And Shield is still rendering black scene SetupTextureFormat(PF_DepthStencil, FOpenGLTextureFormat(GL_DEPTH_COMPONENT, GL_NONE, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false, false)); } } }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; int a[1100]; int main() { int t,turn = 0; scanf("%d",&t); while (turn++ < t) { int n; scanf("%d",&n); for (int i = 1;i <= n; i++) scanf("%d",&a[i]); bool maxheap = true,minheap = true,incbst = true,decbst = true; for (int i = 1;i <= n; i++) { if (2*i <= n) { if (a[2*i] > a[i]) {maxheap = false;incbst = false;} if (a[2*i] < a[i]) {minheap = false;decbst = false;} } if (2*i+1 <= n) { if (a[2*i+1] > a[i]) {maxheap = false;decbst = false;} if (a[2*i+1] < a[i]) {minheap = false;incbst = false;} } if (!(maxheap || minheap || incbst || decbst)) break; } printf("Case #%d: ",turn); if (maxheap || minheap) if (incbst || decbst) printf("Both\n"); else printf("Heap\n"); else if (incbst || decbst) printf("BST\n"); else printf("Neither\n"); } return 0; }
// -*- LSST-C++ -*- /* * LSST Data Management System * Copyright 2014-2015 AURA/LSST. * * This product includes software developed by the * LSST Project (http://www.lsst.org/). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the LSST License Statement and * the GNU General Public License along with this program. If not, * see <http://www.lsstcorp.org/LegalNotices/>. */ /** * @file * * Basic usage: * * Construct a UserQueryFactory, then create a new UserQuery * object. You will get a session ID that will identify the UserQuery * for use with this proxy. The query is parsed and prepared for * execution as much as possible, without knowing partition coverage. * * * UserQuery_getQueryProcessingError(int session) // See if there are errors * * UserQuery_getConstraints(int session) // Retrieve the detected * constraints so that we can apply them to see which chunks we * need. (done in Python) * * UserQuery_submit(int session) // Trigger the dispatch of all chunk * queries for the UserQuery * * @author Daniel L. Wang, SLAC */ // Class header #include "ccontrol/userQueryProxy.h" // LSST headers #include "lsst/log/Log.h" // Qserv headers #include "ccontrol/MissingUserQuery.h" #include "ccontrol/SessionManager.h" #include "ccontrol/UserQuery.h" #include "util/StringHash.h" namespace { } // anonymous namespace namespace lsst { namespace qserv { namespace ccontrol { class UserQueryManager : public SessionManager<UserQuery::Ptr> { public: UserQueryManager() {} UserQuery::Ptr get(int id) { UserQuery::Ptr p = getSession(id); if(!p) { throw MissingUserQuery(id); } return p; } }; static UserQueryManager uqManager; std::string UserQuery_getQueryProcessingError(int session) { std::string s; try { s = uqManager.get(session)->getError(); } catch (std::exception& e) { s = e.what(); LOGF_WARN(s); } return s; } /// Abort a running query void UserQuery_kill(int session) { LOGF_INFO("EXECUTING UserQuery_kill(%1%)" % session); try { uqManager.get(session)->kill(); } catch (const std::exception& e) { LOGF_WARN(e.what()); } } /// Dispatch all chunk queries for this query void UserQuery_submit(int session) { LOGF_DEBUG("EXECUTING UserQuery_submit(%1%)" % session); try { uqManager.get(session)->submit(); } catch (const std::exception& e) { LOGF_ERROR(e.what()); } } /// Block until execution succeeds or fails completely QueryState UserQuery_join(int session) { LOGF_DEBUG("EXECUTING UserQuery_join(%1%)" % session); try { return uqManager.get(session)->join(); } catch (const std::exception& e) { LOGF_ERROR(e.what()); return QueryState::ERROR; } } /// Discard the UserQuery by destroying it and forgetting about its id. void UserQuery_discard(int session) { try { UserQuery::Ptr p = uqManager.get(session); p->discard(); p.reset(); uqManager.discardSession(session); } catch (const std::exception& e) { LOGF_ERROR(e.what()); } } /// Take ownership of a UserQuery object and return a sessionId int UserQuery_takeOwnership(UserQuery* uq) { UserQuery::Ptr uqp(uq); return uqManager.newSession(uqp); } UserQuery& UserQuery_get(int session) { return *uqManager.get(session); } }}} // namespace lsst::qserv::ccontrol
#include "TilesetWidget.hpp" #include "ui_TilesetWidget.h" #include "TileDefinitionDialog.hpp" #include <Tileset.hpp> using namespace Maint; TilesetWidget::TilesetWidget(QWidget *parent) : QWidget(parent), ui(new Ui::TilesetWidget), _levelManager(NULL), _textureManager(NULL) { ui->setupUi(this); definitionModel = NULL; } TilesetWidget::~TilesetWidget() { delete ui; } void TilesetWidget::SetTilesetModel(TileDefinitionModel* model) { this->definitionModel = model; ui->listView->setModel(model); connect(ui->listView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), SLOT(ListSelectionChanged(QModelIndex,QModelIndex))); } void TilesetWidget::SetDependencies(LevelManager *levelManager, TextureManager *textureManager) { _levelManager = levelManager; _textureManager = textureManager; } /* * * Private Slots * */ void TilesetWidget::ShowNewTileDialog() { if(definitionModel == NULL || _levelManager == NULL || _textureManager == NULL) { return; } Tileset const* tileset = definitionModel->GetTileset(); if(tileset == NULL) { return; } TileDefinitionDialog dialog(tileset, _levelManager, _textureManager, this); if(dialog.exec() != QDialog::Accepted) { return; } TileDefinition d = dialog.GetTileDefinition(); definitionModel->AddTileDefinition(d); } void TilesetWidget::EditTile(const QModelIndex &index) { if(_levelManager == NULL && _textureManager == NULL) { return; } if(definitionModel == NULL && definitionModel->GetTileset() != NULL) { return; } const TileDefinition* tileDefinition = definitionModel->GetTileset()->AtIndex(index.row()); if(tileDefinition == NULL) { return; } TileDefinitionDialog dialog(definitionModel->GetTileset(), _levelManager, _textureManager, this); dialog.SetFields(tileDefinition); if(dialog.exec() != QDialog::Accepted) { return; } definitionModel->SetTileDefinition(index.row(), dialog.GetTileDefinition()); } void TilesetWidget::ListSelectionChanged(QModelIndex current, QModelIndex) { SelectionChanged(current.row()); }
#include "file.h" file::file(/* args */) { } file::~file() { }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #include <cassert> #include <util/BajkaService.h> #include <util/ShellContext.h> #include <util/LifecycleHandler.h> #include <view/openGl/GLContext.h> #include "ShellFactory.h" #include "GameLoop.h" #include "sound/Device.h" #include "EventDispatcher.h" #include "GraphicsService.h" Core::VariantMap ShellFactory::singletons; /****************************************************************************/ std::auto_ptr <GameLoop> ShellFactory::createGameLoop (Util::ShellConfig *sConfig) { assert (sConfig); Util::ShellContext *ctx = createShellContext (sConfig); Util::LifecycleHandler *handler = createLifecycleHandler (); GraphicsService *graphicsService = createGraphicsService (); handler->setGraphicsService (graphicsService); singletons["graphicsService"] = Core::Variant (graphicsService); Util::BajkaService *bajkaService = createBajkaService (); handler->setBajkaService (bajkaService); ctx->glContext = bajkaService->getGLContext (); singletons["glContext"] = Core::Variant (ctx->glContext); handler->setSingletons (&singletons); EventDispatcher *eventDispatcher = createEventDispatcher (); handler->setEventDispatcher (eventDispatcher); singletons["eventDispatcher"] = Core::Variant (eventDispatcher); std::auto_ptr <GameLoop> loop = std::auto_ptr <GameLoop> (new GameLoop (ctx, handler)); loop->init (); return loop; } /****************************************************************************/ Util::ShellContext *ShellFactory::createShellContext (Util::ShellConfig *sConfig) { Util::ShellContext *ctx = new Util::ShellContext; ctx->shellConfig = sConfig; return ctx; } /****************************************************************************/ Util::LifecycleHandler *ShellFactory::createLifecycleHandler () { Util::LifecycleHandler *handler = new Util::LifecycleHandler; return handler; } /****************************************************************************/ GraphicsService *ShellFactory::createGraphicsService () { return new GraphicsService (); } /****************************************************************************/ Util::BajkaService *ShellFactory::createBajkaService () { return new Util::BajkaService (); } /****************************************************************************/ EventDispatcher *ShellFactory::createEventDispatcher () { return new EventDispatcher; }
VehicleDocuments[] = { {Loot_MAGAZINE, 1, ItemORP}, {Loot_MAGAZINE, 1, ItemAVE}, {Loot_MAGAZINE, 1, ItemLRK}, {Loot_MAGAZINE, 1, ItemTNK}, {Loot_MAGAZINE, 1, ItemARM}, {Loot_MAGAZINE, 1, ItemTruckORP}, {Loot_MAGAZINE, 1, ItemTruckAVE}, {Loot_MAGAZINE, 1, ItemTruckLRK}, {Loot_MAGAZINE, 1, ItemTruckTNK}, {Loot_MAGAZINE, 1, ItemTruckARM}, {Loot_MAGAZINE, 1, ItemHeliAVE}, {Loot_MAGAZINE, 1, ItemHeliLRK}, {Loot_MAGAZINE, 1, ItemHeliTNK} }; GenericDocuments[] = { {Loot_MAGAZINE, 1, ItemDocument}, {Loot_MAGAZINE, 1, ItemPlotDeed}, {Loot_MAGAZINE, 1, ItemLetter}, {Loot_MAGAZINE, 1, ItemBook1}, {Loot_MAGAZINE, 1, ItemBook2}, {Loot_MAGAZINE, 1, ItemBook3}, {Loot_MAGAZINE, 1, ItemBook4}, {Loot_MAGAZINE, 1, ItemNewspaper}, {Loot_MAGAZINE, 1, ItemDocumentRamp}, {Loot_MAGAZINE, 1, ItemBookBible}, {Loot_MAGAZINE, 1, ItemTrashPaper}, {Loot_MAGAZINE, 1, ItemTrashPaperMusic} };
#include <cstring> #include <cstdio> #include <string> #include <map> /// Some documentation struct s{ std::string i; }; int main(int argc, char *argv[]){ int b = 1; b++; void* p; int* c = new int(2); char dir[1024]; std::strcpy(dir, argv[1]); std::sprintf(dir, argv[1]); }
// ********************************************************************** // This file was generated by a TAF parser! // TAF version 2.1.5.0 by WSRD Tencent. // Generated from `GMOnline.jce' // ********************************************************************** #include "GMOnline.h" #include "jce/wup.h" #include "servant/BaseF.h" using namespace wup; namespace ServerEngine { GMOnlineProxy* GMOnlineProxy::taf_hash(int64_t key) { return (GMOnlineProxy*)ServantProxy::taf_hash(key); } static ::std::string __ServerEngine__GMOnline_all[]= { }; int GMOnlinePrxCallback::onDispatch(taf::ReqMessagePtr msg) { pair<string*, string*> r = equal_range(__ServerEngine__GMOnline_all, __ServerEngine__GMOnline_all+0, msg->request.sFuncName); if(r.first == r.second) return taf::JCESERVERNOFUNCERR; switch(r.first - __ServerEngine__GMOnline_all) { } return taf::JCESERVERNOFUNCERR; } int GMOnline::onDispatch(taf::JceCurrentPtr _current, vector<char> &_sResponseBuffer) { pair<string*, string*> r = equal_range(__ServerEngine__GMOnline_all, __ServerEngine__GMOnline_all+0, _current->getFuncName()); if(r.first == r.second) return taf::JCESERVERNOFUNCERR; switch(r.first - __ServerEngine__GMOnline_all) { } return taf::JCESERVERNOFUNCERR; } }
#pragma once #include "../../Toolbox/Toolbox.h" #include "Texture2D.h" #include "../../Maths/Primitives/TRect.h" namespace ae { class Image; class ImageHDR; /// \ingroup graphics /// <summary> /// 2D image that can be link to a shader to be rendered. /// </summary> /// <seealso cref="Image"/> class AERO_CORE_EXPORT TextureImage : public Texture2D { public: /// <summary>Create a texture from a image file.</summary> /// <param name="_FilePath">The image file path.</param> /// <param name="_SubRect">The area if you want to select only a part of the image.</param> TextureImage( const std::string& _FilePath, const IntRect& _SubRect = IntRect() ); /// <summary>Create a texture from an image.</summary> /// <param name="_ImageSource">The image source.</param> /// <param name="_SubRect">The area if you want to select only a part of the image.</param> TextureImage( const Image& _ImageSource, const IntRect& _SubRect = IntRect() ); /// <summary>Create a texture from an HDR image.</summary> /// <param name="_ImageSource">The image source.</param> /// <param name="_SubRect">The area if you want to select only a part of the image.</param> TextureImage( const ImageHDR& _ImageSource, const IntRect& _SubRect = IntRect() ); /// <summary>Create a texture from an image.</summary> /// <param name="_FilePath">The path to the image file to load.</param> /// <param name="_SubRect">The area if you want to select only a part of the image.</param> void Set( const std::string& _FilePath, const IntRect& _SubRect = IntRect() ); /// <summary>Create a texture from an image.</summary> /// <param name="_ImageSource">The image source.</param> /// <param name="_SubRect">The area if you want to select only a part of the image.</param> void Set( const Image& _ImageSource, const IntRect& _SubRect = IntRect() ); /// <summary>Create a texture from an HDR image.</summary> /// <param name="_ImageSource">The image source.</param> /// <param name="_SubRect">The area if you want to select only a part of the image.</param> void Set( const ImageHDR& _ImageSource, const IntRect& _SubRect = IntRect() ); /// <summary> /// Path to the loaded image.<para/> /// Can be empty if image created from memory. /// </summary> /// <returns>The file path to the loaded texture.</returns> const std::string& GetFilePath() const; /// <summary>Called by the framebuffer to attach the texture to it.</summary> void AttachToFramebuffer( const FramebufferAttachement& _Attachement ) const override; /// <summary> /// Function called by the editor. /// It allows the class to expose some attributes for user editing. /// Think to call all inherited class function too when overloading. /// </summary> virtual void ToEditor(); private: /// <summary>Hide set method of Texture2D.</summary> using Texture2D::Set; /// <summary>Hide set method of Texture2D.</summary> using Texture2D::Resize; /// <summary>Update the OpenGL texture data from an image data.</summary> /// <param name="_ImageSource">The image source.</param> /// <param name="_SubRect">The area to select in the image.</param> void UpdateDataFromImage( const Image& _ImageSource, const IntRect& _SubRect ); /// <summary>Update the OpenGL texture data from an image data.</summary> /// <param name="_ImageSource">The image source.</param> /// <param name="_SubRect">The area to select in the image.</param> void UpdateDataFromImage( const ImageHDR& _ImageSource, const IntRect& _SubRect ); protected: /// <summary> /// Path to loaded image.<para/> /// Can be a path to an image into the resource manager. /// </summary> std::string m_FilePath; }; } // ae
#pragma once #include "ofMain.h" #include "grotesParticle.h" struct lastParticle { ofPoint pos; float speed; float radius; }; class lastParticles { public: void setup(); void update(); void draw(); void toggleGo(); void clear(); vector <lastParticle> particles; void fadeOut(); void compalsion(); private: int time; bool bFadeOut; bool bakuhatu; int num; };
class Path{ public: int start_x; int start_y; int dist; Path(int a, int b, int c): start_x(a), start_y(b), dist(c){} bool operator < (const Path& p) const{return dist > p.dist;} }; class Solution { private: vector<int> delta = {0,1,0,-1,0}; public: int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) { vector<vector<bool>> visited(maze.size(), vector<bool>(maze[0].size(),false)); priority_queue<Path> q; q.push(Path(start[0], start[1], 0)); while(!q.empty()){ int x = q.top().start_x; int y = q.top().start_y; int dist = q.top().dist; q.pop(); if(x == destination[0] && y == destination[1]){return dist;} if(visited[x][y]) continue; visited[x][y] = true; for(int i = 0; i < 4; ++i){ int newx = x, newy = y, newdist = dist; while(newx >= 0 && newx < maze.size() && newy >= 0 && newy < maze[0].size() && !maze[newx][newy]){ newx += delta[i]; newy += delta[i+1]; ++newdist; } newx -= delta[i]; newy -= delta[i+1]; --newdist; if(visited[newx][newy]) continue; q.push(Path(newx, newy, newdist)); } } return -1; } };
#pragma once #include "Core/Core.h" #include "Common/GeomMath.h" #include "Scene/SceneCamera.h" #include "Render/DrawBasic/Texture.h" #include <string> namespace Rocket { struct TagComponent { std::string Tag; TagComponent() = default; TagComponent(const TagComponent&) = default; TagComponent(const std::string& tag) : Tag(tag) {} }; struct TransformComponent { Vector3f Translation = { 0.0f, 0.0f, 0.0f }; Vector3f Rotation = { 0.0f, 0.0f, 0.0f }; // RPY-ZYX Vector3f Scale = { 1.0f, 1.0f, 1.0f }; TransformComponent() = default; TransformComponent(const TransformComponent&) = default; TransformComponent(const Vector3f& translation) : Translation(translation) {} Matrix4f GetTransform() const { Eigen::AngleAxisf v_z((Rotation[0]/180.0f) * M_PI , Eigen::Vector3f::UnitZ()); Eigen::AngleAxisf v_y((Rotation[1]/180.0f) * M_PI , Eigen::Vector3f::UnitY()); Eigen::AngleAxisf v_x((Rotation[2]/180.0f) * M_PI , Eigen::Vector3f::UnitX()); Matrix4f rot_tran = Matrix4f::Identity(); rot_tran.block<3,3>(0,0) = v_x.matrix() * v_y.matrix() * v_z.matrix(); rot_tran(0, 3) = Translation[0]; rot_tran(1, 3) = Translation[1]; rot_tran(2, 3) = Translation[2]; Matrix4f mat_s = Matrix4f::Identity(); mat_s(0, 0) = Scale[0]; mat_s(1, 1) = Scale[1]; mat_s(2, 2) = Scale[2]; return rot_tran * mat_s; } }; struct SpriteRendererComponent { Vector4f Color{ 1.0f, 1.0f, 1.0f, 1.0f }; SpriteRendererComponent() = default; SpriteRendererComponent(const SpriteRendererComponent&) = default; SpriteRendererComponent(const Vector4f& color) : Color(color) {} }; struct TextureRendererComponent { Ref<Texture2D> Texture; TextureRendererComponent() = default; TextureRendererComponent(const TextureRendererComponent&) = default; TextureRendererComponent(const Ref<Texture2D>& texture) : Texture(texture) {} }; struct CameraComponent { SceneCamera Camera; bool Primary = false; bool FixedAspectRatio = false; CameraComponent() = default; CameraComponent(const CameraComponent&) = default; }; }
#include<iostream> #include<cmath> using namespace std; int main() { int h,m; float hour,mins,ans; string input; while(1) { input.clear(); cin>>input; if(input=="0:00") break; if(input[2]==':') { h=(input.at(0)-'0')*10+(input.at(1)-'0'); m=(input.at(3)-'0')*10+(input.at(4)-'0'); } else { h=(input.at(0)-'0'); m=(input.at(2)-'0')*10+(input.at(3)-'0'); } hour=(float)h*30+m*0.5; mins=((float)m*6); ans=hour-mins; ans=ans<0?(-1*ans):ans; if(ans>180) ans=360-ans; cout.setf(ios::fixed,ios::floatfield); cout.precision(3); cout <<ans<< endl; } return 0; }
#pragma once #include "Vector3.h" class Bullet { public: Bullet(); ~Bullet(); void Update(double dt); void SetPosition(Vector3 pos,Vector3 dist); void SetTarget(Vector3 pos); Vector3 GetPosition(); Vector3 gravity; Vector3 pos; Vector3 vel; Vector3 target; private: float positiontill; Vector3 direction; };
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); brush = new QBrush; palette = new QPalette; brush->setTextureImage(QImage(":/textures/BackgroundMenu.jpg")); palette->setBrush(QPalette::Window, *brush); this->setPalette(*palette); this->setWindowFlags(Qt::FramelessWindowHint); this->setFixedSize(400,300); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_actionAuthor_triggered() { QMessageBox::information(NULL,QObject::tr("Author"),tr("Pokatilo Pavel, SPBSTU: group 13501/4")); } //запуск игры с игроком void MainWindow::on_menupvp_clicked() { player *player1=new player(name1); player *player2=new player(name2); BOT *bot = new BOT(0,player1,true,player2); bot->setWindowFlags(Qt::FramelessWindowHint); bot->show(); } //запуск игры с ботом void MainWindow::on_menubot_clicked() { player *player1=new player(name1); BOT *bot = new BOT(0,player1,false); bot->setWindowFlags(Qt::FramelessWindowHint); bot->show(); } void MainWindow::on_actionMain_player_triggered() { bool check; name1=QInputDialog::getText(0,"Change name","Enter new name",QLineEdit::Normal,name1,&check); } void MainWindow::on_actionSecond_player_triggered() { bool check; name2=QInputDialog::getText(0,"Change name","Enter new name",QLineEdit::Normal,name2,&check); } void MainWindow::on_pushButton_clicked() { MainWindow::close(); }
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QDirModel> #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); //setup tree file view and bind to data model model = new QFileSystemModel(); model->setRootPath("C:"); //model->setFilter( QDir::NoDotAndDotDot | QDir::Files ) ; proxy = new QSortFilterProxyModel(); proxy->setDynamicSortFilter(true); proxy->setSourceModel(model); proxy->setFilterKeyColumn(0); ui->treeView->setModel(model); ui->treeView->resizeColumnToContents(0); connect(ui->Add, SIGNAL(clicked()),this,SLOT(AddFolder())); connect(ui->Delete,SIGNAL(clicked()),this,SLOT(DeleteFolder())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::AddFolder() { qDebug()<<"System Initiated"; QModelIndex indexes = ui->treeView->currentIndex(); QString FilePath = ui->FilePath->text(); model->mkdir(indexes,FilePath); ui->FilePath->text().clear(); } void MainWindow::DeleteFolder() { qDebug()<<"..............."; QModelIndex indexes = ui->treeView->currentIndex(); model->remove(indexes); }
/* * @lc app=leetcode.cn id=5 lang=cpp * * [5] 最长回文子串 */ // @lc code=start #include<iostream> #include<string> #include<vector> #include<algorithm> using namespace std; class Solution { public: string palindrome(string& s, int l, int r){ while(l>=0 && r<s.size() && s[l]==s[r]){ l--; r++; } return s.substr(l+1, r-l-1); } string longestPalindrome(string s) { int n = s.size(); if(n<2)return s; string res; for(int i=0;i<s.size();i++){ string s1 = palindrome(s, i, i); string s2 = palindrome(s, i, i+1); res = res.size() > s1.size() ? res : s1; res = res.size() > s2.size() ? res : s2; } return res; } // string longestPalindrome(string s) { // int n = s.size(); // if(n<2)return s; // vector<vector<int> > dp(n, vector<int>(n, 0)); // int maxLen = 1; // int begin = 0; // for(int j=1;j<n;++j) // { // for(int i=0;i<j;i++) // { // if(s[i]!=s[j]) // { // dp[i][j] = 0; // }else{ // if(j-i<3){ // dp[i][j] = 1; // }else{ // dp[i][j] = dp[i+1][j-1]; // } // } // if(dp[i][j]&&j-i+1>maxLen) // { // maxLen = j-i+1; // begin = i; // } // } // } // return s.substr(begin, maxLen); // } }; // @lc code=end
#include<bits/stdc++.h> using namespace std; /* BFS-Breadth first search -> You start with a given/source node and then you will reach to its neighbours -> Its similar to level order traversal in trees NOTE: Distance travelled by the level order is the shortest distance. (if the graph is the unwaited graph that means all edges have the same cost) if weighted graph then Dijkstra's Algorithm */ template<typename T> class Graph{ map<T,list<T>>l; public: void addEdge(int x,int y){ l[x].push_back(y); l[y].push_back(x); } void bfs(T src){//src node to traversal map<T,bool>visited;//to maintain the check whether i visited the node before or not queue<T>q;//to store all the neighbours of a given node q.push(src);//push source node first for traversal visited[src]=true;//marked as visited while (!q.empty()) { T node=q.front(); q.pop(); cout<<node<<" "; for(int nbr:l[node]){ if(!visited[nbr]){ q.push(nbr); visited[nbr]=true;//mark the neighbours are now visited } } } } void shortestPath(T src){//src node to traversal map<T,int>dist;//to maintain the distance from the source node queue<T>q;//to store all the neighbours of a given node for(auto node_pair:l){ T node=node_pair.first; dist[node]=INT_MAX;//initialise all the node distance to infinity as we haven't discovered them yet } q.push(src);//push source node first for traversal dist[src]=0;//we take source node distance as 0 while (!q.empty()) { T node=q.front(); q.pop(); // cout<<node<<" "; for(int nbr:l[node]){ if(dist[nbr]==INT_MAX){//that means we are visiting this node for the first time q.push(nbr); dist[nbr]=dist[node]+1;//distance of neighbour is equal to 1 more than the distance of parent } } } //print distance to every node for(auto node_pair:l){ T node=node_pair.first; int d=dist[node]; cout<<"Node "<<node<<" distance from src "<< d <<endl; } } }; int main(){ Graph<int>g;//create object with datatype g.addEdge(0,1); g.addEdge(1,2); g.addEdge(2,3); g.addEdge(3,4); g.addEdge(4,5); // g.bfs(0); g.shortestPath(0); }
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <stdio.h> #include <string.h> #include <time.h> #include <numeric> using namespace std; #define INF (1<<26) class MatrixShiftings { public: int minimumShifts(vector <string> matrix, int value) { int res = INF; int X = (int)matrix[0].size(); int Y = (int)matrix.size(); for (int y=0; y<Y; ++y) { for (int x=0; x<X; ++x) { if (matrix[y][x] != value + '0') { continue; } res = min( res , min(y,Y-y) + min(x,X-x) ); } } return res == INF ? -1 : res; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {"136", "427", "568", "309"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; int Arg2 = 2; verify_case(0, Arg2, minimumShifts(Arg0, Arg1)); } void test_case_1() { string Arr0[] = {"0000", "0000", "0099"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 9; int Arg2 = 2; verify_case(1, Arg2, minimumShifts(Arg0, Arg1)); } void test_case_2() { string Arr0[] = {"0123456789"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 7; int Arg2 = 3; verify_case(2, Arg2, minimumShifts(Arg0, Arg1)); } void test_case_3() { string Arr0[] = {"555", "555"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; int Arg2 = -1; verify_case(3, Arg2, minimumShifts(Arg0, Arg1)); } void test_case_4() { string Arr0[] = {"12417727123", "65125691886", "55524912622", "12261288888"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 9; int Arg2 = 6; verify_case(4, Arg2, minimumShifts(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { MatrixShiftings ___test; ___test.run_test(-1); } // END CUT HERE
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4; c-file-style:"stroustrup" -*- * * Copyright (C) 1995-2012 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #ifdef M2_SUPPORT # include "adjunct/desktop_util/file_chooser/file_chooser_fun.h" # include "adjunct/desktop_util/mail/mailcompose.h" #ifdef IRC_SUPPORT # include "adjunct/m2/src/backend/irc/chat-networks.h" #endif # include "adjunct/m2/src/engine/accountmgr.h" # include "adjunct/m2/src/engine/engine.h" # include "adjunct/m2/src/import/importer.h" # include "adjunct/m2/src/import/AppleMailImporter.h" # include "adjunct/m2/src/import/ImporterModel.h" # include "adjunct/m2/src/import/ImportFactory.h" # include "adjunct/m2/src/util/accountcreator.h" # include "adjunct/m2/src/util/str/strutil.h" # include "adjunct/quick/Application.h" # include "adjunct/m2_ui/dialogs/NewAccountWizard.h" # include "adjunct/quick_toolkit/widgets/OpTreeView/OpTreeView.h" # include "adjunct/quick_toolkit/widgets/OpProgressbar.h" # include "modules/locale/oplanguagemanager.h" # include "modules/prefs/prefsmanager/collections/pc_m2.h" # include "modules/prefs/prefsmanager/prefsmanager.h" # include "modules/util/handy.h" # include "modules/widgets/OpDropDown.h" # include "modules/widgets/OpListBox.h" # include "modules/widgets/OpEdit.h" /*********************************************************************************** ** ** NewAccountWizard ** ***********************************************************************************/ NewAccountWizard::NewAccountWizard() : m_account_creator(NULL) , m_found_provider(FALSE) , m_has_guessed_fields(FALSE) , m_chooser(NULL) , m_mailto_force_background(FALSE) , m_mailto_new_window(FALSE) , m_has_mailto(FALSE) , m_reset_mail_panel(0) { } NewAccountWizard::~NewAccountWizard() { g_m2_engine->RemoveEngineListener(this); OpListBox* listbox = GetWidgetByName<OpListBox>("Account_type_listbox", WIDGET_TYPE_LISTBOX); if (listbox) listbox->SetListener(NULL); OpTreeView* accountTreeView = (OpTreeView*)GetWidgetByName("Import_setimportaccount"); if(accountTreeView) accountTreeView->SetTreeModel(NULL); OP_DELETE(m_importer_object); g_m2_engine->SetImportInProgress(FALSE); OP_DELETE(m_account_creator); OP_DELETE(m_chooser); } void NewAccountWizard::Init(AccountTypes::AccountType type, DesktopWindow* parent_window, const OpStringC& incoming_dropdown_value) { m_init_type = type == AccountTypes::UNDEFINED ? AccountTypes::POP : type; m_type = m_init_type; m_import_type = EngineTypes::NONE; m_importer_object = NULL; m_incoming_dropdown_value.Set(incoming_dropdown_value); g_m2_engine->AddEngineListener(this); m_reset_mail_panel = g_m2_engine->GetAccountManager()->GetMailNewsAccountCount() == 0; Dialog::Init(parent_window, type == AccountTypes::UNDEFINED ? 0 : OnForward(0)); } void NewAccountWizard::SetMailToInfo(const MailTo& mailto, BOOL force_background, BOOL new_window, const OpStringC *attachment) { m_mailto.Init(mailto.GetRawMailTo().CStr()); m_mailto_force_background = force_background; m_mailto_new_window = new_window; if (attachment) { m_mailto_attachment.Set(attachment->CStr()); } m_has_mailto = TRUE; } /*********************************************************************************** ** ** NewAccountWizard ** ***********************************************************************************/ void NewAccountWizard::OnInit() { OpEdit* password = GetWidgetByName<OpEdit>("Password_edit", WIDGET_TYPE_EDIT); if (password) password->SetPasswordMode(TRUE); const char* ltr_text_widgets[] = { "Mail_edit", "Username_edit", "Incoming_edit", "Outgoing_edit", }; for (unsigned i = 0; i < ARRAY_SIZE(ltr_text_widgets); ++i) { OpEdit* edit = GetWidgetByName<OpEdit>(ltr_text_widgets[i], WIDGET_TYPE_EDIT); if (edit) edit->SetForceTextLTR(TRUE); } OpListBox* listbox = GetWidgetByName<OpListBox>("Account_type_listbox", WIDGET_TYPE_LISTBOX); listbox->SetListener(this); OpString loc_str; g_languageManager->GetString(Str::D_NEW_ACCOUNT_EMAIL, loc_str); listbox->AddItem(loc_str.CStr(), -1, NULL, AccountTypes::POP, m_init_type == AccountTypes::POP || m_init_type == AccountTypes::IMAP, "Account POP"); /* g_languageManager->GetString(Str::S_NEW_ACCOUNT_POP, loc_str); listbox->AddItem(loc_str.CStr(), -1, NULL, (void*) AccountTypes::POP, m_init_type == AccountTypes::POP, "Account POP"); g_languageManager->GetString(Str::S_NEW_ACCOUNT_IMAP, loc_str); listbox->AddItem(loc_str.CStr(), -1, NULL, (void*) AccountTypes::IMAP, m_init_type == AccountTypes::IMAP, "Account IMAP"); */ g_languageManager->GetString(Str::S_NEW_ACCOUNT_NEWS, loc_str); listbox->AddItem(loc_str.CStr(), -1, NULL, AccountTypes::NEWS, m_init_type == AccountTypes::NEWS, "Account News"); if (!g_m2_engine->ImportInProgress()) { g_languageManager->GetString(Str::S_NEW_ACCOUNT_IMPORT, loc_str); listbox->AddItem(loc_str.CStr(), -1, NULL, AccountTypes::IMPORT, m_init_type == AccountTypes::IMPORT, "Account Import"); } #ifdef OPERAMAIL_SUPPORT g_languageManager->GetString(Str::S_NEW_ACCOUNT_OPERAMAIL, loc_str); listbox->AddItem(loc_str.CStr(), -1, NULL, AccountTypes::WEB, m_init_type == AccountTypes::WEB, "Account Operamail"); #endif // OPERAMAIL_SUPPORT #ifdef IRC_SUPPORT g_languageManager->GetString(Str::S_NEW_ACCOUNT_CHAT_IRC, loc_str); listbox->AddItem(loc_str.CStr(), -1, NULL, AccountTypes::IRC, m_init_type == AccountTypes::IRC, "Account IRC"); #endif #ifdef JABBER_SUPPORT listbox->AddItem(UNI_L("Chat (JABBER)"), -1, NULL, AccountTypes::JABBER, m_init_type == AccountTypes::JABBER, "Account IRC"); #endif //JABBER_SUPPORT listbox = GetWidgetByName<OpListBox>("Import_type_listbox", WIDGET_TYPE_LISTBOX); INT32 opera_index = -1; INT32 eudora_index = -1; INT32 netscape_index = -1; #ifdef MSWIN INT32 oe_index = -1; #endif INT32 mbox_index = -1; #ifdef _MACINTOSH_ INT32 apple_index = -1; #endif INT32 thunderbird_index = -1; INT32 opera7_index = -1; g_languageManager->GetString(Str::S_IMPORT_FROM_MBOX, loc_str); listbox->AddItem(loc_str.CStr(), -1, &mbox_index, EngineTypes::MBOX); g_languageManager->GetString(Str::S_IMPORT_FROM_OPERA7, loc_str); listbox->AddItem(loc_str.CStr(), -1, &opera7_index, EngineTypes::OPERA7); g_languageManager->GetString(Str::S_IMPORT_FROM_OPERA6, loc_str); listbox->AddItem(loc_str.CStr(), -1, &opera_index, EngineTypes::OPERA, TRUE); g_languageManager->GetString(Str::S_IMPORT_FROM_EUDORA, loc_str); listbox->AddItem(loc_str.CStr(), -1, &eudora_index, EngineTypes::EUDORA); g_languageManager->GetString(Str::S_IMPORT_FROM_NETSCAPE6, loc_str); listbox->AddItem(loc_str.CStr(), -1, &netscape_index, EngineTypes::NETSCAPE); g_languageManager->GetString(Str::S_IMPORT_FROM_THUNDERBIRD, loc_str); listbox->AddItem(loc_str.CStr(), -1, &thunderbird_index, EngineTypes::THUNDERBIRD); #ifdef _MACINTOSH_ g_languageManager->GetString(Str::S_IMPORT_FROM_APPLE_MAIL_NEW, loc_str); listbox->AddItem(loc_str.CStr(), -1, &apple_index, EngineTypes::APPLE); #endif #ifdef MSWIN g_languageManager->GetString(Str::S_IMPORT_FROM_OE, loc_str); listbox->AddItem(loc_str.CStr(), -1, &oe_index, EngineTypes::OE); #endif g_m2_engine->SetImportInProgress(TRUE); m_import_type = g_m2_engine->GetDefaultImporterId(); switch (m_import_type) { case EngineTypes::OPERA: listbox->SelectItem(opera_index, TRUE); break; case EngineTypes::EUDORA: listbox->SelectItem(eudora_index, TRUE); break; #ifdef MSWIN case EngineTypes::OE: listbox->SelectItem(oe_index, TRUE); break; #endif//MSWIN case EngineTypes::NETSCAPE: listbox->SelectItem(netscape_index, TRUE); break; case EngineTypes::MBOX: listbox->SelectItem(mbox_index, TRUE); break; case EngineTypes::THUNDERBIRD: listbox->SelectItem(thunderbird_index, TRUE); break; case EngineTypes::OPERA7: listbox->SelectItem(opera7_index, TRUE); break; #ifdef _MACINTOSH_ case EngineTypes::APPLE: listbox->SelectItem(apple_index, TRUE); break; #endif // _MACINTOSH_ } //Populate the 'import into' dropdown OpDropDown* import_into = (OpDropDown*)GetWidgetByName("Import_intoaccount_dropdown"); if (import_into) { OpString intoaccount; g_languageManager->GetString(Str::D_IMPORT_MAIL_INTO, intoaccount); import_into->AddItem(intoaccount.CStr(), -1, NULL); AccountManager* account_manager = g_m2_engine->GetAccountManager(); Account* account; int i; for (i=0; account_manager && i<account_manager->GetAccountCount(); i++) { account = account_manager->GetAccountByIndex(i); if (account) { AccountTypes::AccountType type = account->GetIncomingProtocol(); if ((type>AccountTypes::_FIRST_MAIL && type<AccountTypes::_LAST_MAIL && type!=AccountTypes::IMAP) || (type>AccountTypes::_FIRST_NEWS && type<AccountTypes::_LAST_NEWS) || type==AccountTypes::IMPORT) { if (account->GetAccountName().HasContent()) { import_into->AddItem(account->GetAccountName().CStr(), -1, NULL, account->GetAccountId()); } } } } } SetWidgetValue("Leave_on_server_checkbox", TRUE); SetWidgetValue("Delete_permanently_checkbox",TRUE); OpDropDown* incoming_dropdown = (OpDropDown*) GetWidgetByName("Incoming_dropdown"); if (incoming_dropdown) { incoming_dropdown->SetEditableText(TRUE); if (m_incoming_dropdown_value.HasContent()) { // Only insert the user provided value. incoming_dropdown->AddItem(m_incoming_dropdown_value.CStr()); } #ifdef IRC_SUPPORT else { ChatNetworkManager* chat_networks = MessageEngine::GetInstance()->GetChatNetworks(); if (chat_networks != 0) { // Add all default servers. OpAutoVector<OpString> network_names; chat_networks->IRCNetworkNames(network_names); for (UINT32 index = 0, network_count = network_names.GetCount(); index < network_count; ++index) { OpString* network_name = network_names.Get(index); OP_ASSERT(network_name != 0); incoming_dropdown->AddItem(network_name->CStr()); } } } #endif // IRC_SUPPORT incoming_dropdown->SelectItemAndInvoke(0, TRUE, FALSE); } } /*********************************************************************************** ** ** GuessFields ** ***********************************************************************************/ void NewAccountWizard::GuessFields(BOOL guess_userconfig) { BOOL mail = m_type>AccountTypes::_FIRST_MAIL && m_type<AccountTypes::_LAST_MAIL; BOOL news = m_type>AccountTypes::_FIRST_NEWS && m_type<AccountTypes::_LAST_NEWS; if (mail || news) { // Make sure the account creator exists and is ready to go if (!m_account_creator) { m_account_creator = OP_NEW(AccountCreator, ()); if (!m_account_creator || OpStatus::IsError(m_account_creator->Init())) return; } // See if we can get server information with the provided email address OpString mail_address, username; AccountCreator::Server incoming_server; AccountTypes::AccountType protocol = news ? AccountTypes::NEWS : AccountTypes::UNDEFINED; if (guess_userconfig) protocol = news ? AccountTypes::NEWS : AccountTypes::UNDEFINED; else protocol = m_type; GetWidgetText("Mail_edit", mail_address); m_found_provider = OpStatus::IsSuccess(m_account_creator->GetServer(mail_address, protocol, TRUE, incoming_server)); if (!m_found_provider) { // No provider - get some usable default values RETURN_VOID_IF_ERROR(m_account_creator->GetServerDefaults(mail_address, protocol, incoming_server)); } else { // Fill in preferred protocol m_type = incoming_server.GetProtocol(); } // We have a server - fill in values if (guess_userconfig) SetWidgetText("Username_edit", incoming_server.GetUsername().CStr()); SetWidgetText("Incoming_edit", incoming_server.GetHostname().CStr()); SetWidgetText("Outgoing_edit", incoming_server.GetHostname().CStr()); SetWidgetValue("Leave_on_server_checkbox", incoming_server.GetPopLeaveMessages()); SetWidgetValue("Delete_permanently_checkbox",incoming_server.GetPopDeletePermanently()); SetWidgetValue("Incoming_secure_checkbox", incoming_server.GetSecure()); SetWidgetValue("Outgoing_secure_checkbox", incoming_server.GetSecure()); m_has_guessed_fields = TRUE; } } /*********************************************************************************** ** ** InitImportFields ** ***********************************************************************************/ void NewAccountWizard::InitImportFields(BOOL all) { if (EngineTypes::NONE == m_import_type) { return; } OpTreeView* accountTreeView = (OpTreeView*) GetWidgetByName("Import_setimportaccount"); accountTreeView->SetTreeModel(NULL); EnableForwardButton(FALSE); if (all) { OP_DELETE(m_importer_object); m_importer_object = NULL; RETURN_VOID_IF_ERROR(ImportFactory::Instance()->Create(m_import_type, &m_importer_object)); if (m_import_path.IsEmpty()) { m_importer_object->GetLastUsedImportFolder(m_import_type, m_import_path); if (m_import_path.IsEmpty()) m_importer_object->GetDefaultImportFolder(m_import_path); } accountTreeView->SetMultiselectable(FALSE); SetWidgetEnabled("Import_contacts_check", TRUE); SetWidgetEnabled("Import_settings_check", TRUE); SetWidgetEnabled("Import_messages_check", TRUE); SetWidgetValue("Import_settings_check", TRUE); SetWidgetValue("Import_contacts_check", FALSE); SetWidgetValue("Import_messages_check", TRUE); ShowWidget("Import_contacts_check", FALSE); ShowWidget("label_for_Account_path_browse", TRUE); ShowWidget("Account_path_browse", TRUE); ShowWidget("Account_path_dir_browse", FALSE); SetWidgetEnabled("Move_to_sent_dropdown", (EngineTypes::OPERA != m_import_type && EngineTypes::EUDORA != m_import_type)); OpString loc_str; switch (m_import_type) { case EngineTypes::NETSCAPE: g_languageManager->GetString(Str::S_IMPORT_NETSCAPE_PREFS_FILE, loc_str); SetWidgetText("label_for_Account_path_browse", loc_str.CStr()); g_languageManager->GetString(Str::D_BROWSE, loc_str); SetWidgetText("Account_path_browse", loc_str.CStr()); break; case EngineTypes::THUNDERBIRD: g_languageManager->GetString(Str::S_IMPORT_THUNDERBIRD_PREFS_FILE, loc_str); SetWidgetText("label_for_Account_path_browse", loc_str.CStr()); g_languageManager->GetString(Str::D_BROWSE, loc_str); SetWidgetText("Account_path_browse", loc_str.CStr()); break; case EngineTypes::MBOX: #if defined (DESKTOP_FILECHOOSER_DIRFILE) g_languageManager->GetString(Str::D_MBOX_IMPORT_FOLDER_AND_FILE_ADD, loc_str); SetWidgetText("Account_path_browse", loc_str.CStr()); #else // !DESKTOP_FILECHOOSER_DIRFILE ShowWidget("Account_path_dir_browse", TRUE); g_languageManager->GetString(Str::D_MBOX_IMPORT_FILE_ADD, loc_str); SetWidgetText("Account_path_browse", loc_str.CStr()); g_languageManager->GetString(Str::D_MBOX_IMPORT_FOLDER_ADD, loc_str); SetWidgetText("Account_path_dir_browse", loc_str.CStr()); #endif // !DESKTOP_FILECHOOSER_DIRFILE SetWidgetValue("Import_contacts_check", FALSE); SetWidgetValue("Import_settings_check", FALSE); SetWidgetEnabled("Import_contacts_check", FALSE); SetWidgetEnabled("Import_settings_check", FALSE); SetWidgetEnabled("Import_messages_check", FALSE); accountTreeView->SetMultiselectable(TRUE); g_languageManager->GetString(Str::S_IMPORT_GENERIC_MBOX_FILE, loc_str); SetWidgetText("label_for_Account_path_browse", loc_str.CStr()); break; #ifdef _MACINTOSH_ case EngineTypes::APPLE: g_languageManager->GetString(Str::D_BROWSE, loc_str); SetWidgetText("Account_path_browse", loc_str.CStr()); accountTreeView->SetMultiselectable(TRUE); g_languageManager->GetString(Str::S_IMPORT_GENERIC_MBOX_FILE, loc_str); SetWidgetText("label_for_Account_path_browse", loc_str.CStr()); break; #endif #ifdef MSWIN case EngineTypes::OE: g_languageManager->GetString(Str::S_IMPORT_FROM_OE, loc_str); SetWidgetText("label_for_Account_path_browse",loc_str.CStr()); ShowWidget("Account_path_browse", FALSE); break; #endif case EngineTypes::OPERA7: accountTreeView->SetMultiselectable(TRUE); g_languageManager->GetString(Str::S_IMPORT_OPERA7_ACCOUNT_INI, loc_str); SetWidgetText("label_for_Account_path_browse", loc_str.CStr()); g_languageManager->GetString(Str::D_BROWSE, loc_str); SetWidgetText("Account_path_browse", loc_str.CStr()); break; default: g_languageManager->GetString(Str::S_IMPORT_MAILBOX_FOLDER, loc_str); SetWidgetText("label_for_Account_path_browse", loc_str.CStr()); g_languageManager->GetString(Str::D_BROWSE, loc_str); SetWidgetText("Account_path_browse", loc_str.CStr()); break; } } OP_STATUS res = m_importer_object->Init(); accountTreeView->SetTreeModel(m_importer_object->GetModel()); accountTreeView->SetShowThreadImage(TRUE); OpDropDown* move_to_sent = (OpDropDown*)GetWidgetByName("Move_to_sent_dropdown"); if (move_to_sent) move_to_sent->Clear(); if (OpStatus::IsSuccess(res)) { if (m_importer_object->GetModel()->GetItemCount() > 0) { if (EngineTypes::MBOX == m_import_type || EngineTypes::APPLE == m_import_type || EngineTypes::OPERA7 == m_import_type) // select all { accountTreeView->SelectAllItems(); } else { accountTreeView->SetSelectedItem(0); } PopulateMoveToSent(accountTreeView); EnableForwardButton(TRUE); } } OpEdit* account_path = static_cast<OpEdit*>(GetWidgetByName("Account_path")); if (account_path) account_path->SetText(m_import_path.CStr()); } /*********************************************************************************** ** ** PopulateMoveToSent ** ***********************************************************************************/ void NewAccountWizard::PopulateMoveToSent(OpTreeView* accountTreeView) { OpDropDown* move_to_sent = (OpDropDown*)GetWidgetByName("Move_to_sent_dropdown"); if (move_to_sent) { OpString str_none; g_languageManager->GetString(Str::S_IMPORT_WIZARD_NONE, str_none); move_to_sent->Clear(); move_to_sent->AddItem(str_none.CStr(), -1, NULL); OpINT32Vector items; INT32 count_items = accountTreeView->GetSelectedItems(items, FALSE); for (int i = 0; i < count_items; i++) { ImporterModelItem* parent_item = (ImporterModelItem*)accountTreeView->GetItemByPosition(items.Get(i)); if (!parent_item) break; OpQueue<ImporterModelItem>* sequence = OP_NEW(OpQueue<ImporterModelItem>, ()); if (!sequence) return; if (OpStatus::IsError(m_importer_object->GetModel()->MakeSequence(sequence, parent_item))) { OP_DELETE(sequence); return; } ImporterModelItem* item = NULL; do { item = m_importer_object->GetModel()->PullItem(sequence); if (item && item->GetType() == IMPORT_MAILBOX_TYPE) { move_to_sent->AddItem(item->GetName().CStr(), -1, NULL, reinterpret_cast<INTPTR>(item)); } } while (item); OP_DELETE(sequence); } } } /*********************************************************************************** ** ** OnFileChoosingDone ** ***********************************************************************************/ void NewAccountWizard::OnFileChoosingDone(DesktopFileChooser* chooser, const DesktopFileChooserResult& result) { if (result.files.GetCount()) { m_import_path.Set(result.active_directory); m_importer_object->SetLastUsedImportFolder(m_import_type, m_import_path); if (m_import_type == EngineTypes::NETSCAPE || m_import_type == EngineTypes::THUNDERBIRD || m_import_type == EngineTypes::EUDORA || m_import_type == EngineTypes::OPERA || m_import_type == EngineTypes::OPERA7) m_importer_object->AddImportFile(*result.files.Get(0)); else m_importer_object->AddImportFileList(&result.files); InitImportFields(FALSE); } } /*********************************************************************************** ** ** OnInitPage ** ***********************************************************************************/ void NewAccountWizard::OnInitPage(INT32 page_number, BOOL first_time) { const BOOL chat = m_type > AccountTypes::_FIRST_CHAT && m_type < AccountTypes::_LAST_CHAT; const BOOL mail = m_type > AccountTypes::_FIRST_MAIL && m_type < AccountTypes::_LAST_MAIL; const BOOL news = m_type > AccountTypes::_FIRST_NEWS && m_type < AccountTypes::_LAST_NEWS; const BOOL imap = m_type == AccountTypes::IMAP; const BOOL msn = m_type == AccountTypes::MSN; #ifdef JABBER_SUPPORT const BOOL jabber = m_type==AccountTypes::JABBER; #endif // JABBER_SUPPORT EnableForwardButton(TRUE); switch (page_number) { case 1: { #ifdef JABBER_SUPPORT if (jabber) { ShowWidget("label_for_Name_edit", FALSE); ShowWidget("Name_edit", FALSE); SetWidgetText("label_for_Mail_edit", UNI_L("Jabber ID")); ShowWidget("label_for_Mail_edit", TRUE); ShowWidget("Mail_edit", TRUE); ShowWidget("label_for_Organization_edit", FALSE); ShowWidget("Organization_edit", FALSE); break; } #endif // JABBER_SUPPORT ShowWidget("label_for_Organization_edit", !chat); ShowWidget("Organization_edit", !chat); ShowWidget("Outgoing_secure_checkbox",!chat); ShowWidget("label_for_Name_edit", !msn); ShowWidget("Name_edit", !msn); if (msn) break; AccountManager* manager = g_m2_engine->GetAccountManager(); Account* account = NULL; Account* chat_account = NULL; OpString string; manager->GetAccountById(manager->GetDefaultAccountId(AccountTypes::TYPE_CATEGORY_MAIL), account); if (chat) { manager->GetAccountById(manager->GetDefaultAccountId(AccountTypes::TYPE_CATEGORY_CHAT), chat_account); } if (chat_account) account = chat_account; if (account) { account->GetRealname(string); SetWidgetText("Name_edit", string.CStr()); if (!mail) { account->GetEmail(string); SetWidgetText("Mail_edit", string.CStr()); } account->GetOrganization(string); SetWidgetText("Organization_edit", string.CStr()); } if (chat_account) { OpString8 string8; chat_account->GetIncomingUsername(string8); SetWidgetText("Username_edit", string8.CStr()); } if (mail) { OpString text; GetWidgetText("Mail_edit", text); EnableForwardButton(text.HasContent()); } } break; case 2: { // Hide the warning initially, and turn the text red. OpLabel * illegal_nick_label = (OpLabel*) GetWidgetByName("label_for_nick_warning"); if (illegal_nick_label) { illegal_nick_label->SetForegroundColor(OP_RGB(255, 0, 0)); illegal_nick_label->SetVisibility(FALSE); } if (chat) { OpString nick_name; GetWidgetText("Username_edit",nick_name); OpString8 nick8; nick8.Set(nick_name.CStr()); ShowWidget("label_for_nick_warning",!!nick_name.Compare(nick8)); EnableForwardButton(!nick_name.Compare(nick8)); } if (!m_has_guessed_fields) GuessFields(); if (msn) { ShowWidget("label_for_Username_edit", FALSE); ShowWidget("Username_edit", FALSE); break; } #ifdef JABBER_SUPPORT if (jabber) { SetWidgetText("label_for_Username_edit", UNI_L("Username")); break; } #endif // JABBER_SUPPORT if(!mail) { ShowWidget("Email_account_type_label", FALSE); ShowWidget("POP_account_radio", FALSE); ShowWidget("IMAP_account_radio", FALSE); } else { if (first_time && !m_found_provider) m_type = m_init_type; SetWidgetValue("POP_account_radio", m_type == AccountTypes::POP); SetWidgetValue("IMAP_account_radio", m_type == AccountTypes::IMAP); } OpString label; g_languageManager->GetString(!chat ? Str::LocaleString(Str::DI_IDSTR_M2_NEWACC_WIZ_LOGIN) : Str::LocaleString(Str::DI_IDSTR_M2_NEWACC_WIZ_NICK), label); SetWidgetText("label_for_Username_edit", label.CStr()); ShowWidget("label_for_Password_edit", !chat); ShowWidget("Password_edit", !chat); break; } case 3: { OpString label; g_languageManager->GetString(!chat ? Str::LocaleString(Str::DI_IDSTR_M2_NEWACC_WIZ_INCOMING_SERVER) : Str::LocaleString(Str::DI_IDSTR_M2_NEWACC_WIZ_IRC_SERVER), label); SetWidgetText("label_for_Incoming_edit", label.CStr()); ShowWidget("Incoming_secure_checkbox", !news && !chat); //M2 doesn't support snews yet ShowWidget("Incoming_edit", !chat); ShowWidget("Incoming_dropdown", chat); ShowWidget("label_for_Outgoing_edit", !chat); ShowWidget("Outgoing_edit", !chat); ShowWidget("Leave_on_server_checkbox", !(imap || news || chat)); ShowWidget("Delete_permanently_checkbox",!(imap || news || chat)); #ifdef JABBER_SUPPORT if (jabber) { SetWidgetText("label_for_Incoming_edit", UNI_L("Jabber server")); ShowWidget("label_for_Incoming_edit"); ShowWidget("Incoming_edit"); ShowWidget("Incoming_dropdown", FALSE); // undo what is done above break; } #endif // JABBER_SUPPORT } break; case 4: // Import break; case 5: // Import prefs { m_import_path.Empty(); InitImportFields(TRUE); OpString start_text; g_languageManager->GetString(Str::D_START_IMPORT_BUTTON, start_text); SetForwardButtonText(start_text); } break; case 6: // Import progress DoMailImport(); break; } } BOOL NewAccountWizard::IsLastPage(INT32 page_number) { // Normal account wizard has 3 pages, or 2 if it's a known provider int last_page = m_found_provider ? 2 : 3; // Some special cases switch (m_type) { case AccountTypes::IMPORT: last_page = 6; break; #ifdef OPERAMAIL_SUPPORT case AccountTypes::WEB: last_page = 0; break; #endif // OPERAMAIL_SUPPORT case AccountTypes::MSN: last_page = 2; break; } return page_number >= last_page; } UINT32 NewAccountWizard::OnForward(UINT32 page_number) { if (m_type == AccountTypes::IMPORT) { if (page_number == 0) return 4; } if (m_type == AccountTypes::NEWS && page_number == 1) return 3; #ifdef JABBER_SUPPORT if (m_type == AccountTypes::JABBER) return page_number + 1; #endif // JABBER_SUPPORT if (m_type > AccountTypes::MSN && m_type < AccountTypes::IMPORT) return 7; return page_number + 1; } UINT32 NewAccountWizard::OnOk() { // Some special cases that can be handled quickly switch (m_type) { #ifdef OPERAMAIL_SUPPORT case AccountTypes::WEB: if (g_pcm2->GetStringPref(PrefsCollectionM2::WebmailAddress).HasContent()) g_application->GoToPage(g_pcm2->GetStringPref(PrefsCollectionM2::WebmailAddress).CStr()); return 0; #endif // OPERAMAIL_SUPPORT case AccountTypes::IMPORT: UpdateUIAfterAccountCreation(); return 0; } AccountCreator::Server incoming_server, outgoing_server; OpString name, email_address, organization, username, password, account_name; AccountTypes::AccountType outgoing_type = Account::GetOutgoingForIncoming(m_type); // Get necessary information GetWidgetText("Name_edit", name); GetWidgetText("Mail_edit", email_address); GetWidgetText("Organization_edit", organization); GetWidgetText("Username_edit", username); GetWidgetText("Password_edit", password); // Account name set to email address by default; might be changed by GetServerInfo() later account_name.Set(email_address); // If this is a known provider, get server data directly; else, fill in if (m_found_provider) { m_account_creator->GetServer(email_address, m_type, TRUE, incoming_server); m_account_creator->GetServer(email_address, outgoing_type, FALSE, outgoing_server); } else { // Get necessary information OpString incoming_host_total, incoming_host, outgoing_host_total, outgoing_host; unsigned incoming_port, outgoing_port; BOOL leave_messages, incoming_secure, outgoing_secure; GetServerInfo(TRUE, incoming_host, incoming_port, account_name); GetServerInfo(FALSE, outgoing_host, outgoing_port, account_name); leave_messages = GetWidgetValue("Leave_on_server_checkbox"); incoming_secure = GetWidgetValue("Incoming_secure_checkbox"); outgoing_secure = GetWidgetValue("Outgoing_secure_checkbox"); // Set incoming server information incoming_server.Init(m_type); incoming_server.SetHost(incoming_host); incoming_server.SetPort(incoming_port); incoming_server.SetSecure(incoming_secure); incoming_server.SetPopLeaveMessages(leave_messages); incoming_server.SetPopDeletePermanently(GetWidgetValue("Delete_permanently_checkbox")); // Set outgoing server information outgoing_server.Init(outgoing_type); outgoing_server.SetHost(outgoing_host); outgoing_server.SetPort(outgoing_port); outgoing_server.SetSecure(outgoing_secure); } // Set the name of the account to the server name for NNTP - fix for bug #296144 if(m_type == AccountTypes::NEWS) account_name.Set(incoming_server.GetHostname()); // Username should always be what the user typed in the username field, we guessed, but user knows best // fix for bug DSK-209183 incoming_server.SetUsername(username); incoming_server.SetPassword(password); outgoing_server.SetUsername(username); outgoing_server.SetPassword(password); // Now create the account Account* account; if (OpStatus::IsSuccess(m_account_creator->CreateAccount(name, email_address, organization, account_name, incoming_server, outgoing_server, g_m2_engine, account))) { // Show a group subscription dialog if necessary if ((m_type == AccountTypes::NEWS || m_type == AccountTypes::IRC) && (!GetParentDesktopWindow() || GetParentDesktopWindow()->GetType() != DIALOG_TYPE_ACCOUNT_SUBSCRIPTION)) g_application->SubscribeAccount(m_type, NULL, account->GetAccountId(), GetParentDesktopWindow()); // Update UI with new account UpdateUIAfterAccountCreation(); } if (m_has_mailto && (m_type == AccountTypes::IMAP || m_type == AccountTypes::POP)) MailCompose::InternalComposeMail(m_mailto, MAILHANDLER_OPERA, 0, m_mailto_force_background, m_mailto_new_window, m_mailto_attachment.HasContent() ? &m_mailto_attachment : NULL); return 0; } void NewAccountWizard::UpdateUIAfterAccountCreation() { g_application->SettingsChanged(SETTINGS_ACCOUNT_SELECTOR); g_application->SettingsChanged(SETTINGS_MENU_SETUP); g_application->SettingsChanged(SETTINGS_TOOLBAR_SETUP); g_application->SyncSettings(); g_input_manager->InvokeAction(OpInputAction::ACTION_SHOW_PANEL, 0, UNI_L("Contacts"), g_application->GetActiveDesktopWindow()); OpInputAction::Action action = OpInputAction::ACTION_FOCUS_PANEL; OpWindow* parent = GetParentWindow(); if(parent && parent->GetStyle() == OpWindow::STYLE_MODAL_DIALOG) { action = OpInputAction::ACTION_SHOW_PANEL; } switch (m_type) { case AccountTypes::NEWS: case AccountTypes::IMAP: case AccountTypes::POP: case AccountTypes::IMPORT: g_input_manager->InvokeAction(action, 0, UNI_L("Mail"), g_application->GetActiveDesktopWindow()); // if it's the first mail/news account, then we need to add the default categories if ( m_reset_mail_panel ) g_input_manager->InvokeAction(OpInputAction::ACTION_RESET_MAIL_PANEL); break; case AccountTypes::IRC: g_input_manager->InvokeAction(action, 0, UNI_L("Chat"), g_application->GetActiveDesktopWindow()); break; } } void NewAccountWizard::OnCancel() { if (AccountTypes::IMPORT == m_type && m_importer_object) { m_importer_object->CancelImport(); } if ( m_reset_mail_panel && g_m2_engine->GetAccountManager()->GetMailNewsAccountCount() != 0) { UpdateUIAfterAccountCreation(); } Dialog::OnCancel(); } void NewAccountWizard::OnChange(OpWidget *widget, BOOL changed_by_mouse) { if (widget->IsNamed("Account_type_listbox")) { m_type = (AccountTypes::AccountType) (INTPTR) ((OpListBox*)widget)->GetItemUserData(((OpListBox*)widget)->GetSelectedItem()); return; } else if (widget->IsNamed("POP_account_radio") && widget->GetValue()) { m_type = AccountTypes::POP; GuessFields(FALSE); } else if (widget->IsNamed("IMAP_account_radio") && widget->GetValue()) { m_type = AccountTypes::IMAP; GuessFields(FALSE); } else if (widget->IsNamed("Import_type_listbox")) { OpListBox* listbox = (OpListBox*)GetWidgetByName("Import_type_listbox"); INT32 selection = listbox->GetSelectedItem(); if (selection > -1 && listbox->IsEnabled(selection)) { m_import_type = (EngineTypes::ImporterId)(INTPTR)listbox->GetItemUserData(selection); EnableForwardButton(TRUE); } else { m_import_type = EngineTypes::NONE; EnableForwardButton(FALSE); } return; } else if (widget->IsNamed("Import_intoaccount_dropdown")) { OpDropDown* import_into = (OpDropDown*)widget; UINT16 account_id = (UINT16)((UINTPTR)import_into->GetItemUserData(import_into->GetSelectedItem())); SetWidgetEnabled("Import_settings_check", m_import_type!=EngineTypes::MBOX && account_id==0); SetWidgetValue("Import_settings_check", m_import_type!=EngineTypes::MBOX && account_id==0); } else if (widget->IsNamed("Import_setimportaccount")) { PopulateMoveToSent((OpTreeView*)widget); } else if (widget->IsNamed("Mail_edit")) { OpString text; widget->GetText(text); EnableForwardButton(text.HasContent()); } else if(widget->IsNamed("Username_edit") && m_type == AccountTypes::IRC) { // If there is wide characters in the nick, then show error and disable forward button OpString nick_name; widget->GetText(nick_name); OpString8 nick8; nick8.Set(nick_name.CStr()); ShowWidget("label_for_nick_warning",!!nick_name.Compare(nick8)); EnableForwardButton(!nick_name.Compare(nick8)); } else if (widget->IsNamed("Leave_on_server_checkbox")) { SetWidgetEnabled("Delete_permanently_checkbox",widget->GetValue()); } // If there are no more pages then show the Finish button if (IsLastPage(GetCurrentPage())) { OpString finish_text; g_languageManager->GetString(Str::S_WIZARD_FINISH, finish_text); SetForwardButtonText(finish_text); } else { OpString next_text; g_languageManager->GetString(Str::S_WIZARD_NEXT_PAGE, next_text); SetForwardButtonText(next_text); } Dialog::OnChange(widget, changed_by_mouse); } void NewAccountWizard::OnClick(OpWidget *widget, UINT32 id) { if ( (widget->IsNamed("Account_path_browse") || widget->IsNamed("Account_path_dir_browse")) && m_importer_object) { if (!m_chooser) RETURN_VOID_IF_ERROR(DesktopFileChooser::Create(&m_chooser)); if (m_import_path.HasContent()) m_request.initial_path.Set(m_import_path); else { OpString tmp_storage; m_request.initial_path.Set(g_folder_manager->GetFolderPathIgnoreErrors(OPFILE_OPEN_FOLDER, tmp_storage)); }; Str::LocaleString caption_str(Str::NOT_A_STRING); Str::LocaleString filter_str(Str::NOT_A_STRING); m_request.action = DesktopFileChooserRequest::ACTION_FILE_OPEN; switch (m_import_type) { case EngineTypes::NETSCAPE: filter_str = Str::S_IMPORT_NETSCAPE_FILTER; caption_str = Str::D_SELECT_NETSCAPE_JS_TO_IMPORT; break; case EngineTypes::THUNDERBIRD: filter_str = Str::S_IMPORT_THUNDERBIRD_FILTER; caption_str = Str::D_SELECT_THUNDERBIRD_JS_TO_IMPORT; break; case EngineTypes::MBOX: #if defined (DESKTOP_FILECHOOSER_DIRFILE) m_request.action = DesktopFileChooserRequest::ACTION_DIR_FILE_OPEN_MULTI; filter_str = Str::S_IMPORT_MBOX_FILTER; caption_str = Str::D_SELECT_FILES_AND_DIRS_TO_IMPORT; #else if (widget->IsNamed("Account_path_browse")) { m_request.action = DesktopFileChooserRequest::ACTION_FILE_OPEN_MULTI; filter_str = Str::S_IMPORT_MBOX_FILTER; caption_str = Str::D_SELECT_FILES_TO_IMPORT; } else // Account_path_dir_browse { m_request.action = DesktopFileChooserRequest::ACTION_DIRECTORY; caption_str = Str::D_SELECT_MBOX_DIRS_TO_IMPORT; } #endif break; case EngineTypes::APPLE: m_request.action = DesktopFileChooserRequest::ACTION_FILE_OPEN_MULTI; filter_str = Str::S_IMPORT_MBOX_FILTER; caption_str = Str::D_SELECT_FILES_TO_IMPORT; break; case EngineTypes::EUDORA: filter_str = Str::S_IMPORT_EUDORA_FILTER; caption_str = Str::D_SELECT_EUDORA_INI_TO_IMPORT; break; case EngineTypes::OPERA: filter_str = Str::S_IMPORT_OPERA6_MAIL_FILTER; caption_str = Str::D_SELECT_OPERA_ACCOUNTS_INI_TO_IMPORT; break; case EngineTypes::OPERA7: filter_str = Str::S_IMPORT_OPERA7_MAIL_FILTER; caption_str = Str::D_SELECT_OPERA7_ACCOUNTS_INI_TO_IMPORT; break; default: caption_str = Str::D_SELECT_FILES_TO_IMPORT; break; } OpString filter; g_languageManager->GetString(caption_str, m_request.caption); if (filter_str != Str::NOT_A_STRING) g_languageManager->GetString(filter_str, filter); m_request.extension_filters.DeleteAll(); if (filter.HasContent()) StringFilterToExtensionFilter(filter.CStr(), &m_request.extension_filters); OpStatus::Ignore(m_chooser->Execute(GetOpWindow(), this, m_request)); return; } else if (widget->IsNamed("Import_messages_check")) { BOOL enable_sent_dropdown = (BOOL)GetWidgetValue("Import_messages_check"); SetWidgetEnabled("Move_to_sent_dropdown", enable_sent_dropdown && (EngineTypes::OPERA != m_import_type && EngineTypes::EUDORA != m_import_type)); } Dialog::OnClick(widget, id); } void NewAccountWizard::DoMailImport() { OpDropDown* import_into = (OpDropDown*)GetWidgetByName("Import_intoaccount_dropdown"); UINT16 account_id = (UINT16)((UINTPTR)import_into->GetItemUserData(import_into->GetSelectedItem())); BOOL importsettings = GetWidgetValue("Import_settings_check"); BOOL importcontacts = GetWidgetValue("Import_contacts_check"); BOOL importmessages = GetWidgetValue("Import_messages_check"); if (m_importer_object->GetImportFileCount() == 0 && !m_import_path.IsEmpty()) { m_importer_object->AddImportFile(m_import_path); } OpDropDown* move_to_sent = (OpDropDown*)GetWidgetByName("Move_to_sent_dropdown"); if (move_to_sent) { ImporterModelItem* item = (ImporterModelItem*)move_to_sent->GetItemUserData(move_to_sent->GetSelectedItem()); m_importer_object->SetMoveToSentItem(item); } OpTreeView* accountTreeView = (OpTreeView*)GetWidgetByName("Import_setimportaccount"); if (EngineTypes::MBOX == m_import_type) { OpINT32Vector items; int item_count = accountTreeView->GetSelectedItems(items, FALSE); if (item_count == 0) { return; } OpVector<ImporterModelItem> modelItems; for (INT32 i = 0; i < item_count; i++) { ImporterModelItem* item = (ImporterModelItem*) accountTreeView->GetItemByPosition(items.Get(i)); if (!item) continue; modelItems.Add(item); } m_importer_object->SetImportItems(modelItems); modelItems.Clear(); if ((account_id==0 && m_importer_object->CreateImportAccount()==OpStatus::OK) || (account_id!=0 && m_importer_object->SetM2Account(account_id)==OpStatus::OK)) { SetWidgetText("Import_progress_label", UNI_L("")); ((OpProgressBar*)GetWidgetByName("Import_progress_bar"))->SetProgress(0, 0); EnableBackButton(FALSE); EnableForwardButton(FALSE); m_importer_object->ImportMessages(); } } else if(EngineTypes::OPERA7 == m_import_type) { OpINT32Vector items; int item_count = accountTreeView->GetSelectedItems(items, FALSE); if (item_count == 0) { return; } OpVector<ImporterModelItem> modelAccountItems; for (INT32 i = 0; i < item_count; i++) { ImporterModelItem* item = (ImporterModelItem*) accountTreeView->GetItemByPosition(items.Get(i)); if (!item) continue; modelAccountItems.Add(item); } m_importer_object->SetImportItems(modelAccountItems); modelAccountItems.Clear(); SetWidgetText("Import_progress_label", UNI_L("")); ((OpProgressBar*)GetWidgetByName("Import_progress_bar"))->SetProgress(0, 0); EnableBackButton(FALSE); EnableForwardButton(FALSE); // necessary to import messages, see Opera7Importer.h if (importmessages) m_importer_object->ImportMessages(); m_importer_object->ImportAccounts(); } #ifdef _MACINTOSH_ else if(EngineTypes::APPLE == m_import_type) { INT32 accounts_version = ((AppleMailImporter*)m_importer_object)->GetAccountsVersion(); OpINT32Vector items; int item_count = accountTreeView->GetSelectedItems(items, FALSE); if (item_count == 0) { return; } if(accounts_version < 2) { OpVector<ImporterModelItem> modelMailboxItems; OpVector<ImporterModelItem> modelSettingsItems; for (INT32 i = 0; i < item_count; i++) { ImporterModelItem* item = (ImporterModelItem*) accountTreeView->GetItemByPosition(items.Get(i)); if (!item) continue; if(item->GetType() == IMPORT_MAILBOX_TYPE || item->GetType() == IMPORT_FOLDER_TYPE) { modelMailboxItems.Add(item); } else { modelSettingsItems.Add(item); } } m_importer_object->SetImportItems(modelSettingsItems); modelSettingsItems.Clear(); BOOL has_account = FALSE; if (importsettings) { has_account = OpStatus::IsSuccess(m_importer_object->ImportSettings()); OpString importFinished; g_languageManager->GetString(Str::D_MAIL_IMPORT_FINISHED, importFinished); SetWidgetText("Import_progress_label", importFinished.CStr()); ((OpProgressBar*)GetWidgetByName("Import_progress_bar"))->SetProgress(100, 100); } if (!has_account) { if ((account_id==0 && m_importer_object->CreateImportAccount()!=OpStatus::OK) || (account_id!=0 && m_importer_object->SetM2Account(account_id)!=OpStatus::OK)) { OpString acc; if(m_importer_object->GetImportAccount(acc)) m_importer_object->SetM2Account(acc); } } m_importer_object->SetImportItems(modelMailboxItems); m_importer_object->SetImportItems(modelSettingsItems); modelMailboxItems.Clear(); if (importmessages) { SetWidgetText("Import_progress_label", UNI_L("")); ((OpProgressBar*)GetWidgetByName("Import_progress_bar"))->SetProgress(0, 0); EnableBackButton(FALSE); EnableForwardButton(FALSE); m_importer_object->ImportMessages(); } } else { for (INT32 i = 0; i < item_count; i++) { ImporterModelItem* item = (ImporterModelItem*) accountTreeView->GetItemByPosition(items.Get(i)); if (!item) continue; if(item->GetType() == IMPORT_ACCOUNT_TYPE) { m_importer_object->SetImportItem(item); BOOL has_account = FALSE; if (importsettings) { has_account = OpStatus::IsSuccess(m_importer_object->ImportSettings()); OpString importFinished; g_languageManager->GetString(Str::D_MAIL_IMPORT_FINISHED, importFinished); SetWidgetText("Import_progress_label", importFinished.CStr()); ((OpProgressBar*)GetWidgetByName("Import_progress_bar"))->SetProgress(100, 100); } if (has_account || (account_id==0 && m_importer_object->CreateImportAccount() == OpStatus::OK) || (account_id!=0 && m_importer_object->SetM2Account(account_id) == OpStatus::OK)) { OpVector<ImporterModelItem> items; items.Add(item); m_importer_object->SetImportItems(items); if (importmessages) { SetWidgetText("Import_progress_label", UNI_L("")); ((OpProgressBar*)GetWidgetByName("Import_progress_bar"))->SetProgress(0, 0); EnableBackButton(FALSE); EnableForwardButton(FALSE); m_importer_object->ImportMessages(); } } } } } } #endif // _MACINTOSH_ else { ImporterModelItem* item = (ImporterModelItem*)accountTreeView->GetSelectedItem(); if (item != NULL) { m_importer_object->SetImportItem(item); BOOL has_account = FALSE; if (importsettings) { has_account = OpStatus::IsSuccess(m_importer_object->ImportSettings()); OpString importFinished; g_languageManager->GetString(Str::D_MAIL_IMPORT_FINISHED, importFinished); SetWidgetText("Import_progress_label", importFinished.CStr()); ((OpProgressBar*)GetWidgetByName("Import_progress_bar"))->SetProgress(100, 100); } if (!has_account) { if ((account_id==0 && m_importer_object->CreateImportAccount()!=OpStatus::OK) || (account_id!=0 && m_importer_object->SetM2Account(account_id)!=OpStatus::OK)) { OpString acc; m_importer_object->GetImportAccount(acc); m_importer_object->SetM2Account(acc); } } if (importcontacts) { m_importer_object->ImportContacts(); OpString importFinished; g_languageManager->GetString(Str::D_MAIL_IMPORT_FINISHED, importFinished); SetWidgetText("Import_progress_label", importFinished.CStr()); ((OpProgressBar*)GetWidgetByName("Import_progress_bar"))->SetProgress(100, 100); } if (importmessages) { SetWidgetText("Import_progress_label", UNI_L("")); ((OpProgressBar*)GetWidgetByName("Import_progress_bar"))->SetProgress(0, 0); EnableBackButton(FALSE); EnableForwardButton(FALSE); m_importer_object->ImportMessages(); } } } } void NewAccountWizard::OnImporterProgressChanged(const Importer* importer, const OpStringC& infoMsg, OpFileLength current, OpFileLength total, BOOL simple) { OpString buf; if (!buf.Reserve(80)) return; buf.CStr()[0] = 0; if (total > 0) { int percent = current * 100 / total; if (simple) { OpString format; g_languageManager->GetString(Str::D_IMPORT_PROCESSING_SIMPLE, format); if (format.CStr()) { uni_sprintf(buf.CStr(), format.CStr(), percent, importer->GetGrandTotal()); } } else { OpString format; g_languageManager->GetString(Str::D_IMPORT_PROCESSING_FULL, format); if (format.CStr()) { uni_sprintf(buf.CStr(), format.CStr(), percent, current, total, importer->GetGrandTotal()); } } ((OpProgressBar*)GetWidgetByName("Import_progress_bar"))->SetProgress(current, total); } SetWidgetText("Import_info_label", infoMsg.CStr()); SetWidgetText("Import_progress_label", buf.CStr()); } void NewAccountWizard::OnImporterFinished(const Importer* importer, const OpStringC& infoMsg) { OpString label, format; g_languageManager->GetString(Str::D_IMPORT_FINISHED, format); if (format.HasContent()) { label.AppendFormat(format.CStr(), importer->GetGrandTotal()); } SetWidgetText("Import_info_label", infoMsg.CStr()); SetWidgetText("Import_progress_label", label.CStr()); EnableForwardButton(TRUE); EnableBackButton(TRUE); } void NewAccountWizard::GetServerInfo(BOOL incoming, OpString& host, unsigned& port, OpString& account_name) { OpString host_total; #ifdef IRC_SUPPORT // Special handling for incoming IRC servers if (m_type == AccountTypes::IRC && incoming) { OpString network_or_server; GetWidgetText("Incoming_dropdown", network_or_server); ChatNetworkManager* chat_networks = MessageEngine::GetInstance()->GetChatNetworks(); if (chat_networks) { if (chat_networks->HasNetwork(ChatNetworkManager::IRCNetworkType, network_or_server)) { account_name.Set(network_or_server); chat_networks->ServerList(ChatNetworkManager::IRCNetworkType, network_or_server, host_total, 6667); if (host_total.IsEmpty()) chat_networks->FirstServer(ChatNetworkManager::IRCNetworkType, network_or_server, host_total); } else { OpString network_name; OpStatus::Ignore(chat_networks->AddNetworkAndServers( ChatNetworkManager::IRCNetworkType, network_or_server, network_name)); if (network_name.HasContent()) { account_name.Set(network_name); chat_networks->ServerList(ChatNetworkManager::IRCNetworkType, network_name, host_total, 6667); if (host_total.IsEmpty()) chat_networks->FirstServer(ChatNetworkManager::IRCNetworkType, network_name, host_total); } } } } else #endif if (incoming) GetWidgetText("Incoming_edit", host_total); else GetWidgetText("Outgoing_edit", host_total); // Split server and port information port = 0; if (host_total.IsEmpty() || !host.Reserve(host_total.Length())) return; uni_sscanf(host_total.CStr(), UNI_L("%[^:]:%u"), host.CStr(), &port); } void NewAccountWizard::OnMouseEvent(OpWidget *widget, INT32 pos, INT32 x, INT32 y, MouseButton button, BOOL down, UINT8 nclicks) { if (!down && pos >= 0 && nclicks >= 2) { OpInputAction* action = NULL; RETURN_VALUE_IF_ERROR(OpInputAction::CreateInputActionsFromString("Forward", action), ); OpAutoPtr<OpInputAction> ptr(action); g_input_manager->InvokeAction(action, this); } } #endif //M2_SUPPORT
#ifndef ADDONS_DOMAINS_MATRIX_SEMELEM_FIXTURES_HPP #define ADDONS_DOMAINS_MATRIX_SEMELEM_FIXTURES_HPP #include "wali/ShortestPathSemiring.hpp" namespace testing { namespace semelem_matrix { using namespace boost::numeric::ublas; using namespace wali::domains; using wali::ShortestPathSemiring; const int inf = 1000; inline ShortestPathSemiring * make_sp(int val) { if (val == inf) { return ShortestPathSemiring::make_zero(); } else { return new ShortestPathSemiring(val); } } struct RandomMatrix1_3x3 { SemElemMatrix::BackingMatrix mat; RandomMatrix1_3x3() : mat(3,3) { int m[3][3] = { { 1, inf, inf}, { 12, 0, 1}, { inf, inf, 17} }; for (size_t i = 0; i< mat.size1(); ++i) { for (size_t j = 0; j < mat.size2(); ++j) { mat(i, j) = make_sp(m[i][j]); } } } }; struct RandomMatrix2_3x3 { SemElemMatrix::BackingMatrix mat; RandomMatrix2_3x3() : mat(3,3) { int m[3][3] = { { inf, 0, 21}, { 1, 17, 0}, { 0, 7, 12} }; for (size_t i = 0; i< mat.size1(); ++i) { for (size_t j = 0; j < mat.size2(); ++j) { mat(i, j) = make_sp(m[i][j]); } } } }; struct ExtendR1R2_3x3 { SemElemMatrix::BackingMatrix mat; ExtendR1R2_3x3() : mat(3,3) { int m[3][3] = { { inf, 1, 22}, { 1, 8, 0}, { 17, 24, 29} }; for (size_t i = 0; i< mat.size1(); ++i) { for (size_t j = 0; j < mat.size2(); ++j) { mat(i, j) = make_sp(m[i][j]); } } } }; struct ExtendR2R1_3x3 { SemElemMatrix::BackingMatrix mat; ExtendR2R1_3x3() : mat(3,3) { int m[3][3] = { { 12, 0, 1}, { 2, 17, 17}, { 1, 7, 8} }; for (size_t i = 0; i< mat.size1(); ++i) { for (size_t j = 0; j < mat.size2(); ++j) { mat(i, j) = make_sp(m[i][j]); } } } }; typedef ExtendR2R1_3x3 CombineR1Id_3x3; struct ZeroBackingMatrix_3x3 { SemElemMatrix::BackingMatrix mat; ZeroBackingMatrix_3x3() : mat(zero_matrix<SemElemMatrix::value_type>(3, 3)) {} }; struct IdBackingMatrix_3x3 { SemElemMatrix::BackingMatrix mat; IdBackingMatrix_3x3() : mat(identity_matrix<SemElemMatrix::value_type>(3, 3)) {} }; struct MatrixFixtures_3x3 { RandomMatrix1_3x3 r1; RandomMatrix2_3x3 r2; ExtendR1R2_3x3 ext_r1_r2; ExtendR2R1_3x3 ext_r2_r1; IdBackingMatrix_3x3 id; ZeroBackingMatrix_3x3 zero; }; } } #endif
#include "TestGTE.h" #include <iostream> #include <iomanip> int main(int argc, char **argv) { using namespace test; gte device; GTEtestbench tester(&device); tester.constructInstruction(0, DCPL); tester.storeData(gte::RGB, 0x0000000C); // red = 12 tester.storeData(gte::IR0, 0x00002A00); // ir0 = 2.625 tester.storeData(gte::IR1, 0x000035C0); // ir1,2,3 = 3.359375 tester.storeData(gte::IR2, 0x000035C0); tester.storeData(gte::IR3, 0x000035C0); tester.storeControl(gte::RFC, 0x00000500);// far red = 80 tester.storeControl(gte::GFC, 0x00000500);// far green = 80 tester.storeControl(gte::BFC, 0x00000500);// far blue = 80 /* Mac 1 = (12 * 3.359375) + 2.625*(B1[80 - (12 * 3.359375)]) * = 40.3125 + 2.625*(39.6875) * = 104.1796875->104.125 * = 144.4375 * * Mac 2, 3 = (0 * 3.4) + 2.625*(80 - 0) * = 210 * * IR1,2,3 = Mac1,2,3 * * RGB2 = 0x00D2D290 * */ tester.run(); if (tester.getData(gte::MAC1) == (144.4375 * 16) && tester.getData(gte::MAC2) == (210 * 16) && tester.getData(gte::MAC3) == (210 * 16) && tester.getData(gte::IR1) == (144.4375 * 16) && tester.getData(gte::IR2) == (210 * 16) && tester.getData(gte::IR3) == (210 * 16) && tester.getData(gte::RGB2) == 0x00D2D290) std::cout << argv[0] << " Pass" << std::endl; else { std::cout << argv[0] << " Fail" << std::endl; std::cout << "MAC1: " << tester.getData(gte::MAC1) << std::endl; std::cout << "MAC2: " << tester.getData(gte::MAC2) << std::endl; std::cout << "MAC3: " << tester.getData(gte::MAC3) << std::endl; std::cout << "IR1: " << tester.getData(gte::IR1) << std::endl; std::cout << "IR2: " << tester.getData(gte::IR2) << std::endl; std::cout << "IR3: " << tester.getData(gte::IR3) << std::endl; std::cout << "RGB2: " << std::hex << tester.getData(gte::RGB2) << std::endl; } }
#include <locale> #include <cppunit/extensions/HelperMacros.h> #include "cppunit/BetterAssert.h" #include "l10n/LocaleImpl.h" using namespace std; using namespace Poco; namespace BeeeOn { class SystemLocaleImplTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(SystemLocaleImplTest); CPPUNIT_TEST(testLanguage); CPPUNIT_TEST(testCountry); CPPUNIT_TEST(testDisplayName); CPPUNIT_TEST(testToString); CPPUNIT_TEST_SUITE_END(); public: void testLanguage(); void testCountry(); void testDisplayName(); void testToString(); }; CPPUNIT_TEST_SUITE_REGISTRATION(SystemLocaleImplTest); void SystemLocaleImplTest::testLanguage() { SystemLocaleImpl locale; CPPUNIT_ASSERT_EQUAL("C", locale.language()); } void SystemLocaleImplTest::testCountry() { SystemLocaleImpl locale; CPPUNIT_ASSERT_EQUAL("", locale.country()); } void SystemLocaleImplTest::testDisplayName() { SystemLocaleImpl locale; CPPUNIT_ASSERT_EQUAL("C", locale.displayName()); } void SystemLocaleImplTest::testToString() { SystemLocaleImpl locale; CPPUNIT_ASSERT_EQUAL("C", locale.toString()); } }
#include<iostream> //#include<cstdio> #include<ctime> #include <windows.h> #include<time.h> #include<stdio.h> #define MAX 10001 #define MAX_RANGE 10001 #define MIN(a,b) a<b?a:b #define good 8 using namespace std; typedef int typee; typee a[MAX],b[MAX]; double random(double start,double end){ return start+(end-start)*rand()/(RAND_MAX+1.0); } void print(typee a[],int n){ int x=MIN(good,n); for (int i=0;i<x;i++){ cout<<a[i]<<' '; } } void create(int n){ bool f[MAX_RANGE+1]={false}; srand(unsigned(time(0))); /* for (int i=0;i <n;i++){ a[i]=int (random(-MAX_RANGE,MAX_RANGE)); int f=0; for (int j=0;j<i;j++){ if (a[i]==a[j]) { i--;f=1; break; } } }*/ for (int i=0;i <n;i++){ a[i]=int (random(0,MAX_RANGE)); if (!f[a[i]]){ f[a[i]]=true; //cout<<i; continue; } i--; } } void swap(typee b[],int i,int j) { typee t=b[i]; b[i]=b[j]; b[j]=t; } void qs(typee a[],int l,int r){ if (l>=r) return; typee t=a[l]; int i=l,j=r; while (i<j){ while (i<j && a[j]>=t) j--; a[i]=a[j]; while (i<j && a[i]<=t) i++; a[j]=a[i]; } a[i]=t; qs(a,l,i-1); qs(a,i+1,r); } /* void choice(typee a[],int n){ int i,j,max; for (i=n-1;i>0;i--){ max=0; for (j=0;j<i;j++){ if (a[j]>a[max]) max=j; } swap(max,i); } } */ void bubble(typee a[],int n){ int i,j,f=1; while (f){ f=0; for (i=0;i<n-1;i++){ if (a[i]>a[i+1]) { swap(a,i,i+1); f=1; } } } } void binsearch(typee a[], int i,int j,int x){ if (i>j) {cout<<"找不到";return;} int m=(i+j)/2; if (a[m]==x) {cout<<x<<"找到了";} else if (a[m]<x) {cout<<m<<"->";binsearch(a,m+1,j,x);} else {cout<<m<<"->";binsearch(a,i,m-1,x);} } void binsearch2(typee a[], int l,int r,int x){ int i=l,j=r,m; while (i<=j){ m=(i+j)/2; if (a[m]==x) {cout<<x<<"找到了";return;} else if (a[m]<x) {cout<<m<<"->";i=m+1;} else {cout<<m<<"->";j=m-1;} } cout<<"找不到"; return; }
#pragma once class CD3DFont; namespace ui { class Console { public: Console(); ~Console(); void render(); void chooseFont(); void addMessage(const char* message); void addMessage(const string& message); void charpressed(const eXistenZ::KeyEventArgs& args); void keypressed(const eXistenZ::KeyEventArgs& args); void clear(); void reset(); public: int xpos; int ypos; int width; int height; int cmdecho; U32 filter; CD3DFont* d3dfont; deque<string> scrollback; deque<string> history; string cmd; unsigned int cursorpos; unsigned int historypos; int wireframe; int draw; mutex sbmutex; typedef deque<char*>::iterator scrollback_iter; }; };
#ifndef VNASTANDARDMODEL_H #define VNASTANDARDMODEL_H // Rsa // // Qt #include <QMetaType> namespace RsaToolbox { class VnaStandardModel { public: enum /*class*/ Type { Open, Short, Match, R, Thru }; VnaStandardModel(); VnaStandardModel(const VnaStandardModel &other); // Use default double minimumFrequency_Hz; double maximumFrequency_Hz; Type type; double eLength_m; double loss_dB_per_sqrt_Hz; double Z0_Ohms; bool hasCapacitanceValues() const; double C0_fF; double C1_fF_per_GHz; double C2_fF_per_GHz2; double C3_fF_per_GHz3; bool hasInductanceValues() const; double L0_pH; double L1_pH_per_GHz; double L2_pH_per_GHz2; double L3_pH_per_GHz3; bool hasRValue() const; double R_Ohms; void operator=(VnaStandardModel const &other); }; bool operator==(VnaStandardModel const &left, VnaStandardModel const &right); bool operator!=(VnaStandardModel const &left, VnaStandardModel const &right); } Q_DECLARE_METATYPE(RsaToolbox::VnaStandardModel) #endif // VNASTANDARDMODEL_H
#define _CRT_SECURE_NO_WARNINGS //#define LOCAL_TEST #include <iostream> #include "parser.hpp" #include "bookingSystem.h" ticketBookingSystem S; string getToken(const string &str, int t) { int l = str.length(), cnt = 0, st = 0; for(int i=0;i<l;i++) if (str[i] == ' ') { cnt++; if (cnt == t) return str.substr(st,i-st); else if (cnt == t - 1) st = i + 1; } return str; } int main() { #ifdef LOCAL_TEST freopen("2s.in", "r", stdin); freopen("myans.txt", "w", stdout); S.process("clean", vector<token>()); #endif // LOCAL_TEST std::ios_base::sync_with_stdio(0); //std::cout.precision(10); std::string str,s; //std::cout << sizeof(keyInfo) << " " << sizeof(Detail) << endl; while (true) { std::getline(std::cin,str); s = getToken(str, 1); if (s == "add_train" || s == "modify_train") { s = getToken(str,5); int n = 0; for (int i = 0; i < s.length(); i++) n = n * 10 + s[i] - '0'; while (n--) { std::getline(std::cin, s); str = str + '\n' + s; } } EXECUTOR(S,str); } return 0; }
#include <iostream> #include "Controller.hpp" #include "Briscola.hpp" #include "View.hpp" int main(){ // TEST Briscola Briscola* model = new Briscola(); Controller<Briscola>* cont = new Controller<Briscola>( model , new View<Briscola>() ); // REMPLACER LA LIGNE 32 PAR CELLES-CI POUR TESTER PLUS VITE (SANS ENTRER LES PRENOMS A CHAQUE FOIS) /* Team* t1 = new Team(); Team* t2 = new Team(); Player* p1 = new Player("J1",false,0); Player* p2 = new Player("J2",false,1); Player* p3 = new Player("J3",false,1); Player* p4 = new Player("J4",false,0); t1->addPlayer(p1); t2->addPlayer(p2); t2->addPlayer(p3); t1->addPlayer(p4); model->addTeam(t1); model->addTeam(t2); model->addPlayer(p1); model->addPlayer(p2); model->addPlayer(p3); model->addPlayer(p4); */ cont->initPlayers(1,2,2,5); // peut être remplacé par les lignes au dessus cont->launch_game_loop(); delete cont; return 0; }
#include "TestCPU.h" #include <iostream> int main(int argc, char** argv) { using namespace test; memoryInterface *mem = new RAMImpl(10); cpu device(mem); CPUtestbench tester(&device); mem->writeWord(0x110, 0xFEDCBA09); tester.storeReg(1, 0x55); tester.storeReg(2, 0x77); tester.storeReg(15, 0x100); tester.constructInstruction(SB, 15, 1, 0x10); tester.constructInstruction(SB, 15, 2, 0x12); tester.run(); if (mem->readWord(0x110) == 0xFE77BA55) std::cout << argv[0] << " Pass" << std::endl; else { std::cout << argv[0] << " Fail" << std::endl; std::cout << "Mem 0x110 = " << mem->readWord(0x110) << std::endl; } delete mem; }
#include <NTL/GF2X.h> #include <stdint.h> #include <UnitTest++.h> #include <tr1/random> #include <sstream> #include "xsadd.h" #include "xsadd.c" // to check static functions using namespace NTL; using namespace std; void touz(uz *r, ZZ& x) { ZZ work = x; uz_clear(r); for (int i = 0; i < UZ_ARRAY_SIZE; i++) { for (int j = 0; j < 16; j++) { uint16_t mask = 1 << j; if (IsOdd(work)) { r->ar[i] |= mask; } work = work >> 1; } } } void uztostring16(char * str, uz * x) { int p = 0; int first = 1; for (int i = UZ_ARRAY_SIZE - 1; i >= 0; i--) { if (first) { if (x->ar[i] != 0) { first = 0; sprintf(str, "%x", x->ar[i]); p = strlen(str); } } else { sprintf(str + p, "%04x", x->ar[i]); p = p + 4; } } if (first) { strcpy(str, "0"); } } void to16string(char * buff, ZZ& x) { uz tmp; touz(&tmp, x); uztostring16(buff, &tmp); } bool eq(xsadd_t& xs1, xsadd_t& xs2) { for (int i = 0; i < 4; i++) { if (xs1.state[i] != xs2.state[i]) { return false; } } return true; } SUITE(JUMP) { TEST(SMALL) { xsadd_t xs1; xsadd_t xs2; tr1::mt19937 mt(1); for (int i = 0; i < 200; i++) { uint32_t seed = mt(); int step = mt() % 500; xsadd_init(&xs1, seed); xsadd_init(&xs2, seed); xsadd_jump(&xs1, step, "1"); for (int j = 0; j < step; j++) { xsadd_uint32(&xs2); } CHECK(eq(xs1, xs2)); } } TEST(LARGE) { xsadd_t xs1; xsadd_t xs2; tr1::mt19937 mt(1); char buff[200]; for (int i = 0; i < 200; i++) { uint32_t seed = mt(); int step = mt() % 500; ZZ lstep; RandomBits(lstep, 70); to16string(buff, lstep); xsadd_init(&xs1, seed); xsadd_init(&xs2, seed); xsadd_jump(&xs1, step, buff); lstep *= step; to16string(buff, lstep); xsadd_jump(&xs2, 1, buff); CHECK(eq(xs1, xs2)); } } }
// Sharna Hossain // CSC 111 // Lab 8 | grades_switch2.cpp #include <iostream> using namespace std; int main() { int grade; char letter_grade; cout << "Enter a grade (0-100): "; cin >> grade; if (grade >= 0 && grade <= 100) { // This solution works because grade is an int being divided // by the int 10, so the result will be an int, as reflected // in the possible cases. switch (grade/10) { case 10: case 9: letter_grade = 'A'; break; case 8: letter_grade = 'B'; break; case 7: letter_grade = 'C'; break; case 6: letter_grade = 'D'; break; default: letter_grade = 'F'; } cout << "Your grade is " << letter_grade << endl; } else { cout << "ERROR: Invalid grade\n"; cout << "Please rerun the program and enter a grade from 0-100\n"; } return 0; }
#include <bits/stdc++.h> using namespace std; #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 20000000 #define INF 0x3f3f3f3f #define DEVIATION 0.00000005 typedef long long LL; bool sieve[MAXN+10]; vector <int> Prime; vector <pair<int,int>> TwinPrime; void build(){ memset(sieve, 0, sizeof(sieve)); for(int i = 2 ; i < MAXN+5 ; i++ ){ if( !sieve[i] ){ for(int j = i+i ; j < MAXN+5 ; j+=i ) sieve[j] = true; Prime.push_back(i); } } pair <int,int> P; for(int i = 1 ; i < Prime.size() ; i++ ){ if( Prime[i-1]+2 == Prime[i] ){ P.first = Prime[i-1]; P.second = Prime[i]; TwinPrime.push_back(P); } } } int main(int argc, char const *argv[]) { build(); int num; while( ~scanf("%d", &num) ) printf("(%d, %d)\n", TwinPrime[num-1].first, TwinPrime[num-1].second); return 0; }
// Created on: 1994-10-13 // Created by: Jean Yves LEBEY // Copyright (c) 1994-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _TopOpeBRep_FaceEdgeIntersector_HeaderFile #define _TopOpeBRep_FaceEdgeIntersector_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <TopoDS_Face.hxx> #include <TopoDS_Edge.hxx> #include <GeomAdaptor_Curve.hxx> #include <IntCurveSurface_SequenceOfPnt.hxx> #include <TColStd_SequenceOfInteger.hxx> #include <Standard_Integer.hxx> #include <TopExp_Explorer.hxx> #include <TopoDS_Shape.hxx> #include <TopoDS_Vertex.hxx> #include <TopAbs_State.hxx> #include <TopAbs_Orientation.hxx> #include <TopAbs_ShapeEnum.hxx> class gp_Pnt; class gp_Pnt2d; class TopOpeBRepDS_Transition; //! Describes the intersection of a face and an edge. class TopOpeBRep_FaceEdgeIntersector { public: DEFINE_STANDARD_ALLOC Standard_EXPORT TopOpeBRep_FaceEdgeIntersector(); Standard_EXPORT void Perform (const TopoDS_Shape& F, const TopoDS_Shape& E); Standard_EXPORT Standard_Boolean IsEmpty(); //! returns intersected face or edge according to //! value of <Index> = 1 or 2 Standard_EXPORT const TopoDS_Shape& Shape (const Standard_Integer Index) const; //! Force the tolerance values used by the next Perform(S1,S2) call. Standard_EXPORT void ForceTolerance (const Standard_Real tol); //! Return the tolerance value used in the last Perform() call //! If ForceTolerance() has been called, return the given value. //! If not, return value extracted from shapes. Standard_EXPORT Standard_Real Tolerance() const; Standard_EXPORT Standard_Integer NbPoints() const; Standard_EXPORT void InitPoint(); Standard_EXPORT Standard_Boolean MorePoint() const; Standard_EXPORT void NextPoint(); //! return the 3D point of the current intersection point. Standard_EXPORT gp_Pnt Value() const; //! parametre de Value() sur l'arete Standard_EXPORT Standard_Real Parameter() const; //! parametre de Value() sur la face Standard_EXPORT void UVPoint (gp_Pnt2d& P) const; //! IN ou ON / a la face. Les points OUT ne sont pas retournes. Standard_EXPORT TopAbs_State State() const; //! Index = 1 transition par rapport a la face, en cheminant sur l'arete Standard_EXPORT TopOpeBRepDS_Transition Transition (const Standard_Integer Index, const TopAbs_Orientation FaceOrientation) const; Standard_EXPORT Standard_Boolean IsVertex (const TopoDS_Shape& S, const gp_Pnt& P, const Standard_Real Tol, TopoDS_Vertex& V); Standard_EXPORT Standard_Boolean IsVertex (const Standard_Integer I, TopoDS_Vertex& V); //! trace only Standard_EXPORT Standard_Integer Index() const; protected: private: Standard_EXPORT void ResetIntersection(); //! extract tolerance values from shapes <S1>,<S2>, //! in order to perform intersection between <S1> and <S2> //! with tolerance values "fitting" the shape tolerances. //! (called by Perform() by default, when ForceTolerances() has not //! been called) Standard_EXPORT void ShapeTolerances (const TopoDS_Shape& S1, const TopoDS_Shape& S2); //! returns the max tolerance of sub-shapes of type <T> //! found in shape <S>. If no such sub-shape found, return //! Precision::Intersection() //! (called by ShapeTolerances()) Standard_EXPORT Standard_Real ToleranceMax (const TopoDS_Shape& S, const TopAbs_ShapeEnum T) const; TopoDS_Face myFace; TopoDS_Edge myEdge; Standard_Real myTol; Standard_Boolean myForceTolerance; GeomAdaptor_Curve myCurve; Standard_Boolean myIntersectionDone; IntCurveSurface_SequenceOfPnt mySequenceOfPnt; TColStd_SequenceOfInteger mySequenceOfState; Standard_Integer myPointIndex; Standard_Integer myNbPoints; TopExp_Explorer myVertexExplorer; TopoDS_Shape myNullShape; TopoDS_Vertex myNullVertex; }; #endif // _TopOpeBRep_FaceEdgeIntersector_HeaderFile
// // main.cpp // PlaneMapBatch // // Created by Yimeng Zhang on 5/25/14. // Copyright (c) 2014 Yimeng Zhang. All rights reserved. // // Include standard headers #include <iostream> #include <cstdio> #include <cstdlib> // Include GLEW #include <GL/glew.h> // Include GLFW #include <GLFW/glfw3.h> // Include GLM #include <glm/glm.hpp> //#include <glm/gtc/matrix_transform.hpp> #include <cmath> // my helper functions #include "draw_single_frame.h" #include "load_float_image.h" #include "write_float_image.h" // shader functions. #include <../common/shader.hpp> #include <../common/texture.hpp> #include "parameter_struct.h" #include "getParameters.h" // for output #include <string> #include <fstream> int main(int argc, const char * argv[]) { GLFWwindow* window; // Initialise GLFW if( !glfwInit() ) { fprintf( stderr, "Failed to initialize GLFW\n" ); return -1; } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);//crucial for Mac. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Open a window and create its OpenGL context window = glfwCreateWindow( 1, 1, "PlaneMapBatch", NULL, NULL); if( window == NULL ){ glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwHideWindow(window); // Initialize GLEW glewExperimental = true; // Needed for core profile if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); return -1; } // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); // write something to pass in parameters. // pass in width, height, configuration file for 2 (or more) cameras, configuration file for vertex array (all in a big file), and filename list for a lot of image patch file. // here I should get // 1. width & height // 2. 650 surfaces, each with 6 vertices ParameterStruct parameterStruct; getParameters(&parameterStruct,argc,argv); GLsizei width = parameterStruct.width; GLsizei height = parameterStruct.height; // enable my frame buffer. GLuint fbo; glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER,fbo); // set 2 textures for my framebuffer GLuint color_texture; glGenTextures(1, &color_texture); glBindTexture(GL_TEXTURE_2D, color_texture); glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA16F, width, height); // allocate space for my frame buffer. // turn off mipmap for this. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); GLuint depth_texture; glGenTextures(1, &depth_texture); glBindTexture(GL_TEXTURE_2D, depth_texture); glTexStorage2D(GL_TEXTURE_2D, 1, GL_DEPTH_COMPONENT32F, width, height); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, color_texture, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depth_texture, 0); // specify that we write into the buffer. static const GLenum draw_buffers[] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1,draw_buffers); glBindFramebuffer(GL_FRAMEBUFFER, fbo); glViewport(0, 0, width , height); const GLfloat bkgcolor[] = { 0.0f, 0.0f, 0.0f, 1.0f }; static const GLfloat one = 1.0f; // don't understand why we set zero.. glClearBufferfv(GL_COLOR, 0, bkgcolor); glClearBufferfv(GL_DEPTH, 0, &one); GLenum fboStatus = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); assert(fboStatus==GL_FRAMEBUFFER_COMPLETE); // Create and compile our GLSL program from the shaders GLuint programID = LoadShaders( "../shader/TransformVertexShader.vertexshader", "../shader/TextureFragmentShader.fragmentshader" ); // Use our shader glUseProgram(programID); GLuint VertexArrayID; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); // Get a handle for our "MVP" uniform GLuint MatrixID = glGetUniformLocation(programID, "MVP"); // Two UV coordinatesfor each vertex. This is fixed for now. static const GLfloat g_uv_buffer_data[] = { 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, }; // bind uv buffer GLuint uvbuffer; glGenBuffers(1, &uvbuffer); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_uv_buffer_data), g_uv_buffer_data, GL_STATIC_DRAW); GLfloat const *g_vertex_buffer_data = NULL; //fixed for now. g_vertex_buffer_data = NULL; // claim vertex bufer. GLuint vertexbuffer; glGenBuffers(1, &vertexbuffer); size_t surfaceTotal = parameterStruct.vectorBufferArray.size()/(3*6); size_t textureTotal = parameterStruct.imageFileNameArray.size(); size_t MVPTotal = parameterStruct.MVPArray.size(); glm::mat4 MVP; std::ofstream output(parameterStruct.outputFileNameListName); for (int iTexture = 0; iTexture < textureTotal; iTexture++) { //update vertex buffer in my own RAM //"visa2.flt" should be fed by a list. const char *textureName = parameterStruct.imageFileNameArray[iTexture].c_str(); GLuint Texture = load_float_image(textureName); for (int iSurface = 0; iSurface < surfaceTotal; iSurface++) { g_vertex_buffer_data = parameterStruct.vectorBufferArray.data(); g_vertex_buffer_data = g_vertex_buffer_data + 6*3*iSurface; //update vertex buffer in GPU. glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, 6*3*sizeof(GLfloat), g_vertex_buffer_data, GL_STATIC_DRAW); for (int iMVP = 0; iMVP < MVPTotal; iMVP++) { //update MVP matrix. (bounding done in inner function). MVP = parameterStruct.MVPArray[iMVP]; draw_single_frame(MatrixID, MVP, Texture, vertexbuffer, uvbuffer, 6); //"out.flt" should be fed by a list. if (!(parameterStruct).singleOutput) { // here we use a C++11 feature for fast development... std::string outputName = parameterStruct.outputPrefix + "_" + std::to_string(iTexture) + "_" + std::to_string(iSurface) + "_" + parameterStruct.MVPNameArray[iMVP] + parameterStruct.outputSuffix; write_float_image(fbo,width,height,outputName.c_str(),false); output <<outputName << std::endl; } else { write_float_image(fbo,width,height,parameterStruct.outputFileNameListName.c_str(),true); } } } // clean up texture generated. glDeleteTextures(1, &Texture); } //clean up output.close(); glDeleteBuffers(1, &vertexbuffer); glDeleteBuffers(1, &uvbuffer); glDeleteProgram(programID); glDeleteVertexArrays(1, &VertexArrayID); glDeleteFramebuffers(1,&fbo); glDeleteTextures(1, &color_texture); glDeleteTextures(1, &depth_texture); // Close OpenGL window and terminate GLFW glfwTerminate(); return 0; }
#include "udpclient.h" // liste des commandes char scmd[] = "b<ps>nxi m-+v"; UdpClient::UdpClient( QObject *parent ) : QObject( parent ) { hostIp.setAddress( QString( LAROCOLA_IP )); #ifdef DEBUG if( udpSocket.bind( SERVER_PORT )) qDebug() << "Ready to read"; else qDebug() << "Not ready to read"; #else udpSocket.bind( SERVER_PORT ); #endif QObject::connect( &udpSocket, SIGNAL( readyRead() ), this, SLOT( getData() )); moreLines = ". . ."; for( int i = 0; i < NUM_LINE; i++ ) { linesList.append( " " ); filesList.append( " " ); } // visualise la version de la telecommande sur la derniere ligne de la liste linesList.replace( NUM_LINE - 1, VERSION ); // demande la version de LaRocola (commande 'v') sendCmd( 32 ); // attend 2 secondes et demande la liste des fichiers depth = 0; QTimer::singleShot( 2000, this, SLOT( sendCmdListRoot())); } UdpClient::~UdpClient() { udpSocket.close(); } void UdpClient::sendDatagram( char * cmd ) { QByteArray datagram( cmd ); udpSocket.writeDatagram( datagram, hostIp, 8888 ); #ifdef DEBUG qDebug() << "Sending: " << datagram; #endif } void UdpClient::sendCmd( int cmd ) { #ifdef DEBUG qDebug() << "Command: " << cmd; #endif if( cmd == 0 ) { clearList( 0 ); sendCmdList( "/" ); } else if( cmd <= NUM_LINE ) { cmd --; QByteArray fn = filesList.at( cmd ); if( fn.length() > 0 ) { QByteArray path; if( type( fn ) >= 1 ) // fichier mp3 { for( int i = 0; i < depth; i++ ) path.append( "/" + filesList.at( i )); path.append( "/" + filesList.at( cmd )); sendCmdPlay( path ); } else { if( cmd < depth ) depth = cmd; for( int i = 0; i < depth; i++ ) path.append( "/" + filesList.at( i )); if( filesList.at( cmd ) == moreLines ) path.append( "/" + filesList.at( cmd - 1 )); else { path.append( "/" + filesList.at( cmd ) + "/" ); filesList.replace( depth, filesList.at( cmd )); linesList.replace( depth, linesList.at( cmd )); // typesList.replace( depth, typesList.at( cmd )); depth ++; } clearList( depth ); sendCmdList( path.data() ); } } } else if( cmd == 28 ) ; //sendCmdPlay( "/The Beatles/Rubber Soul/01 - Drive My Car.mp3" ); else if( cmd >= 20 ) { // send *x* where x is the command cmd -= 20; char c[4]; c[0] = '*'; c[1] = scmd[ cmd ]; c[2] = '*'; c[3] = 0; sendDatagram( c ); } } void UdpClient::sendCmdList( char * dir ) { // maxline - depth suffit à remplir la liste. // mais on demande une ligne de plus pour savoir s'il y en a d'autre QByteArray cmd; cmd.append( "*l*" ); cmd.append( (char) ('0' + NUM_LINE - depth + 1 )); cmd.append( dir ); sendDatagram( cmd.data()); } void UdpClient::sendCmdPlay( QByteArray play ) { QByteArray cmd; cmd.append( "*f*" ); cmd.append( play ); sendDatagram( cmd.data()); } void UdpClient::getData() { QByteArray datagram; #ifdef DEBUG qDebug() << "Receiving:"; #endif do { datagram.resize( udpSocket.pendingDatagramSize() ); udpSocket.readDatagram( datagram.data(), datagram.size() ); #ifdef DEBUG qDebug() << datagram; #endif char c = datagram.at(0); int n = datagram.at(1) - '0'; if( c == 'i' ) { if( n == 1 ) statusline1 = datagram.mid( 2 ); else if( n == 2 ) statusline2 = datagram.mid( 2 ); emit statusChanged(); } else if( c == 'l' ) // l premiere lettre de list, pas "un" if( n >= 0 ) { if( n + depth < NUM_LINE ) { linesList.replace( n + depth, format( datagram.mid( 2 ), depth )); filesList.replace( n + depth, datagram.mid( 2 )); } else { linesList.replace( NUM_LINE - 1, ident( moreLines, depth )); filesList.replace( NUM_LINE - 1, moreLines ); } emit linesChanged(); } } while( udpSocket.hasPendingDatagrams() ); } QStringList UdpClient::lines() { // return filesList; return linesList; } QString UdpClient::status1() { return statusline1.data(); } QString UdpClient::status2() { return statusline2.data(); } void UdpClient::clearList( int d ) { for( int i = d; i < NUM_LINE; i++ ) { linesList.replace( i, "" ); filesList.replace( i, "" ); } depth = d; emit linesChanged(); } int UdpClient::type( QByteArray file ) { int lf = file.length(); int pp = file.lastIndexOf( '.' ); if( pp == -1 || lf - pp > 5 ) return 0; QByteArray ext = file.right( lf - pp - 1 ); ext = ext.toLower(); if( ext == "mp3" || ext == "aac" || ext == "flac" || ext == "ogg" || ext == "wav" || ext == "wma" ) return 1; else if( ext == "rad" ) return 2; return 0; } QString UdpClient::colorFile( int ind ) { switch( type( filesList.at( ind ))) { case 1: return "#1E9A5A"; case 2: return "#7070FF"; default: return "#943232"; } } QByteArray UdpClient::format( QByteArray l, int d ) { QByteArray f = l; // retire "01 - " ou "01-" int i = 0; while( f.length() > i ) { char c = f.at( i ); if( c >= '0' && c <= '9') i++; else break; } while( i > 0 && f.length() > i ) { char c = f.at( i++ ); if( c == '-' ) break; else if( c != ' ' ) i = -1; } while( i > 1 && f.length() > i ) { if( f.at( i ) != ' ' ) break; i++; } if( i > 0 ) f.remove( 0, i ); // retire l'extension ( 4 ou 5 caracteres ) if( f.length() > 4 && type( l ) >= 1 ) { int lc = f.length() - f.lastIndexOf( '.' ); if( lc <= 5 ) f.chop( lc ); } f = ident( f, d ); return f; } QByteArray UdpClient::ident( QByteArray l, int d ) { QByteArray f = l; if( d > 0 ) f.insert( 0, QByteArray( 3*d, ' ' )); return f; }
#include<iostream> #include<cmath> using namespace std; int n; char gr; void putout(string s) { int space=s.find(' '),lth=s.length(); int n1=0,n2=0,n3; for(int i=0;i<space;i++) n1=n1*10+s[i]-'0'; for(int i=space+1;i<lth;i++) n2=n2*10+s[i]-'0'; if(gr=='a') { n3=n1+n2; while(n3) n3/=10,lth++; cout<<n1<<'+'<<n2<<'='<<n1+n2<<endl<<(n1+n2<0?lth+2:lth+1)<<endl; } if(gr=='b') { n3=n1-n2; while(n3) n3/=10,lth++; cout<<n1<<'-'<<n2<<'='<<n1-n2<<endl<<(n1-n2<0?lth+2:lth+1)<<endl; } if(gr=='c') { n3=n1*n2; while(n3) n3/=10,lth++; cout<<n1<<'*'<<n2<<'='<<n1*n2<<endl<<(n1*n2<0?lth+2:lth+1)<<endl; } } int main() { //freopen("1.out","w",stdout); cin>>n; for(int i=1;i<=n+1;i++) { string s; getline(cin,s); if(s[0]>='a' && s[0]<='c') { gr=s[0]; s.erase(0,2); } putout(s); } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef DOM_JILUTILS_H #define DOM_JILUTILS_H #ifdef DOM_JIL_API_SUPPORT #include "modules/device_api/jil/JILFeatures.h" #include "modules/util/OpHashTable.h" #ifdef PI_POWER_STATUS #include "modules/pi/device_api/OpPowerStatus.h" #endif // PI_POWER_STATUS #include "modules/dom/src/domjil/domjilobject.h" #include "modules/dom/src/domsuspendcallback.h" #include "modules/device_api/jil/utils.h" #include "modules/device_api/SystemResourceSetter.h" class ES_Object; class JILApplicationNames; class OpGadget; class DOM_Runtime; struct DOM_JIL_Array_Element { ES_Value m_val; int m_index; }; class JIL_PropertyMappings; class JILUtils { public: JILUtils(); virtual ~JILUtils(); void ConstructL(); /** * See JILApplicationNames. */ JILApplicationNames* GetApplicationNames() { return m_jil_application_names;} /** * Extracts the gadget object from origining_runtime. * * @return gadget object associated with the origining_runtime or NULL */ OpGadget* GetGadgetFromRuntime(DOM_Runtime* origining_runtime); /** * Helper determining whether runtime should have access to filesystem. * should only be called by JIL objects in widgets */ // TODO: this functionality should be moved to security_manager BOOL RuntimeHasFilesystemAccess(DOM_Runtime* origining_runtime); static BOOL ValidatePhoneNumber(const uni_char* number); /** * Check whether given api_name is present in configuration file of a * gadget for this runtime. */ BOOL IsJILApiRequested(JILFeatures::JIL_Api api_name, DOM_Runtime* runtime); /** Helper class for implementing suspending callbacks */ template<class CallbackInterface> class ModificationSuspendingCallbackImpl : public DOM_SuspendCallback<CallbackInterface> { public: virtual void OnSuccess(const uni_char* id) { OP_STATUS error = m_id.Set(id); if (OpStatus::IsError(error)) DOM_SuspendCallbackBase::OnFailed(error); else DOM_SuspendCallbackBase::OnSuccess(); } virtual void OnFailed(const uni_char* id, OP_STATUS error) { m_id.Set(id); DOM_SuspendCallbackBase::OnFailed(error); } const uni_char* GetElementId() const { return m_id.CStr(); } private: OpString m_id; }; class SetSystemResourceCallbackSuspendingImpl : public DOM_SuspendCallback<SystemResourceSetter::SetSystemResourceCallback> { public: virtual void OnFinished(OP_SYSTEM_RESOURCE_SETTER_STATUS status); }; private: JILApplicationNames* m_jil_application_names; }; #endif// DOM_JIL_API_SUPPORT #endif // DOM_JILUTILS_H
#pragma once #include "WeaponInfo.h" class MeshBuilder; class Pistol : public CWeaponInfo { public: Pistol(GenericEntity::OBJECT_TYPE _bulletType); virtual ~Pistol(); // Initialise this instance to default values void Init(void); //render weapon void Render(); //Reolad gun void Reload(); // Discharge this weapon void Discharge(Vector3 position, Vector3 target); // Get mesh Mesh* GetMesh(); private: // Number of bullet to create and pattern void generateBullet(Vector3 position, Vector3 target, const int numBullet = 1, const float angle = 0.f); //void generateEnemyBullet(Vector3 position, Vector3 target, const int numBullet = 1, const float angle = 0.f); };
#ifndef _PLAYER_H #define _PLAYER_H #include <string> using namespace std; class PLAYER { private: //private data members unsigned short p_Level; unsigned int p_Xp; int p_HpMax; int p_Hp; short p_Armour; short p_Attack; string p_EquipedWeapon; string p_EquipedHeadArmour; string p_EquipedChestArmour; string p_EquipedLegArmour; string p_EquipedRingArmour; public: //public methods. PLAYER(); PLAYER(unsigned short Level, unsigned int Xp, int HpMax, int Hp, short Armour, short Attack, string EquipedWeapon, string EquipedHeadArmour, string EquipedChestArmour, string EquipedLegArmour, string EquipedRingArmour); void SetLevel(unsigned short Level); unsigned short GetLevel(); void SetXp(unsigned int Xp); unsigned int GetXp(); void SetHpMax(int HpMax); int GetHpMax(); void SetHp(int Hp); int GetHp(); void SetArmour(short Armour); short GetArmour(); void SetAttack(short Attack); short GetAttack(); void SetEquipedWeapon(string EquipedWeapon); string GetEquipedWeapon(); void SetEquipedHeadArmour(string EquipedHeadArmour); string GetEquipedHeadArmour(); void SetEquipedChestArmour(string EquipedChestArmour); string GetEquipedChestArmour(); void SetEquipedLegArmour(string EquipedLegArmour); string GetEquipedLegArmour(); void SetEquipedRingArmour(string EquipedRingArmour); string GetEquipedRingArmour(); }; #endif
#ifndef CALLER_H #define CALLER_H // These classes were made to provide a unified way of using // pointers to functions as well as pointers to member functions // KEEP IN MIND THAT THE MEMBER FUNCTION POINTERS 'GO BAD' once // the object they point to is deleted! template<typename retType, typename... paramType> class Caller { public: Caller(); virtual ~Caller(); virtual retType doCall(paramType...) = 0; }; template<typename retType, typename... paramType> class FuncCaller : public Caller<retType, paramType...> { public: FuncCaller(retType (*toCall)(paramType...)); ~FuncCaller(); retType doCall(paramType...); private: FuncCaller(); retType (*funcPtr)(paramType...); }; template<class ToCall, typename retType, typename... paramType> class ClassCaller : public Caller<retType, paramType...> { public: ClassCaller(ToCall* obj, retType (ToCall::*member)(paramType...)); ~ClassCaller(void); retType doCall(paramType...); private: ClassCaller(); ToCall* const object; retType (ToCall::*funcPtr)(paramType...); }; // G++ requires the actual functions within the header, since it doesn't // actually compile anything before linking when it comes to templates #include "Caller.cpp" #endif // CALLER_H
// This program converts a set of images to a lmdb/leveldb by storing them // as Datum proto buffers. // Usage: // convert_imageset [FLAGS] ROOTFOLDER/ LISTFILE DB_NAME // // where ROOTFOLDER is the root folder that holds all the images, and LISTFILE // should be a list of files as well as their labels, in the format as // subfolder1/file1.JPEG 7 // .... #include <gflags/gflags.h> #include <glog/logging.h> #include <leveldb/db.h> #include <leveldb/write_batch.h> #include <lmdb.h> #include <sys/stat.h> #include <algorithm> #include <fstream> // NOLINT(readability/streams) #include <string> #include <utility> #include <vector> #include <opencv2/opencv.hpp> #include "caffe/proto/caffe.pb.h" // #include "caffe/util/io.hpp" #include "caffe/util/rng.hpp" using namespace caffe; // NOLINT(build/namespaces) using std::pair; using std::string; DEFINE_bool(gray, false, "When this option is on, treat images as grayscale ones"); DEFINE_bool(shuffle, false, "Randomly shuffle the order of images and their labels"); DEFINE_string(backend, "lmdb", "The backend for storing the result"); DEFINE_int32(resize_width, 0, "Width images are resized to"); DEFINE_int32(resize_height, 0, "Height images are resized to"); bool ReadImageToDatum(const string& filename1, const string& filename2, const int label, const int height, const int width, const bool is_color, Datum* datum) { cv::Mat cv_img1; cv::Mat cv_img2; int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR : CV_LOAD_IMAGE_GRAYSCALE); cv::Mat cv_img1_origin = cv::imread(filename1, cv_read_flag); cv::Mat cv_img2_origin = cv::imread(filename2, cv_read_flag); if (!cv_img1_origin.data || !cv_img2_origin.data) { LOG(ERROR) << "Could not open or find file " << filename1 << " : " << filename2; return false; } if (height > 0 && width > 0) { cv::resize(cv_img1_origin, cv_img1, cv::Size(width, height)); cv::resize(cv_img2_origin, cv_img2, cv::Size(width, height)); } else { cv_img1 = cv_img1_origin; cv_img2 = cv_img2_origin; } int num_channels = (is_color ? 6 : 2); datum->set_channels(num_channels); datum->set_height(cv_img1.rows); datum->set_width(cv_img1.cols); datum->set_label(label); datum->clear_data(); datum->clear_float_data(); string* datum_string = datum->mutable_data(); if (is_color) { for (int c = 0; c < num_channels/2; ++c) { for (int h = 0; h < cv_img1.rows; ++h) { for (int w = 0; w < cv_img1.cols; ++w) { datum_string->push_back(static_cast<char>(cv_img1.at<cv::Vec3b>(h, w)[c])); } } } for (int c = 0; c < num_channels/2; ++c) { for (int h = 0; h < cv_img2.rows; ++h) { for (int w = 0; w < cv_img2.cols; ++w) { datum_string->push_back(static_cast<char>(cv_img2.at<cv::Vec3b>(h, w)[c])); } } } } else { // Faster than repeatedly testing is_color for each pixel w/i loop for (int h = 0; h < cv_img1.rows; ++h) { for (int w = 0; w < cv_img1.cols; ++w) { datum_string->push_back(static_cast<char>(cv_img1.at<uchar>(h, w))); } } for (int h = 0; h < cv_img2.rows; ++h) { for (int w = 0; w < cv_img2.cols; ++w) { datum_string->push_back(static_cast<char>(cv_img2.at<uchar>(h, w))); } } } return true; } int main(int argc, char** argv) { ::google::InitGoogleLogging(argv[0]); #ifndef GFLAGS_GFLAGS_H_ namespace gflags = google; #endif gflags::SetUsageMessage("Convert a set of images to the leveldb/lmdb\n" "format used as input for Caffe.\n" "Usage:\n" " convert_imageset [FLAGS] ROOTFOLDER/ LISTFILE DB_NAME\n" "The ImageNet dataset for the training demo is at\n" " http://www.image-net.org/download-images\n"); gflags::ParseCommandLineFlags(&argc, &argv, true); if (argc != 4) { gflags::ShowUsageWithFlagsRestrict(argv[0], "tools/convert_imageset"); return 1; } bool is_color = !FLAGS_gray; std::ifstream infile(argv[2]); // std::vector<std::pair<string, int> > lines; std::vector<std::pair<std::pair<string, string>, int> > lines; string filename1; string filename2; int label; while (infile >> filename1 >> filename2 >> label) { lines.push_back(std::make_pair(std::make_pair(filename1, filename2), label)); } if (FLAGS_shuffle) { // randomly shuffle data LOG(INFO) << "Shuffling data"; shuffle(lines.begin(), lines.end()); } LOG(INFO) << "A total of " << lines.size() << " images."; const string& db_backend = FLAGS_backend; const char* db_path = argv[3]; int resize_height = std::max<int>(0, FLAGS_resize_height); int resize_width = std::max<int>(0, FLAGS_resize_width); // Open new db // lmdb MDB_env *mdb_env; MDB_dbi mdb_dbi; MDB_val mdb_key, mdb_data; MDB_txn *mdb_txn; // leveldb leveldb::DB* db; leveldb::Options options; options.error_if_exists = true; options.create_if_missing = true; options.write_buffer_size = 268435456; leveldb::WriteBatch* batch = NULL; // Open db if (db_backend == "leveldb") { // leveldb LOG(INFO) << "Opening leveldb " << db_path; leveldb::Status status = leveldb::DB::Open( options, db_path, &db); CHECK(status.ok()) << "Failed to open leveldb " << db_path << ". Is it already existing?"; batch = new leveldb::WriteBatch(); } else if (db_backend == "lmdb") { // lmdb LOG(INFO) << "Opening lmdb " << db_path; CHECK_EQ(mkdir(db_path, 0744), 0) << "mkdir " << db_path << "failed"; CHECK_EQ(mdb_env_create(&mdb_env), MDB_SUCCESS) << "mdb_env_create failed"; CHECK_EQ(mdb_env_set_mapsize(mdb_env, 1099511627776), MDB_SUCCESS) // 1TB << "mdb_env_set_mapsize failed"; CHECK_EQ(mdb_env_open(mdb_env, db_path, 0, 0664), MDB_SUCCESS) << "mdb_env_open failed"; CHECK_EQ(mdb_txn_begin(mdb_env, NULL, 0, &mdb_txn), MDB_SUCCESS) << "mdb_txn_begin failed"; CHECK_EQ(mdb_open(mdb_txn, NULL, 0, &mdb_dbi), MDB_SUCCESS) << "mdb_open failed. Does the lmdb already exist? "; } else { LOG(FATAL) << "Unknown db backend " << db_backend; } // Storing to db string root_folder(argv[1]); Datum datum; int count = 0; const int kMaxKeyLength = 256; char key_cstr[kMaxKeyLength]; int data_size; bool data_size_initialized = false; for (int line_id = 0; line_id < lines.size(); ++line_id) { if (!ReadImageToDatum(root_folder + lines[line_id].first.first, root_folder + lines[line_id].first.second, lines[line_id].second, resize_height, resize_width, is_color, &datum)) { continue; } if (!data_size_initialized) { data_size = datum.channels() * datum.height() * datum.width(); data_size_initialized = true; } else { const string& data = datum.data(); CHECK_EQ(data.size(), data_size) << "Incorrect data field size " << data.size(); } // sequential snprintf(key_cstr, kMaxKeyLength, "%08d_%s", line_id, (lines[line_id].first.first + lines[line_id].first.second).c_str()); string value; datum.SerializeToString(&value); string keystr(key_cstr); // Put in db if (db_backend == "leveldb") { // leveldb batch->Put(keystr, value); } else if (db_backend == "lmdb") { // lmdb mdb_data.mv_size = value.size(); mdb_data.mv_data = reinterpret_cast<void*>(&value[0]); mdb_key.mv_size = keystr.size(); mdb_key.mv_data = reinterpret_cast<void*>(&keystr[0]); CHECK_EQ(mdb_put(mdb_txn, mdb_dbi, &mdb_key, &mdb_data, 0), MDB_SUCCESS) << "mdb_put failed"; } else { LOG(FATAL) << "Unknown db backend " << db_backend; } if (++count % 1000 == 0) { // Commit txn if (db_backend == "leveldb") { // leveldb db->Write(leveldb::WriteOptions(), batch); delete batch; batch = new leveldb::WriteBatch(); } else if (db_backend == "lmdb") { // lmdb CHECK_EQ(mdb_txn_commit(mdb_txn), MDB_SUCCESS) << "mdb_txn_commit failed"; CHECK_EQ(mdb_txn_begin(mdb_env, NULL, 0, &mdb_txn), MDB_SUCCESS) << "mdb_txn_begin failed"; } else { LOG(FATAL) << "Unknown db backend " << db_backend; } LOG(ERROR) << "Processed " << count << " files."; } } // write the last batch if (count % 1000 != 0) { if (db_backend == "leveldb") { // leveldb db->Write(leveldb::WriteOptions(), batch); delete batch; delete db; } else if (db_backend == "lmdb") { // lmdb CHECK_EQ(mdb_txn_commit(mdb_txn), MDB_SUCCESS) << "mdb_txn_commit failed"; mdb_close(mdb_env, mdb_dbi); mdb_env_close(mdb_env); } else { LOG(FATAL) << "Unknown db backend " << db_backend; } LOG(ERROR) << "Processed " << count << " files."; } return 0; }
// Lingor hangars class land_ibr_hangar : House { model = "\ibr\ibr_hangars\ibr_hangar"; scope = 2; vehicleClass = "ibr_hangars"; transportFuel = 0; transportRepair = 0; icon = "\ibr\ibr_hangars\icons\icon5.paa"; mapSize = 40; displayName = "House"; destrType = "DestructBuilding"; armor = 1200; };
#include <string> #include <iostream> #include <map> #include <math.h> #include <stdexcept> // std::invalid_argument #include <string> #include <sstream> #define SSTR( x ) dynamic_cast< std::ostringstream & >( \ (std::ostringstream() << std::dec << x)).str() std::pair<int,int> * ParElem(std::string elem) { unsigned key = 0; unsigned value = 0; auto i = elem.find("x"); if (i == std::string::npos) { if (elem.size() != 0) value = std::stoi( elem ); else value = 0; } else if (i == 0) { if (elem[1] == '^'){ value = 1; key = std::stoi( elem.substr(i + 2)); } else { value = 1; key = 1; } } else { if (i == 1 && elem[0] == '-') value = 1; else value = std::stoi( elem.substr(0, i-1)); if (i + 2 <= elem.size()) key = std::stoi( elem.substr(i + 2)); else key = 1; } value *= key; --key; return new std::pair<int,int>(key,value); } std::string printProizv(std::map<int,int>& dictionary) { std::string* result = new std::string(); bool noOut = true; ///����� ���� ������������������ map �� ����� for (auto it = dictionary.rbegin(); it != dictionary.rend(); ++it) { if(it->second == 0) continue; (*result) += (it->second < 0 ? "" : (noOut?"":"+")) + (abs(it->second) == 1 ? (it->first > 0?(it->second < 0? "-":""):std::to_string(it->second)) : std::to_string(it->second)) + (it->first > 0?("*x" + (it->first > 1?"^" + std::to_string(it->first):"")):""); noOut = false; } if (noOut) (*result) += "0"; return (*result); } std::string derivative(std::string polynomial) { if (polynomial.size() < -20){ // throw *(new std::invalid_argument(polynomial.c_str())); } int currInd = 0; std::map<int,int> dict; for (int i = 0; i <= polynomial.size(); ++i){ if(polynomial[i] == '+' || polynomial[i] == '-' || i == polynomial.length()) { auto elem = polynomial.substr(currInd, (i - currInd)); auto pair = ParElem(elem); if (pair->first < 0) continue; if (dict.count(pair->first) > 0) dict[pair->first] += (polynomial[currInd == 0 ? 0 :currInd-1] == '-' ? -1: 1)*pair->second; else{ if(polynomial[currInd == 0 ? 0 :currInd-1] == '-') pair->second = -1*pair->second; dict.insert(*pair); } currInd = i + 1; } } return printProizv(dict); } int main1 (int argc, char **argv) { std::cout << derivative("10*x-9*x"); std::cout << std::endl; system("pause"); return 0; }
#include<bits/stdc++.h> using namespace std; int cnt1[10]; int cnt2[10]; int cnt[10]; int main() { memset(cnt1,0,sizeof(cnt1)); memset(cnt2,0,sizeof(cnt2)); memset(cnt,0,sizeof(cnt)); int n; cin>>n; for(int i=0; i<n; i++) { int x; cin>>x; cnt1[x]++; cnt[x]++; } for(int i=0; i<n; i++) { int x; cin>>x; cnt2[x]++; cnt[x]++; } bool flag=true; for(int i=1; i<=5; i++) { if(cnt[i]%2!=0) { flag=false; break; } } if(!flag) { cout<<"-1\n"; return 0; } int ans1=0; int ans2=0; int ans=0; for(int i=0; i<=5; i++) { if(cnt1[i]>cnt2[i]) { ans1+=cnt1[i]-cnt2[i]; } else if(cnt1[i]<cnt2[i]) ans2+=cnt2[i]-cnt1[i]; } if(ans1!=ans2) { cout<<"-1\n"; return 0; } ans=ans1/2; cout<<ans<<"\n"; return 0; }
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_COMPILER_TF2TENSORRT_SEGMENT_UNION_FIND_H_ #define TENSORFLOW_COMPILER_TF2TENSORRT_SEGMENT_UNION_FIND_H_ #include "absl/types/optional.h" #include "tensorflow/core/util/device_name_utils.h" #if GOOGLE_CUDA && GOOGLE_TENSORRT namespace tensorflow { namespace tensorrt { namespace segment { // ClusterBatchSize is a data structure to record the batch size we have seen // for a cluster during segmentation. // // When constructing clusters for implicit batch mode, we support the // with both dynamic batch size and static batch size. We restrict nodes inside // a cluster to either have dynamic batch size or have the same value for static // batch size. For this reason, we use a field has_dynamic_batch_size_ to keep // track of whether the cluster has any node with dynamic batch size. We use // field static_batch_size_ to keep track of whether the cluster has any node // with static batch size and what the value of the static batch size, if any. // Examples: // cluster: a = a1[1,3] + a1[1,3] // ClusterBatchSize: has_dynamic_batch_size_ = false // static_batch_size_ = {has value, 1} // // cluster: b = b1[-1,3] + b2[-1, 3] // ClusterBatchSize: has_dynamic_batch_size_ = true // static_batch_size_ = {has no value} // // cluster: a = a1[1,3] + a1[1,3]; b = b1[-1,3] + b2[-1, 3] // ClusterBatchSize: has_dynamic_batch_size_ = true // static_batch_size_ = {has value, 1} // // When constructing cluster for explicit batch mode, all ClusterBatchSize is // irrelevant. // // class ClusterBatchSize { public: ClusterBatchSize(); bool operator==(const ClusterBatchSize& other); bool operator!=(const ClusterBatchSize& other) { return !(*this == other); } // Sets the batch size assuming that the object doesn't have a batch size yet: // a non-negative input value representing a static batch size. // a negative input value representing a dynamic batch size. ClusterBatchSize& SetBatchSize(int batch_size); bool HasStaticBatchSize() const { return static_batch_size_.has_value(); } int GetStaticBatchSize() const; bool MergeIfCompatible(const ClusterBatchSize& other); // Returns a string for the batch size. // If the object has a static batch size, return a string for the value. // If the object has a dynamic size, return -1. // Otherwise, returns -2 to represent that the batch size hasn't been set // yet. std::string ToString() const; private: bool HasDynamicBatchSize() const { return has_dynamic_batch_size_; } // To track whether the cluster has any node with dynamic batch size. bool has_dynamic_batch_size_; // To track whether the cluster has any node with static batch size, and the // unique value for static batch size. absl::optional<int> static_batch_size_; }; inline std::ostream& operator<<(std::ostream& os, const ClusterBatchSize& batch_size) { return os << batch_size.ToString(); } // Represents the accumulated properties of a cluster during segmentation, // including information about batch size and device assignment. Clusters shall // have compatible properties in order to be merged together. class ClusterProperty { public: ClusterProperty() {} ClusterProperty(const ClusterBatchSize& batch_size, const DeviceNameUtils::ParsedName& device_name); // Returns the batch size of the cluster and compresses the path from this // object to the root object. const ClusterBatchSize& BatchSize() const { return batch_size_; } // Returns the device name of the cluster and compresses the path from this // object to the root object. const DeviceNameUtils::ParsedName& DeviceName() const { return device_name_; } Status Merge(const ClusterProperty& other); private: ClusterBatchSize batch_size_; DeviceNameUtils::ParsedName device_name_; }; // Represents a disjoint set of copyable value with type T and accumulated // property of the values with type P. Most of the methods in this class are // side-effecting as they also compress the path from the object to the parent // of its containing set. template <typename T, typename P = ClusterProperty> class UnionFind { public: UnionFind() : size_(1), parent_(nullptr) {} UnionFind(const T& v, const P& p) : size_(1), parent_(nullptr), value_(v), property_(p) {} UnionFind(const T& v, P&& p) : size_(1), parent_(nullptr), value_(v), property_(p) {} // Returns the number of elements in the set and compresses the path from // this object to the root of the set. int Size() { return FindRoot()->size_; } // Returns the accumulated property of all the elements in the set and // compresses the path from this object to the root of the set. const P& Property() { return FindRoot()->property_; } // Merges this set with 'other'. This updates the size_ and property_ of the // set. The size_ and property_ of 'other' becomes inaccessible as only the // size_ and property_ of the root of the set is accessible. Status Merge(UnionFind* other); // Retrieves the value for the root of the set. const T& ParentValue() { return FindRoot()->value_; } // Returns the value for the object. const T& Value() const { return value_; } private: // Returns the root object for the set and compresses the path from this // object to the root object. UnionFind* FindRoot(); int size_; UnionFind* parent_; T value_; P property_; }; template <typename T, typename P> Status UnionFind<T, P>::Merge(UnionFind* other) { UnionFind<T>* a = FindRoot(); UnionFind<T>* b = other->FindRoot(); if (a == b) return Status::OK(); P merged_property(a->property_); TF_RETURN_IF_ERROR(merged_property.Merge(b->property_)); b->parent_ = a; a->size_ += b->size_; a->property_ = std::move(merged_property); return Status::OK(); } template <typename T, typename P> UnionFind<T, P>* UnionFind<T, P>::FindRoot() { if (!parent_) return this; // Path compression: update intermediate nodes to point to the root of the // equivalence class. parent_ = parent_->FindRoot(); return parent_; } } // namespace segment } // namespace tensorrt } // namespace tensorflow #endif // GOOGLE_CUDA && GOOGLE_TENSORRT #endif // TENSORFLOW_COMPILER_TF2TENSORRT_SEGMENT_UNION_FIND_H_
#include <functional> #include <mutex> using namespace std; /* 本题固定有5个哲学家,多个线程共享一个实例对象,会抢着调用同一个实例对象的wantsToEat方法 大部分C++/Java解法都是使用Semaphore API,类似Mutex 我注意到Rust的Semaphore Deprecated since 1.7.0: easily confused with system sempahores and not used enough to pull its weight 而且Rust官方教程中的哲学家问题就是通过将Mutex去解决哲学家进餐问题的,所以我也用Mutex了 */ class DiningPhilosophers { public: static mutex forks[5]; static void wantsToEat( int philosopher, function<void()> pickLeftFork, function<void()> pickRightFork, function<void()> eat, function<void()> putLeftFork, function<void()> putRightFork ) { int left_fork = philosopher; int right_fork = (philosopher + 1) % 5; forks[left_fork].lock(); forks[right_fork].lock(); pickLeftFork(); pickRightFork(); eat(); putLeftFork(); putRightFork(); forks[left_fork].unlock(); forks[right_fork].unlock(); } }; int main() { return 0; }
#include <algorithm> #include <cstring> #include <climits> #include <functional> #include <iostream> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <vector> #include <sstream> #include <unordered_map> #include "../utils/VectorUtils.hpp" #include "../utils/PrintUtils.hpp" // #include "../utils/HeapUtils.hpp" // #include "../utils/BinarySearch.hpp" // #include "../utils/TreeUtils.hpp" // https://leetcode.com/problems/buddy-strings/ using namespace std; #pragma GCC diagnostic ignored "-Wunknown-pragmas" // Live coding problems, watch at // https://www.twitch.tv/yipcubed // https://www.youtube.com/channel/UCTV_UOPu7EWXvYWsBFxMsSA/videos // // makes code faster, but larger. Just for LeetCode fun! #pragma GCC optimise ("Ofast") // makes stdin not synced so it is faster. Just for LeetCode fun! static auto __ __attribute__((unused)) = []() { // NOLINT ios_base::sync_with_stdio(false); cin.tie(nullptr); return nullptr; }(); class Solution { public: bool buddyStrings(string A, string B) { if (A.empty() || B.empty() || A.length() != B.length()) return false; if (A == B) { for (char c: A) { if (count(A.begin(), A.end(), c) > 1) return true; } return false; } bool swap_started = false; bool swapped = false; char swapA, swapB; for (int i = 0; i < A.length(); ++i) { if (A[i] == B[i]) continue; if (swapped) return false; if (!swap_started) { swapA = A[i]; swapB = B[i]; swap_started = true; } else { if (A[i] != swapB || B[i] != swapA) return false; swapped = true; } } return swapped; } }; void test1() { cout << boolalpha; string A = "ab", B = "ba"; cout << "t ? " << Solution().buddyStrings(A, B) << endl; A = "ab", B = "ab"; cout << "f ? " << Solution().buddyStrings(A, B) << endl; A = "aa", B = "aa"; cout << "t ? " << Solution().buddyStrings(A, B) << endl; A = "aaaaaaabc", B = "aaaaaaacb"; cout << "t ? " << Solution().buddyStrings(A, B) << endl; A = "", B = "aa"; cout << "f ? " << Solution().buddyStrings(A, B) << endl; } void test2() { } void test3() { }
// // Created by manout on 18-4-9. // static int x, y; static unsigned long int dfs(int x_, int y_, int k) { if (x_ == x and y_ == y) return 1; if (x_ < 0 or x_ > 8 or y_ < 0 or y_ > 8 or k == 0) return 0; unsigned long int ans = 0; ans += dfs(x_ + 1, y_ + 2, k - 1); ans += dfs(x_ + 2, y_ + 1, k - 1); ans += dfs(x_ + 2, y_ - 1, k - 1); ans += dfs(x_ + 1, y_ - 2, k - 1); ans += dfs(x_ - 1, y_ - 2, k - 1); ans += dfs(x_ - 2, y_ - 1, k - 1); ans += dfs(x_ - 2, y_ + 1, k - 1); ans += dfs(x_ - 1, y_ + 2, k - 1); return ans; } unsigned long int horse_jump(int k, int x_, int y_) { x = x_; y = y_; return dfs(0, 0, k); }
#pragma once #include <vector> #include <string> #include <iostream> // tmp #include <llog/severity_type.hpp> #include <llog/argument.hpp> namespace llog { class Context { public: protected: Context * parent_; typedef std::vector<Context*> ChildListType; ChildListType childs_; std::string name_; std::string full_name_; SeverityType severity_; protected: void registerChild(Context * child) { //todo: synchronized childs_.push_back(child); } public: Context(const std::string& name, Context * parent = 0) : name_(name), full_name_(), parent_(parent), severity_(0) { if(parent_ != 0) { parent_->registerChild(this); full_name_ = parent->getFullName(); } full_name_.append("/"); full_name_.append(name_); } ~Context() { //todo: consider how to handle destruction } void setLoggingSeverity(const SeverityType severity) { severity_ = severity; } void setLoggingSeverityRecursive(const SeverityType severity) { severity_ = severity; for(ChildListType::iterator it = childs_.begin(); it != childs_.end(); it++) { (*it)->setLoggingSeverityRecursive(severity); } } bool isSeverityLogged(const SeverityType severity) { return severity <= severity_; } const std::string& getFullName() { return full_name_; } template<typename T> void log(const SeverityType severity, const char* name1, const Argument<T>& argument1) { if(isSeverityLogged(severity)) { // todo: dispatch to a backend instead std::cout << full_name_ << ":" << std::endl << " " << name1 << llog::to_string(argument1) << std::endl; } } }; }
// Created on: 2000-02-05 // Created by: data exchange team // Copyright (c) 2000-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 _IGESControl_IGESBoundary_HeaderFile #define _IGESControl_IGESBoundary_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <IGESToBRep_IGESBoundary.hxx> #include <IGESData_HArray1OfIGESEntity.hxx> #include <Standard_Integer.hxx> class IGESToBRep_CurveAndSurface; class IGESData_IGESEntity; class ShapeExtend_WireData; class IGESControl_IGESBoundary; DEFINE_STANDARD_HANDLE(IGESControl_IGESBoundary, IGESToBRep_IGESBoundary) //! Translates IGES boundary entity (types 141, 142 and 508) //! in Advanced Data Exchange. //! Redefines translation and treatment methods from inherited //! open class IGESToBRep_IGESBoundary. class IGESControl_IGESBoundary : public IGESToBRep_IGESBoundary { public: //! Creates an object and calls inherited constructor. Standard_EXPORT IGESControl_IGESBoundary(); //! Creates an object and calls inherited constructor. Standard_EXPORT IGESControl_IGESBoundary(const IGESToBRep_CurveAndSurface& CS); //! Checks result of translation of IGES boundary entities //! (types 141, 142 or 508). //! Checks consistency of 2D and 3D representations and keeps //! only one if they are inconsistent. //! Checks the closure of resulting wire and if it is not closed, //! checks 2D and 3D representation and updates the resulting //! wire to contain only closed representation. Standard_EXPORT virtual void Check (const Standard_Boolean result, const Standard_Boolean checkclosure, const Standard_Boolean okCurve3d, const Standard_Boolean okCurve2d) Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(IGESControl_IGESBoundary,IGESToBRep_IGESBoundary) protected: Standard_EXPORT virtual Standard_Boolean Transfer (Standard_Boolean& okCurve, Standard_Boolean& okCurve3d, Standard_Boolean& okCurve2d, const Handle(IGESData_IGESEntity)& icurve3d, const Handle(ShapeExtend_WireData)& scurve3d, const Standard_Boolean usescurve, const Standard_Boolean toreverse3d, const Handle(IGESData_HArray1OfIGESEntity)& curves2d, const Standard_Boolean toreverse2d, const Standard_Integer number, Handle(ShapeExtend_WireData)& lsewd) Standard_OVERRIDE; }; #endif // _IGESControl_IGESBoundary_HeaderFile
/****************************************************************************** * * * Copyright 2018 Jan Henrik Weinstock * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * ******************************************************************************/ #ifndef VCML_AIO_H #define VCML_AIO_H #include <functional> namespace vcml { enum aio_policy { AIO_ONCE, AIO_ALWAYS }; typedef std::function<void(int, int)> aio_handler; void aio_notify(int fd, aio_handler handler, aio_policy policy); void aio_cancel(int fd); } #endif
#include <string> #include <vector> #include <filesystem> #include <boost/process.hpp> #include <deco/all.h>
#include <iostream> #include <iterator> #include "PuzzleArea.h" #include "Item.h" #include "SDLobsluga.h" #include <string> Item::Item(){ } void Item::ChangeImage(int id,bool OnOff) { switch (id) { case 1: SDL_RenderSetViewport(Obraz, &Slot1); break; case 2: SDL_RenderSetViewport(Obraz, &Slot2); break; case 3: SDL_RenderSetViewport(Obraz, &Slot3); break; case 4: SDL_RenderSetViewport(Obraz, &Slot4); break; case 5: SDL_RenderSetViewport(Obraz, &Slot5); break; case 6: SDL_RenderSetViewport(Obraz, &Slot6); break; } if (OnOff == true) { ObecnyObraz = Przedmioty[id -1]; } else { ObecnyObraz = Przedmioty[6]; } SDL_RenderCopy(Obraz, ObecnyObraz, NULL, NULL); SDL_RenderPresent(Obraz); SDL_RenderSetViewport(Obraz, &mainview); return; } void Item::PickUp(int id,Ekwipunek* equipment) { equipment->inside.push_back(new Item(id)); ChangeImage(id,true); return; } bool Item::Use(Ekwipunek* equipment, int given_id){ std::vector<Item*>::iterator it; it = equipment->inside.begin(); do { if (given_id == (*it)->id) { } it++; } while (it != equipment->inside.end()); return false; } void Item::Remove(Ekwipunek* equipment, int given_id) { std::vector<Item*>::iterator it; bool odp; do{ it = equipment->inside.begin(); if (given_id == (*it)->id) { equipment->inside.erase(it); it = equipment->inside.end(); ChangeImage(given_id, false); odp = true; } else { it++; } } while (it != equipment->inside.end()||odp!=true); return; } Item::Item(int nr) { id = nr; }
// https://www.codechef.com/viewsolution/23658836 #include <bits/stdc++.h> #define FAST ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); typedef long long ll; typedef long double ld; using namespace std; bool comp(vector<pair<ll,ll>> a,vector<pair<ll,ll>> b) { if(a.size()>b.size()) return 1; return 0; } int main() { FAST/**/ ll t; cin>>t; while(t--) { ll n; cin>>n; ll arr[n]; for(ll i=0;i<n;i++) cin>>arr[i]; unordered_map<ll,ll> ma; ll ind = 0; for(ll i=0;i<n;i++) ma[arr[i]] = -1; for(ll i=0;i<n;i++) { if(ma[arr[i]] == -1) { ma[arr[i]] = ind; ind++; } } vector<pair<ll,ll>> v[ma.size()]; for(ll i=0;i<n;i++) { ll j = ma[arr[i]]; v[j].push_back(make_pair(arr[i], i)); } sort(v, v+ma.size(), comp); ll siz = ma.size(); if(v[0].size()>n/2) { cout<<"No"<<"\n"; continue; } cout<<"Yes"<<"\n"; vector<pair<ll,ll>> aux; for(ll i=0;i<siz;i++) for(auto it = v[i].begin();it!=v[i].end();it++) aux.push_back(*it); ll final[n]; for(ll cp = 0;cp<n;cp++) { ll temp = v[0].size(); ll ind1 = aux[cp].second; ll ind2 = aux[(cp + temp)%n].second; final[ind1] = arr[ind2]; } for(ll i=0;i<n;i++) cout<<final[i]<<" "; cout<<"\n"; } return 0; }
#include <iostream> using namespace std; int req[] = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6}; int getSticks(int x) { int sticks = 0, rem; while (x) { rem = x % 10; x = x / 10; sticks += req[rem]; } return sticks; } int main() { int a, b, t; cin >> t; while (t--) { cin >> a >> b; cout << getSticks(a + b) << endl; } }
/** \file Kick.hpp \author UnBeatables \date LARC2018 \name Kick */ #pragma once /* * Kick inherited from BehaviorBase. */ #include <BehaviorBase.hpp> /** \brief This class is responsable for robot`s kick behavior. */ class Kick : public BehaviorBase { private: static Kick *instance; int finished; bool isKickable; bool isLeft; int oldBallX, oldBallY; int lostCount; bool lastMoveFinished; int kickBallX; int countOnce; int ticksCount; public: /** \brief Class constructor. \details Inicialize class parameters. */ Kick(); /** \brief Sets Kick as current instance. \return Current instance. */ static BehaviorBase* Behavior(); /** \brief This function determines Kick transition. \details Transitions to postKick when robot finishes kick behavior. \param _ub void pointer for UnBoard. \return Transition state. */ BehaviorBase* transition(void*); /** \brief This function is responsable for robot`s kick behavior. \details The commands will make robot get close and align with the ball, ajusting head pitch and using bottom camera for ball center coordinates, will turn right eyes leds yellow (state leds) and will kick ball after chosing wich leg to use (aparently just left leg is active). \param _ub void pointer for UnBoard. */ void action(void*); };
// Created on: 2006-05-26 // Created by: Alexander GRIGORIEV // Copyright (c) 2006-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 VrmlData_IndexedFaceSet_HeaderFile #define VrmlData_IndexedFaceSet_HeaderFile #include <VrmlData_Faceted.hxx> #include <VrmlData_Coordinate.hxx> #include <VrmlData_Normal.hxx> #include <VrmlData_Color.hxx> #include <VrmlData_TextureCoordinate.hxx> #include <gp_XYZ.hxx> #include <Quantity_Color.hxx> /** * Implementation of IndexedFaceSet node */ class VrmlData_IndexedFaceSet : public VrmlData_Faceted { public: // ---------- PUBLIC METHODS ---------- /** * Empty constructor */ inline VrmlData_IndexedFaceSet () : myArrPolygons (0L), myArrNormalInd (0L), myArrColorInd (0L), myArrTextureInd (0L), myNbPolygons (0), myNbNormals (0), myNbColors (0), myNbTextures (0), myNormalPerVertex (Standard_True), myColorPerVertex (Standard_True) {} /** * Constructor */ inline VrmlData_IndexedFaceSet (const VrmlData_Scene& theScene, const char * theName, const Standard_Boolean isCCW =Standard_True, const Standard_Boolean isSolid =Standard_True, const Standard_Boolean isConvex=Standard_True, const Standard_Real theCreaseAngle = 0.) : VrmlData_Faceted (theScene, theName, isCCW, isSolid, isConvex, theCreaseAngle), myArrPolygons (0L), myArrNormalInd (0L), myArrColorInd (0L), myArrTextureInd (0L), myNbPolygons (0), myNbNormals (0), myNbColors (0), myNbTextures (0), myNormalPerVertex (Standard_True), myColorPerVertex (Standard_True) {} /** * Query the Normals. */ inline const Handle(VrmlData_Normal)& Normals () const { return myNormals; } /** * Query the Colors. */ inline const Handle(VrmlData_Color)& Colors () const { return myColors; } /** * Query the Texture Coordinates. */ inline const Handle(VrmlData_TextureCoordinate)& TextureCoords () const { return myTxCoords; } // ======================================================================== // =========================== TRIANGULATION GRID ========================= /** * Query the Coordinates. */ inline const Handle(VrmlData_Coordinate)& Coordinates () const { return myCoords; } /** * Query the array of polygons */ inline size_t Polygons (const Standard_Integer**& arrPolygons) const { arrPolygons = myArrPolygons; return myNbPolygons; } /** * Query one polygon. * @param iFace * rank of the polygon [0 .. N-1] * @param outIndice * <tt>[out]</tt> array of vertex indice * @return * number of vertice in the polygon - the dimension of outIndice array */ inline Standard_Integer Polygon (const Standard_Integer iFace, const Standard_Integer *& outIndice) { return * (outIndice = myArrPolygons[iFace])++; } /** * Set the nodes */ inline void SetCoordinates (const Handle(VrmlData_Coordinate)& theCoord) { myCoords = theCoord; } /** * Set the polygons */ inline void SetPolygons (const Standard_Size nPolygons, const Standard_Integer ** thePolygons) { myNbPolygons = nPolygons; myArrPolygons = thePolygons; } // ======================================================================== // ================================ NORMALS =============================== /** * Query the array of normal indice * @param arrNormalInd * <tt>[out]</tt> array of normalIndex as it is described in VRML2.0 spec * @return * Number of integers in the array arrNormalInd. */ inline size_t ArrayNormalInd (const Standard_Integer**& arrNormalInd) const { arrNormalInd = myArrNormalInd; return myNbNormals; } /** * Query normals indice for one face. This method should be called after * checking myArrNormalInd != NULL, otherwise exception will be thrown. * @param iFace * rank of the face [0 .. N-1] * @param outIndice * <tt>[out]</tt> array of normals indice * @return * number of indice in the array - the dimension of outIndice array */ inline Standard_Integer IndiceNormals (const Standard_Integer iFace, const Standard_Integer *& outIndice) { return * (outIndice = myArrNormalInd[iFace])++; } /** * Query a normal for one node in the given element. The normal is * interpreted according to fields myNormals, myArrNormalInd, * myNormalPerVertex, as defined in VRML 2.0. * @param iFace * rank of the polygon [0 .. N-1] * @param iVertex * rank of the vertex in the polygon [0 .. M-1]. This parameter is ignored * if (myNormalPerVertex == False) * @return * Normal vector; if the normal is indefinite then returns (0., 0., 0.) */ Standard_EXPORT gp_XYZ GetNormal (const Standard_Integer iFace, const Standard_Integer iVertex); /** * Set the normals array of indice */ inline void SetNormalInd (const Standard_Size nIndice, const Standard_Integer ** theIndice) { myNbNormals = nIndice; myArrNormalInd = theIndice; } /** * Set the normals node */ inline void SetNormals (const Handle(VrmlData_Normal)& theNormals) { myNormals = theNormals; } /** * Set the boolean value "normalPerVertex" */ inline void SetNormalPerVertex (const Standard_Boolean isNormalPerVertex) { myNormalPerVertex = isNormalPerVertex; } // ======================================================================== // ================================ COLORS ================================ /** * Query the array of color indice * @param arrColorInd * <tt>[out]</tt> array of colorIndex as it is described in VRML2.0 spec * @return * Number of integers in the array arrColorInd. */ inline size_t ArrayColorInd (const Standard_Integer**& arrColorInd) const { arrColorInd = myArrColorInd; return myNbColors; } /** * Query a color for one node in the given element. The color is * interpreted according to fields myColors, myArrColorInd, * myColorPerVertex, as defined in VRML 2.0. * @param iFace * rank of the polygon [0 .. N-1] * @param iVertex * rank of the vertex in the polygon [0 .. M-1]. This parameter is ignored * if (myColorPerVertex == False) * @return * Color value (RGB); if the color is indefinite then returns (0., 0., 0.) */ Standard_EXPORT Quantity_Color GetColor (const Standard_Integer iFace, const Standard_Integer iVertex); /** * Set the colors array of indice */ inline void SetColorInd (const Standard_Size nIndice, const Standard_Integer ** theIndice) { myNbColors = nIndice; myArrColorInd = theIndice; } /** * Set the Color node */ inline void SetColors (const Handle(VrmlData_Color)& theColors) { myColors = theColors; } /** * Set the boolean value "colorPerVertex" */ inline void SetColorPerVertex (const Standard_Boolean isColorPerVertex) { myColorPerVertex = isColorPerVertex; } // ======================================================================== // ========================== TEXTURE COIRDINATES ========================= /** * Query the array of texture coordinate indice * @param arrTextureCoordInd * <tt>[out]</tt> array of texCoordIndex as it is described in VRML2.0 spec * @return * Number of integers in the array texCoordIndex. */ inline size_t ArrayTextureCoordInd (const Standard_Integer**& arrTextureCoordInd) const { arrTextureCoordInd = myArrTextureInd; return myNbTextures; } /** * Set the TexCoordiante array of indice */ inline void SetTextureCoordInd (const Standard_Size nIndice, const Standard_Integer ** theIndice) { myNbTextures = nIndice; myArrTextureInd = theIndice; } /** * Set the Texture Coordinate node */ inline void SetTextureCoords(const Handle(VrmlData_TextureCoordinate)& tc) { myTxCoords = tc; } /** * Query the shape. This method checks the flag myIsModified; if True it * should rebuild the shape presentation. */ Standard_EXPORT virtual const Handle(TopoDS_TShape)& TShape () Standard_OVERRIDE; /** * Create a copy of this node. * If the parameter is null, a new copied node is created. Otherwise new node * is not created, but rather the given one is modified. */ Standard_EXPORT virtual Handle(VrmlData_Node) Clone (const Handle(VrmlData_Node)& theOther)const Standard_OVERRIDE; /** * Read the Node from input stream. */ Standard_EXPORT virtual VrmlData_ErrorStatus Read (VrmlData_InBuffer& theBuffer) Standard_OVERRIDE; /** * Write the Node to output stream. */ Standard_EXPORT virtual VrmlData_ErrorStatus Write (const char * thePrefix) const Standard_OVERRIDE; /** * Returns True if the node is default, so that it should not be written. */ Standard_EXPORT virtual Standard_Boolean IsDefault () const Standard_OVERRIDE; protected: // ---------- PROTECTED METHODS ---------- // /** // * If the normals are not defined, here we compute them from the polygons. // * @param theArray // * Array of float values having length:<ul> // * <li>if myNormalPerVertex==TRUE : 3 * myCoords->Length()</li> // * <li>if myNormalPerVertex==FALSE: 9 * number_of_triangles </li> // * </ul> // */ // Standard_EXPORT void // computeNormals (Standard_ShortReal * theArray); private: // ---------- PRIVATE FIELDS ---------- Handle(VrmlData_Coordinate) myCoords; Handle(VrmlData_Normal) myNormals; Handle(VrmlData_Color) myColors; Handle(VrmlData_TextureCoordinate) myTxCoords; const Standard_Integer ** myArrPolygons; const Standard_Integer ** myArrNormalInd; const Standard_Integer ** myArrColorInd; const Standard_Integer ** myArrTextureInd; Standard_Size myNbPolygons; Standard_Size myNbNormals; Standard_Size myNbColors; Standard_Size myNbTextures; Standard_Boolean myNormalPerVertex; Standard_Boolean myColorPerVertex; public: // Declaration of CASCADE RTTI DEFINE_STANDARD_RTTIEXT(VrmlData_IndexedFaceSet,VrmlData_Faceted) }; // Definition of HANDLE object using Standard_DefineHandle.hxx DEFINE_STANDARD_HANDLE (VrmlData_IndexedFaceSet, VrmlData_Faceted) #endif
#ifndef __GAME_WORLDSPAWN_H__ #define __GAME_WORLDSPAWN_H__ /* =============================================================================== World entity. =============================================================================== */ class idWorldspawn : public idEntity { public: CLASS_PROTOTYPE( idWorldspawn ); ~idWorldspawn(); void Spawn( void ); void Save( idRestoreGame *savefile ); void Restore( idRestoreGame *savefile ); private: void Event_Remove( void ); }; #endif /* !__GAME_WORLDSPAWN_H__ */
/******************************************************************************** ** Form generated from reading UI file 'networkaccessviewer.ui' ** ** Created: Tue Mar 8 09:41:16 2011 ** by: Qt User Interface Compiler version 4.7.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_NETWORKACCESSVIEWER_H #define UI_NETWORKACCESSVIEWER_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QHeaderView> #include <QtGui/QLabel> #include <QtGui/QPlainTextEdit> #include <QtGui/QPushButton> #include <QtGui/QTreeWidget> #include <QtGui/QWidget> QT_BEGIN_NAMESPACE class Ui_NetworkAccessViewer { public: QTreeWidget *responseDetails; QTreeWidget *requestDetails; QLabel *label_2; QLabel *label; QTreeWidget *requestList; QPushButton *clearButton; QLabel *label_3; QPlainTextEdit *textEditResponseData; void setupUi(QWidget *NetworkAccessViewer) { if (NetworkAccessViewer->objectName().isEmpty()) NetworkAccessViewer->setObjectName(QString::fromUtf8("NetworkAccessViewer")); NetworkAccessViewer->resize(912, 534); responseDetails = new QTreeWidget(NetworkAccessViewer); responseDetails->setObjectName(QString::fromUtf8("responseDetails")); responseDetails->setGeometry(QRect(360, 281, 256, 217)); requestDetails = new QTreeWidget(NetworkAccessViewer); requestDetails->setObjectName(QString::fromUtf8("requestDetails")); requestDetails->setGeometry(QRect(13, 281, 341, 217)); label_2 = new QLabel(NetworkAccessViewer); label_2->setObjectName(QString::fromUtf8("label_2")); label_2->setGeometry(QRect(13, 262, 341, 13)); label = new QLabel(NetworkAccessViewer); label->setObjectName(QString::fromUtf8("label")); label->setGeometry(QRect(13, 10, 341, 23)); requestList = new QTreeWidget(NetworkAccessViewer); requestList->setObjectName(QString::fromUtf8("requestList")); requestList->setGeometry(QRect(13, 39, 891, 217)); requestList->setAlternatingRowColors(true); requestList->setRootIsDecorated(false); clearButton = new QPushButton(NetworkAccessViewer); clearButton->setObjectName(QString::fromUtf8("clearButton")); clearButton->setGeometry(QRect(491, 10, 125, 23)); label_3 = new QLabel(NetworkAccessViewer); label_3->setObjectName(QString::fromUtf8("label_3")); label_3->setGeometry(QRect(360, 262, 125, 13)); textEditResponseData = new QPlainTextEdit(NetworkAccessViewer); textEditResponseData->setObjectName(QString::fromUtf8("textEditResponseData")); textEditResponseData->setGeometry(QRect(620, 280, 281, 221)); retranslateUi(NetworkAccessViewer); QMetaObject::connectSlotsByName(NetworkAccessViewer); } // setupUi void retranslateUi(QWidget *NetworkAccessViewer) { NetworkAccessViewer->setWindowTitle(QApplication::translate("NetworkAccessViewer", "NetworkAccessViewer", 0, QApplication::UnicodeUTF8)); QTreeWidgetItem *___qtreewidgetitem = responseDetails->headerItem(); ___qtreewidgetitem->setText(1, QApplication::translate("NetworkAccessViewer", "Value", 0, QApplication::UnicodeUTF8)); ___qtreewidgetitem->setText(0, QApplication::translate("NetworkAccessViewer", "Name", 0, QApplication::UnicodeUTF8)); QTreeWidgetItem *___qtreewidgetitem1 = requestDetails->headerItem(); ___qtreewidgetitem1->setText(1, QApplication::translate("NetworkAccessViewer", "Value", 0, QApplication::UnicodeUTF8)); ___qtreewidgetitem1->setText(0, QApplication::translate("NetworkAccessViewer", "Name", 0, QApplication::UnicodeUTF8)); label_2->setText(QApplication::translate("NetworkAccessViewer", "Request Details", 0, QApplication::UnicodeUTF8)); label->setText(QApplication::translate("NetworkAccessViewer", "Network Requests", 0, QApplication::UnicodeUTF8)); QTreeWidgetItem *___qtreewidgetitem2 = requestList->headerItem(); ___qtreewidgetitem2->setText(5, QApplication::translate("NetworkAccessViewer", "Info", 0, QApplication::UnicodeUTF8)); ___qtreewidgetitem2->setText(4, QApplication::translate("NetworkAccessViewer", "Content Type", 0, QApplication::UnicodeUTF8)); ___qtreewidgetitem2->setText(3, QApplication::translate("NetworkAccessViewer", "Length", 0, QApplication::UnicodeUTF8)); ___qtreewidgetitem2->setText(2, QApplication::translate("NetworkAccessViewer", "Response", 0, QApplication::UnicodeUTF8)); ___qtreewidgetitem2->setText(1, QApplication::translate("NetworkAccessViewer", "URL", 0, QApplication::UnicodeUTF8)); ___qtreewidgetitem2->setText(0, QApplication::translate("NetworkAccessViewer", "Method", 0, QApplication::UnicodeUTF8)); clearButton->setText(QApplication::translate("NetworkAccessViewer", "&Clear", 0, QApplication::UnicodeUTF8)); label_3->setText(QApplication::translate("NetworkAccessViewer", "Response Details", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class NetworkAccessViewer: public Ui_NetworkAccessViewer {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_NETWORKACCESSVIEWER_H
// Created on: 1995-03-06 // Created by: Laurent PAINNOT // Copyright (c) 1995-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 _Poly_Connect_HeaderFile #define _Poly_Connect_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <TColStd_Array1OfInteger.hxx> #include <TColStd_PackedMapOfInteger.hxx> #include <Standard_Integer.hxx> #include <Standard_Boolean.hxx> class Poly_Triangulation; //! Provides an algorithm to explore, inside a triangulation, the //! adjacency data for a node or a triangle. //! Adjacency data for a node consists of triangles which //! contain the node. //! Adjacency data for a triangle consists of: //! - the 3 adjacent triangles which share an edge of the triangle, //! - and the 3 nodes which are the other nodes of these adjacent triangles. //! Example //! Inside a triangulation, a triangle T //! has nodes n1, n2 and n3. //! It has adjacent triangles AT1, AT2 and AT3 where: //! - AT1 shares the nodes n2 and n3, //! - AT2 shares the nodes n3 and n1, //! - AT3 shares the nodes n1 and n2. //! It has adjacent nodes an1, an2 and an3 where: //! - an1 is the third node of AT1, //! - an2 is the third node of AT2, //! - an3 is the third node of AT3. //! So triangle AT1 is composed of nodes n2, n3 and an1. //! There are two ways of using this algorithm. //! - From a given node you can look for one triangle that //! passes through the node, then look for the triangles //! adjacent to this triangle, then the adjacent nodes. You //! can thus explore the triangulation step by step (functions //! Triangle, Triangles and Nodes). //! - From a given node you can look for all the triangles //! that pass through the node (iteration method, using the //! functions Initialize, More, Next and Value). //! A Connect object can be seen as a tool which analyzes a //! triangulation and translates it into a series of triangles. By //! doing this, it provides an interface with other tools and //! applications working on basic triangles, and which do not //! work directly with a Poly_Triangulation. class Poly_Connect { public: DEFINE_STANDARD_ALLOC //! Constructs an uninitialized algorithm. Standard_EXPORT Poly_Connect(); //! Constructs an algorithm to explore the adjacency data of //! nodes or triangles for the triangulation T. Standard_EXPORT Poly_Connect (const Handle(Poly_Triangulation)& theTriangulation); //! Initialize the algorithm to explore the adjacency data of //! nodes or triangles for the triangulation theTriangulation. Standard_EXPORT void Load (const Handle(Poly_Triangulation)& theTriangulation); //! Returns the triangulation analyzed by this tool. const Handle(Poly_Triangulation)& Triangulation() const { return myTriangulation; } //! Returns the index of a triangle containing the node at //! index N in the nodes table specific to the triangulation analyzed by this tool Standard_Integer Triangle (const Standard_Integer N) const { return myTriangles (N); } //! Returns in t1, t2 and t3, the indices of the 3 triangles //! adjacent to the triangle at index T in the triangles table //! specific to the triangulation analyzed by this tool. //! Warning //! Null indices are returned when there are fewer than 3 //! adjacent triangles. void Triangles (const Standard_Integer T, Standard_Integer& t1, Standard_Integer& t2, Standard_Integer& t3) const { Standard_Integer index = 6*(T-1); t1 = myAdjacents(index+1); t2 = myAdjacents(index+2); t3 = myAdjacents(index+3); } //! Returns, in n1, n2 and n3, the indices of the 3 nodes //! adjacent to the triangle referenced at index T in the //! triangles table specific to the triangulation analyzed by this tool. //! Warning //! Null indices are returned when there are fewer than 3 adjacent nodes. void Nodes (const Standard_Integer T, Standard_Integer& n1, Standard_Integer& n2, Standard_Integer& n3) const { Standard_Integer index = 6*(T-1); n1 = myAdjacents(index+4); n2 = myAdjacents(index+5); n3 = myAdjacents(index+6); } public: //! Initializes an iterator to search for all the triangles //! containing the node referenced at index N in the nodes //! table, for the triangulation analyzed by this tool. //! The iterator is managed by the following functions: //! - More, which checks if there are still elements in the iterator //! - Next, which positions the iterator on the next element //! - Value, which returns the current element. //! The use of such an iterator provides direct access to the //! triangles around a particular node, i.e. it avoids iterating on //! all the component triangles of a triangulation. //! Example //! Poly_Connect C(Tr); //! for //! (C.Initialize(n1);C.More();C.Next()) //! { //! t = C.Value(); //! } Standard_EXPORT void Initialize (const Standard_Integer N); //! Returns true if there is another element in the iterator //! defined with the function Initialize (i.e. if there is another //! triangle containing the given node). Standard_Boolean More() const { return mymore; } //! Advances the iterator defined with the function Initialize to //! access the next triangle. //! Note: There is no action if the iterator is empty (i.e. if the //! function More returns false).- Standard_EXPORT void Next(); //! Returns the index of the current triangle to which the //! iterator, defined with the function Initialize, points. This is //! an index in the triangles table specific to the triangulation //! analyzed by this tool Standard_Integer Value() const { return mytr; } private: Handle(Poly_Triangulation) myTriangulation; TColStd_Array1OfInteger myTriangles; TColStd_Array1OfInteger myAdjacents; Standard_Integer mytr; Standard_Integer myfirst; Standard_Integer mynode; Standard_Integer myothernode; Standard_Boolean mysense; Standard_Boolean mymore; TColStd_PackedMapOfInteger myPassedTr; }; #endif // _Poly_Connect_HeaderFile
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "GeneticAI.h" #include "Components/ActorComponent.h" #include "NeuralInputComponent.generated.h" class ANeuralNetworkManager; UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class GENETICAI_API UNeuralInputComponent : public UActorComponent { GENERATED_BODY() public: // Sets default values for this component's properties UNeuralInputComponent(); // Called every frame virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override; // Sets the inputs which will be passed to the NN-manager UFUNCTION(BlueprintCallable) void SetInputs(const TArray<float> NewInputs); protected: // Called when the game starts virtual void BeginPlay() override; public: UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Inputs") uint8 NumberOfInputs = 0; // Inputs sent to the Neural Network UPROPERTY(BlueprintReadOnly, Category = "Inputs") TArray<float> Inputs; //manager UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Inputs") ANeuralNetworkManager* Manager; };
/* ID: washirv1 PROG: PROGRAM LANG: C++ */ #include <iostream> #include <fstream> using namespace std; #define INFILE "PROGRAM.in" #define OUTFILE "PROGRAM.out" int main() { ifstream fin(INFILE); fin.close(); ofstream fout(OUTFILE); fout.close(); return 0; }
/* * File: main.cpp * Author: Daniel Canales * * Created on July 27, 2014, 11:09 AM */ #include <cstdlib> #include <iomanip> #include <iostream> #include <cmath> #include <fstream> using namespace std; /* * */ const int SIZE = 10; const int SIZE2 = 12; const int SIZE3 = 5; const int ROW = 3; const int COL = 7; const int SUM = 3; const int ROW2 = 3; const int COL2 = 31; const int DIVI = 6; const int QUART = 4; void problem1(); void problem2(); void getNum( int ref[], int SIZE2 ); void totRain( int ref[], int SIZE2 ); void hilow( int ref[], int SIZE2 ); void problem3(); void getInfo(string salsa[], int SIZE3, int jars[], int SIZE32); void disInfo(string salsa[], int SIZE3, int jars[], int SIZE32); void high(string salsa[], int SIZE3, int jars[], int SIZE32); void low(string salsa[], int SIZE3, int jars[], int SIZE32); void problem4(); void getInfo(int monkey[][COL],int ROW); void disInfo(int monkey[][COL],int ROW); void sumFood(int monkey[][COL],int ROW); void checkFood(int monkey[][COL], int ROW); void problem5(); void checkSun(char ref[][COL2], int ROW2, string month); void mostRainy(char ref[][COL2], int ROW2); void problem7(); void getInfo(string division[], int SIZE, float ref[][QUART], int DIVI); void disInfo(string division[], int SIZE, float ref[][QUART], int DIVI); void moneyInfo(string division[], int SIZE, float ref[][QUART], int DIVI); int main(int argc, char** argv) { cout << "This will go through the completed problem" << endl; int begin = 1; do{ switch(begin) { case 1 : problem1(); break; case 2 : problem2(); break; case 3 : problem3(); break; case 4 : problem4(); break; case 5 : problem5(); break; case 6 : break; case 7 : problem7(); break; } begin++; }while(begin <8); return 0; } void problem1() { //declare variables int numbers[SIZE]; int highest; int lowest; //loop to get numbers for(int i=0; i<SIZE; i++) { cout << "Enter number " << (i+1) << endl; cin >> numbers[i]; } //set high/low = to array 0 highest = numbers[0]; lowest = numbers[0]; //loop again to check. didnt work if i did it while getting the numbers for(int i=0; i<SIZE; i++) { if(highest<numbers[i])highest = numbers[i]; if(lowest>numbers[i]) lowest = numbers[i]; } //output the numbers cout << "Highest number is " << highest << endl;; cout << "Lowest number is " << lowest << endl; } void problem2() { //delclare vairables int ref[SIZE2]; //use functions to get numbers add/divi/sum/high/lowest getNum(ref,SIZE2); totRain(ref,SIZE2); hilow(ref,SIZE2); } void getNum( int ref[], int SIZE2 ) { //loops to get numbers for(int i=0; i<SIZE2; i++) { cout << "Enter number " << (i+1) << endl; cin >> ref[i]; } } void totRain( int ref[], int SIZE2 ) { int sum; float avg; //loops to add each into sum for(int i=0; i<SIZE2; i++) { sum += ref[i]; } //divide byb 12 for avg avg = sum/12; cout << "Total Rain is " << sum << endl; cout << "Average Rain is " << avg << endl; } void hilow( int ref[], int SIZE2 ) { //set them to first number int high = ref[0]; int low = ref[0]; //replace whenever high or low is beaten for(int i=0; i<SIZE2; i++) { if(high<ref[i]) high=ref[i]; if(low>ref[i]) low=ref[i]; } cout << "Highest Rain is " << high << endl; cout << "Lowest Rain is " << low << endl; } void problem3() { //declare variables string salsa[SIZE3]; int jars[SIZE3]; //add info to 2 arrays getInfo(salsa,SIZE3,jars,SIZE3); disInfo(salsa,SIZE3,jars,SIZE3); high(salsa,SIZE3,jars,SIZE3); low(salsa,SIZE3,jars,SIZE3); } void getInfo(string salsa[], int SIZE3, int jars[], int SIZE32) { //loop for jars and type for(int i=0; i<SIZE3; i++) { //enter the info cout << "Enter the name of the salsa" << endl; cout << "Mild,Medium,Sweet,Hot,Zesty" << endl; cin >> salsa[i]; cout << "Enter how many jars sold" << endl; cin >> jars[i]; cout << " " << endl; } } void disInfo(string salsa[], int SIZE3, int jars[], int SIZE32) { for(int i=0; i<SIZE3; i++) { cout << "Salsa Amount Sold" << endl; cout << salsa[i] << " " << jars[i] << endl; } } void high(string salsa[], int SIZE3, int jars[], int SIZE32) { int high; high = jars[0]; string name1; for(int i=0; i<SIZE3; i++) { if(high<jars[i]) high = jars[i]; name1 = salsa[i]; } cout << " " << endl; cout << "Highest Item Amount Sold" << endl; cout << name1 << " " << high << endl; } void low(string salsa[], int SIZE3, int jars[], int SIZE32) { int low; low = jars[0]; string name2; for(int i=0; i<SIZE3; i++) { //figure out how to get names if(low>jars[i]) low = jars[i]; name2 = salsa[i]; } cout << "Lowest Item Amount Sold" << endl; cout << name2 << " " << low << endl; } void problem4() { int array[ROW][COL] ; getInfo(array,ROW); disInfo(array,ROW); sumFood(array,ROW); checkFood(array,ROW); } void getInfo(int monkey[][COL], int ROW) { //loop 7 times for days for(int i=0; i<ROW; i++) { cout << "How much did monkey " << (i+1) << " eat?" << endl; //loop 3 for each monkey for(int x=0; x<COL; x++) { cout << "Day " << (x+1) << endl; cin >> monkey[i][x]; } } } void disInfo(int monkey[][COL],int ROW) { //so i can see if numbers entered correctly for(int i=0; i<ROW; i++) { for(int x=0; x<COL; x++) { cout << "Array " << "[" << i << "]" << "[" << x << "]" << monkey[i][x] << endl; } } } void sumFood(int monkey[][COL],int ROW) { int sum = 0; int avg = 0; //add to get sum for array for(int i=0; i<ROW; i++) { for(int x=0; x<COL; x++) { sum += monkey[i][x]; } } avg = sum/7; cout << "Sum of all the food eaten is " << sum << endl; cout << "Average food eaten per day " << avg << endl; } void checkFood(int monkey[][COL], int ROW) { int low = 0; int high = 0; int size = 3; //sum array to add each individual part of whole array int sum[SUM]; //created to add to sum array int sum1 = 0; int sum2 = 0; int sum3 = 0; //so i can check for high/low high = monkey[0][0]; low = monkey[0][0]; //monkey 1 for(int i=0; i<COL; i++) { sum1 += monkey[0][i]; sum[0] = sum1; } //monkey 2 for(int i=0; i<COL; i++) { sum2 += monkey[1][i]; sum[1] = sum2; } //monkey 3 for(int i=0; i<COL; i++) { sum3 += monkey[2][i]; sum[2] = sum3; } //check for high/low for(int i=0; i<ROW; i++) { for(int x=0; x<COL; x++) { if(high < monkey[i][x]) high = monkey[i][x]; if(low > monkey[i][x]) low = monkey[i][x]; } } cout << "Monkey 1 ate " << sum[0] << " bananas" << endl; cout << "Monkey 2 ate " << sum[1] << " bananas" << endl; cout << "Monkey 3 ate " << sum[2] << " bananas" << endl; cout << "Most amount eaten in a day " << high << endl; cout << "Least amount eaten in a day " << low << endl; } void problem5() { //declare variables ifstream inFile; char array[ROW2][COL2]; string June = "June"; string July = "July"; string August = "August"; //open the file inFile.open("RainorShine.txt"); //read from file for(int r=0; r<ROW2; r++) { for(int c=0; c<COL2; c++) { inFile >> array[r][c]; } } //close file inFile.close(); //output one at a time cout << "June : "; //loop for month june outputs for(int c=1; c<COL2; c++) { //check on first ROW2 cout << array[0][c] << " "; } cout << " " << endl; //july cout << "July : "; for(int c=1; c<COL2; c++) { cout << array[1][c] << " "; } cout << " " << endl; //august cout << "August: "; for(int c=1; c<COL2; c++) { cout << array[2][c] << " "; } cout << " " << endl; //use functions checkSun(array,0,June); checkSun(array,1,July); checkSun(array,2,August); mostRainy(array,ROW2); } void checkSun(char ref[][COL2], int ROW2, string month) { //weather counter int sunny = 0; int rainy = 0; int cloudy = 0; //adds one for each day that appears for(int c=0; c<COL2; c++) { if(ref[ROW2][c] == 'C' ) cloudy += 1; if(ref[ROW2][c] == 'R' ) rainy += 1; if(ref[ROW2][c] == 'S' ) sunny += 1; } //display results cout << " " << endl; cout << month << endl; cout << cloudy << " days cloudy" << endl; cout << rainy << " days rainy" << endl; cout << sunny << " days sunny" << endl; cout << " " << endl; } void mostRainy(char ref[][COL2], int ROW2) { //declare variables int SIZE = 3; int month[SIZE]; int sum1, sum2, sum3; int temp = month[0]; //month of june for(int i=0; i<COL2; i++) { sum1 += ref[0][i]; month[0] = sum1; } //month of july for(int i=0; i<COL2; i++) { sum2 += ref[0][i]; month[1] = sum2; } //month of august for(int i=0; i<COL2; i++) { sum3 += ref[0][i]; month[2] = sum3; } //compare to check highest for(int i=0; i<3; i++) { if(temp<month[0]) temp = month[i]; } //check if equal and display appropiate results if(temp == month[0]) cout << "June has the highest amount of rainy days" << endl; if(temp == month[1]) cout << "July has the highest amount of rainy days" << endl; if(temp == month[2]) cout << "August has the highest amount of rainy days" << endl; } void problem7() { string division[DIVI]; float sales[DIVI][QUART]; getInfo(division, DIVI, sales ,DIVI); disInfo(division, DIVI, sales, DIVI); moneyInfo(division, DIVI, sales, DIVI); } //gather input from user void getInfo(string division[], int SIZE, float ref[][QUART], int DIVI) { //seperate array to get name for(int divi=0; divi<DIVI; divi++) { cout << "Please enter the name of division " << (divi+1) << endl; cin >> division[divi]; //loop to get number for each division for(int quart=0; quart<QUART; quart++) { cout << "Enter the sales total for quarter " << (quart+1) << endl; cin >> ref[divi][quart]; } } } //output display void disInfo(string division[], int SIZE, float ref[][QUART], int DIVI) { for(int divi=0; divi<DIVI; divi++) { //output company to display name before the amount cout << division[divi] << ":"; //loop for output for(int quart=0; quart<QUART; quart++) { cout << ref[divi][quart] << " "; } //finish the line to start next division cout << " " << endl; } } //recording gain/loss void moneyInfo(string division[], int SIZE, float ref[][QUART], int DIVI) { float quart[DIVI][QUART]; //used to compare month to previous float compare[QUART]; for(int divi=0; divi<DIVI; divi++) { cout << "Division: " << divi << endl; //hold quarter revenue to compare compare[0] = ref[divi][0]; compare[1] = ref[divi][1]; compare[2] = ref[divi][2]; compare[3] = ref[divi][3]; for(int month=0; month<QUART; month++) { //compare //stop before month turns 5 if(month+1 == 5) cout << "Done" << endl; if(compare[month] < compare[month+1]) cout << "Profit Quarter!" << endl; if(compare[month] > compare[month+1]) cout << "Loss Quater!" << endl; if(compare[month] == compare[month+1]) cout << "No gain Quarter!" << endl; } } }
#include "SceneHandler.hpp" SceneHandler::SceneHandler() { } SceneHandler::~SceneHandler() { } Scene * SceneHandler::addScene(Scene * scene) { m_scenes[scene->getName()] = scene; return scene; } void SceneHandler::setScene(std::string name) { Scene* s = m_scenes[name]; if (s != NULL) { m_currentScene = s; } else { std::cout << "Scene not found: " << name.c_str() << std::endl; } } void SceneHandler::events(const float & delta, const Dimension<int>& screen, const SDL_Event & evnt) { if (m_currentScene != NULL) { m_currentScene->events(delta, screen, evnt); } } void SceneHandler::update(const float & delta, const Dimension<int>& screen) { if (m_currentScene != NULL) { m_currentScene->update(delta, screen); } } void SceneHandler::render(const float & delta, const Dimension<int>& screen) { if (m_currentScene != NULL) { m_currentScene->render(delta, screen); } }
#include "implicitconstant.h" namespace anl { CImplicitConstant::CImplicitConstant() : m_constant(0){} CImplicitConstant::CImplicitConstant(double c) : m_constant(c){} CImplicitConstant::~CImplicitConstant(){} void CImplicitConstant::setConstant(double c){m_constant=c;} double CImplicitConstant::get(double, double){return m_constant;} double CImplicitConstant::get(double, double, double){return m_constant;} double CImplicitConstant::get(double, double, double, double){return m_constant;} double CImplicitConstant::get(double, double, double, double, double, double){return m_constant;} };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2006 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef SVG_DOM_ANGLE_IMPL_H #define SVG_DOM_ANGLE_IMPL_H #include "modules/svg/svg_dominterfaces.h" #include "modules/svg/src/SVGValue.h" #if defined(SVG_DOM) && defined(SVG_FULL_11) class SVGDOMAngleImpl : public SVGDOMAngle { public: SVGDOMAngleImpl(SVGAngle* angle); virtual ~SVGDOMAngleImpl(); virtual const char* GetDOMName(); virtual SVGDOMAngle::UnitType GetUnitType(); virtual OP_BOOLEAN SetValue(double v); virtual double GetValue(); virtual OP_BOOLEAN SetValueInSpecifiedUnits(double v); virtual double GetValueInSpecifiedUnits(); virtual OP_STATUS SetValueAsString(const uni_char* v); virtual const uni_char* GetValueAsString(); virtual OP_BOOLEAN NewValueSpecifiedUnits(SVGDOMAngle::UnitType unitType, double valueInSpecifiedUnits); virtual OP_BOOLEAN ConvertToSpecifiedUnits(SVGDOMAngle::UnitType unitType); virtual SVGObject* GetSVGObject() { return m_angle; } SVGAngle* GetAngle() { return m_angle; } private: SVGAngle* m_angle; static SVGDOMAngle::UnitType SVGAngleTypeToDOMAngleType(SVGAngleType svg_angle_type); static SVGAngleType DOMAngleTypeToSVGAngleType(SVGDOMAngle::UnitType dom_angle_type); }; #endif // SVG_DOM && SVG_FULL_11 #endif // !SVG_DOM_ANGLE_IMPL_H
/*! \file */ //Copyright 2011-2016 Tyler Gilbert; All Rights Reserved #ifndef THREAD_HPP_ #define THREAD_HPP_ #ifndef __link #include <pthread.h> #include "Sched.hpp" namespace sys { /*! \brief Thread Class * \details This class creates and manages new threads using POSIX calls. * */ class Thread { public: enum { ID_ERROR = -2, ID_UNINITIALIZED = -1, JOINABLE = PTHREAD_CREATE_JOINABLE, DETACHED = PTHREAD_CREATE_DETACHED }; /*! \details This constructs a new thread object * * @param stack_size The stack size of the new thread (default is 4096) * @param detached Whether to create as a detached thread. If this value is false, * another thread must use join() in order for the thread to terminate correctly. */ Thread(int stack_size = 4096, bool detached = true); ~Thread(); /*! \details Sets the stacksize (no effect after create) */ int set_stacksize(int size); /*! \details Gets the stacksize */ int get_stacksize() const; /*! \details Get the detach state (Thread::JOINABLE or Thread::DETACHED) */ int get_detachstate() const; /*! \details Sets the thread priority */ int set_priority(int prio, enum Sched::policy policy = Sched::RR); /*! \details Gets the thread priority */ int get_priority() const; /*! \details Get the thread policy */ int get_policy() const; /*! \details Gets the ID of the thread */ int id() const { return m_id; } /*! \details Start the thread */ int create(void * (*func)(void*), void * args = NULL, int prio = 0, enum Sched::policy policy = Sched::OTHER); /*! \details Check if the thread is running */ bool is_running() const; /*! \details Wait for the thread to complete (joins thread if it is not detached) */ int wait(void**ret = 0, int interval = 1000); /*! \details Yield the processor to another thread */ static void yield(); /*! \details Join the current thread to the specified thread * * @param ident the ID of the target thread * @param value_ptr A pointer to the return value of the target thread * @return Zero on success */ static int join(int ident, void ** value_ptr); /*! \details This method returns true if the thread is joinable */ bool is_joinable() const; /*! \details The calling thread will joing the thread with id Thread::id() * * @return 0 if joined, -1 if couldn't join (doesn't exist or is detached) */ int join(void ** value_ptr) const; /*! \details Reset the object (thread must not be running) */ void reset(); /*! \details Set the scheduler * * @param pid The process ID * @param value The policy (such as Sched::FIFO) * @param priority The priority (higher is higher priority) * @return Zero on success of -1 with errno set */ static int set_scheduler(int id, enum Sched::policy value, int priority); /*! \details Allows read only access to the thread attributes */ const pthread_attr_t & attr() const { return m_pthread_attr; } private: pthread_attr_t m_pthread_attr; pthread_t m_id; int init(int stack_size, bool detached); void set_id_default(){ m_id = ID_UNINITIALIZED; } void set_id_error(){ m_id = ID_ERROR; } }; }; #endif #endif /* THREAD_HPP_ */
#pragma once #include <iostream> #include <vector> #include <map> #include <string> #include <sstream> #include <fstream> #include <cstring> #include <exception> struct BadParse : public std::exception { const char * what() const throw () { return "json parser Error!"; } }; enum JsonType { jsonObject, jsonArray, jsonString, jsonBoolean, jsonNumber, jsonNull, jsonUnknown }; class JsonObject { public: JsonObject(); JsonObject(JsonType); std::string toString(); JsonType getType(); int size(); int asInt(); double asDouble(); bool asBool(); void* asNull(); std::string asString(); void setType(JsonType); void addProperty(std::string key, JsonObject value); void addElement(JsonObject value); void setString(std::string string); JsonObject operator[](int i); JsonObject operator[](std::string s); friend bool operator== (const JsonObject &left, const JsonObject &right); private: std::string makeSpace(int spaceCount); std::string toStringWithSpace(int spaceCount); private: std::string mStringValue; JsonType mType; std::vector<std::pair<std::string, JsonObject> > mProperties; std::map<std::string, size_t> mMapIndex; std::vector<JsonObject> mArray; }; namespace parser { enum tokenType { tokenString, tokenNumber, tokenBoolean, tokenBracesOpen, tokenBracesClose, tokenBracketOpen, tokenBracketClose, tokenComma, tokenColon, tokenNull, tokenUnknown }; class Token { public: Token(std::string value = "", tokenType type = tokenUnknown) : mStringValue(value), mType(type) { } tokenType getType() const; std::string getValue() const; private: std::string mStringValue; tokenType mType; }; JsonObject parse(const std::string& jsonString, bool multithreaded = false); JsonObject parseFile(const std::string& filePath); int nextWhitespace(const std::string& jsonString, int pos); int skipWhitespaces(const std::string& jsonString, int pos); std::vector<Token> tokenizeMultithreaded(std::string jsonString); std::vector<Token> tokenize(std::string jsonString); JsonObject jsonParse(std::vector<Token> v, int startPos, int& endPos); }
#include <string> namespace ariel{std::string snowman(int x);};
// Sharna Hossain // CSC 111 // Lab 22 | exercise_2.cpp // Ask user to enter the size of the array and then ask him to enter // values for this array. Then by using pointer calculate the average // of all these numbers. // Hint: array name is the address of the first element of an array. // so by knowing the address of the first element you can access all // elements. #include <iostream> using namespace std; double get_avg(int *arr, int size) { int sum = 0; for (int i = 0; i < size; i++) { sum += *(arr + i); } return sum / (size * 1.0); } int main() { int size; cout << "Enter the size of array: "; cin >> size; int arr[size]; for (int i = 0; i < size; i++) { cout << "Enter element #" << i + 1 << ": "; cin >> arr[i]; } cout << "Average is " << get_avg(arr, size) << endl; return 0; }
#pragma once #include <cassert> #include <functional> namespace breakout { class Allocator { public: Allocator(const size_t size); virtual ~Allocator() = 0; virtual void* allocate(const size_t size) = 0; virtual void deallocate(void* p) = 0; protected: size_t m_memorySize = 0; size_t m_allocatedMemorySize = 0; size_t m_allocationsNumber = 0; size_t m_deallocatedMemorySize = 0; size_t m_deallocationsNumber = 0; }; template<typename T, typename... Args> T* allocate(Allocator* allocator, Args& ... args) { return new (allocator->allocate(sizeof(T))) T(args...); }; template<typename T> void deallocate(Allocator* allocator, T* object) { object->~T(); allocator->deallocate(static_cast<void*>(object)); }; }
#include <iostream> #include <deque> using namespace std; deque<int> q; deque<int>::iterator it; int csize; void implement(int x) { if (q.size() == csize) { if (std::find(q.begin(), q.end(), x) != q.end()) { for (it = q.begin(); it != q.end(); it++) { if ((*it) == x) { q.erase(it); } } } else { q.pop_front(); } } q.push_back(x); } int main() { cout << "Enter frame size : "; cin >> csize; int x; char ch; while (true) { cout << "Enter value : "; cin >> x; implement(x); cout << "More values?(y/n)"; cin >> ch; if (ch == 'n') break; } for (it = q.begin(); it != q.end(); it++) { cout << *it << " "; } cout << endl; return 0; }
// // Main menu for Blackjack // Project: A2BlackJack // Created by: Ryan Purse // Date: 23/11/2020 // #include <iostream> #include "../public/blackjack.h" #include "../public/input.h" #include "../public/settings.h" #include "../public/tutorial.h" void menuInfo() { system("CLS"); std::cout << "-_-_-_-_-_-_-_- Dr. Greens Casino -_-_-_-_-_-_-" << std::endl; std::cout << "Welcome to Dr. Greens Casino.\n" "Select an option below:\n" "\n" "(P)lay Blackjack\n" "(S)ettings\n" "(H)ow to play?\n" "(Q)uit\n" << std::endl; } /* * Main menu for: Blackjack, settings and tutorial. * Quits the program upon user request. */ int main() { /* Main menu for the user. Branches off into separate methods */ for (;;) { menuInfo(); char playerChoice = characterInput((char*)"Option:", (char*)"pshq", true); switch (playerChoice) { case 'p': case '1': blackjack(); break; case 's': case '2': settingsMenu(); break; case 'h': case '3': displayTutorial(); break; case 'q': case '4': return 0; default: std::cout << "Please type p, s, h or q to continue" << std::endl; break; } } }