text
stringlengths
8
6.88M
#pragma once #include "plbase/PluginBase.h" #include "CTask.h" #pragma pack(push, 4) class PLUGIN_API CTaskComplex : public CTask { CTaskComplex() = delete; protected: CTaskComplex(plugin::dummy_func_t a) : CTask(a) {} public: CTask *m_pSubTask; // vtable virtual void SetSubTask(CTask *subTask); virtual CTask *CreateNextSubTask(class CPed *ped);//=0 virtual CTask *CreateFirstSubTask(class CPed *ped);//=0 virtual CTask *ControlSubTask(class CPed *ped);//=0 }; #pragma pack(pop) VALIDATE_SIZE(CTaskComplex, 0xC);
// This file is MACHINE GENERATED! Do not edit. #ifndef TENSORFLOW_CC_OPS_LOOKUP_OPS_INTERNAL_H_ #define TENSORFLOW_CC_OPS_LOOKUP_OPS_INTERNAL_H_ // This file is MACHINE GENERATED! Do not edit. #include "tensorflow/cc/framework/ops.h" #include "tensorflow/cc/framework/scope.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/lib/gtl/array_slice.h" namespace tensorflow { namespace ops { namespace internal { // NOTE: This namespace has internal TensorFlow details that // are not part of TensorFlow's public API. /// @defgroup lookup_ops_internal Lookup Ops Internal /// @{ /// Removes keys and its associated values from a table. /// /// The tensor `keys` must of the same type as the keys of the table. Keys not /// already in the table are silently ignored. /// /// Arguments: /// * scope: A Scope object /// * table_handle: Handle to the table. /// * keys: Any shape. Keys of the elements to remove. /// /// Returns: /// * the created `Operation` class LookupTableRemove { public: LookupTableRemove(const ::tensorflow::Scope& scope, ::tensorflow::Input table_handle, ::tensorflow::Input keys); operator ::tensorflow::Operation() const { return operation; } Operation operation; }; } // namespace internal } // namespace ops } // namespace tensorflow #endif // TENSORFLOW_CC_OPS_LOOKUP_OPS_INTERNAL_H_
#include <iostream> #include <cstdlib> #include <ctime> #include "Sudoku.h" using namespace std; void Sudoku::giveQuestion(){ int i; int Sudo[81]={0,0,0,0,0,0,6,8,0,0,0,0,0,7,3,0,0,9,3,0,9,0,0,0,0,4,5,4,9,0,0,0,0,0,0,0,8,0,3,0,5,0,9,0,2,0,0,0,0,0,0,0,3,6,9,6,0,0,0,0,3,0,8,7,0,0,6,8,0,0,0,0,0,2,8,0,0,0,0,0,0}; for(i=0;i<81;i++){ cout<<Sudo[i]; if((i+1)%9==0) cout<<endl; else cout<<" "; } } void Sudoku::readIn(){ int i,j; for(i=0;i<9;i++){ for(j=0;j<9;j++) cin>>sudoku[i][j]; } } void Sudoku::solve(){ int i,j,k; if(more_answer()) cout<<"2"<<endl; else{ for(i=8;i>=0;i--){ for(j=8;j>=0;j--){ if(sudoku[i][j]==0) k=9*i+j; } } if(fillIn(0,k)==1){ cout<<"1"<<endl; printOut(); } else cout<<"0"<<endl; } } int Sudoku::fillIn(int n,int k){ int i,j; int conflict,try_number; int row,col,block_row,block_col; if(n==81) return 1; row=n/9; col=n%9; block_row=row/3; block_col=col/3; if(sudoku[row][col]!=0) return fillIn(n+1,k); for(try_number=1;try_number<=9;try_number++){ conflict=0; for(i=0;i<9&&!conflict;i++){ if(((row!=i)&&(sudoku[i][col]==try_number))||((col!=i)&&(sudoku[row][i]==try_number))) conflict=1; } if(!conflict){ for(i=0;i<3&&!conflict;i++){ for(j=0;j<3&&!conflict;j++){ if(sudoku[3*block_row+i][3*block_col+j]==try_number) conflict=1; } } if(!conflict){ sudoku[row][col]=try_number; if(fillIn(n+1,k)) return 1; } } if(conflict==1&&try_number==9&&n==k) return 0; } sudoku[row][col]=0; return 0; } bool Sudoku::more_answer(){ int i,j; int count=0; for(i=0;i<9;i++){ for(j=0;j<9;j++){ if(sudoku[i][j]!=0) count++; } } if(count<17) return true; else return false; } void Sudoku::changeNum(int n1,int n2){ int i,j,temp1,temp2; for(i=0;i<9;i++){ for(j=0;j<9;j++){ if(sudoku[i][j]==n1) temp1=j; if(sudoku[i][j]==n2) temp2=j; } sudoku[i][temp1]=n2; sudoku[i][temp2]=n1; } } void Sudoku::changeRow(int r1,int r2){ int i,j,R1=3*r1,R2=3*r2; int temp[3][9]; for(i=0;i<3;i++,R1++,R2++){ for(j=0;j<9;j++){ temp[i][j]=sudoku[R1][j]; sudoku[R1][j]=sudoku[R2][j]; sudoku[R2][j]=temp[i][j]; } } } void Sudoku::changeCol(int c1,int c2){ int i,j,C1=3*c1,C2=3*c2; int temp[9][3]; for(j=0;j<3;j++,C1++,C2++){ for(i=0;i<9;i++){ temp[i][j]=sudoku[i][C1]; sudoku[i][C1]=sudoku[i][C2]; sudoku[i][C2]=temp[i][j]; } } } void Sudoku::rotate(int r){ int i,j,N=r%4; int temp[9][9]; switch (N){ case 1: for(i=0;i<9;i++){ for(j=0;j<9;j++) temp[i][j]=sudoku[i][j]; } for(i=0;i<9;i++){ for(j=0;j<9;j++) sudoku[j][8-i]=temp[i][j]; } break; case 2: for(i=0;i<9;i++){ for(j=0;j<9;j++) temp[i][j]=sudoku[i][j]; } for(i=0;i<9;i++){ for(j=0;j<9;j++) sudoku[8-i][8-j]=temp[i][j]; } break; case 3: for(i=0;i<9;i++){ for(j=0;j<9;j++) temp[i][j]=sudoku[i][j]; } for(i=0;i<9;i++){ for(j=0;j<9;j++) sudoku[8-j][i]=temp[i][j]; } break; default: return; } } void Sudoku::flip(int f){ int i,j; int temp[9][9]; if(f==0){ for(i=0;i<9;i++){ for(j=0;j<9;j++) temp[i][j]=sudoku[i][j]; } for(i=0;i<9;i++){ for(j=0;j<9;j++) sudoku[8-i][j]=temp[i][j]; } } else{ for(i=0;i<9;i++){ for(j=0;j<9;j++) temp[i][j]=sudoku[i][j]; } for(i=0;i<9;i++){ for(j=0;j<9;j++) sudoku[i][8-j]=temp[i][j]; } } } void Sudoku::transform(){ readIn(); change(); printOut(); } void Sudoku::change(){ srand(time(NULL)); changeNum(rand()%9+1,rand()%9+1); changeRow(rand()%3,rand()%3); changeCol(rand()%3,rand()%3); rotate(rand()%101); flip(rand()%2); } void Sudoku::printOut(){ int i,j; for(i=0;i<9;i++){ for(j=0;j<9;j++){ cout<<sudoku[i][j]; if(j==8) cout<<endl; else cout<<" "; } } }
#pragma once #include <stdio.h> #include <stdlib.h> class party; class player; class item; class enemy; class quest; class party { protected: int gold; player **ply_lst; int num_plys; int Max_members; item **inventory; int inv_size; quest *active_quest; bool game_over; public: party(); ~party(); int getGold() {return gold;} player** getPlayers() {return ply_lst;} int getPartySize() {return num_plys;} int getMaxPartySize() {return Max_members;} item** getInventory() {return inventory;} int getInventorySize() {return inv_size;} bool isGameOver() {return game_over;} quest* getActiveQuest() {return active_quest;} void recieveGold(int); void loseGold(int); bool goldCheck(int); bool checkGameOver(); player* recievePlayer(player*); void compressParty(); player* removePlayer(int); void deletePlayer(int); void printPlayers(); void printInventory(); bool inventoryFull(); bool partyFull(); bool checkStock(int, int); bool checkItem(int); char* getItemName(int); int getItemValue(int); void recieveItem(item*); item* removeItem(int); item* removeOneItem(int); item* removeItems(int, int); void discardItem(int); item* swapItem(item*); int findItemIndex(int); void equipGear(int, int); void unequipGear(int, int); void useItem(int, int); // void useItemBtl(int itm_idx, player **ply_lst, int num_plys, enemy *enm_lst, int num_enms, int targ); void viewItemInfo(int); void acceptQuest(quest*); void discardQuest(); void deleteQuest(); quest* swapQuest(quest*); void printQuest(); void recieveQuestRewards(); bool hasQuest(); bool metQuestRequirements(); bool questCompleted(); void managePlayers(); void manageInventory(); void manageEquipment(int); void manageSkills(int); void useSkill_OB(int); void useItem_OB(); void viewItemInfo_OB(); player* removePlayer_OB(); void deletePlayer_OB(); void partyMenu(); void printPartyInfo(); void switchPartyOrder(); void saveParty(); void loadParty(); };
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> using namespace std; typedef long long ll; #define INF 10e17 // 4倍しても(4回足しても)long longを溢れない #define rep(i,n) for(int i=0; i<n; i++) #define rep_r(i,n,m) for(int i=m; i<n; i++) #define END cout << endl #define MOD 1000000007 #define pb push_back #define sorti(x) sort(x.begin(), x.end()) #define sortd(x) sort(x.begin(), x.end(), std::greater<int>()) #define debug(x) std::cerr << (x) << std::endl; #define roll(x) for (auto itr : x) { debug(itr); } template <class T> inline void chmax(T &ans, T t) { if (t > ans) ans = t;} template <class T> inline void chmin(T &ans, T t) { if (t < ans) ans = t;} template <class T = long long> class Union_Find { using size_type = std::size_t; using _Tp = T; public: vector<_Tp> par; const _Tp operator[] (size_type child) { return -par[root(child)]; } Union_Find(size_type n) : par(n, -1) {} void init(int n) { par.assign(n, -1); } _Tp root(size_type x) { if (par[x] < 0) return x; else return par[x] = root(par[x]); } bool issame(size_type x, size_type y) { return root(x) == root(y); } bool merge(size_type x, size_type y) { x = root(x); y = root(y); if (x == y) return false; if (par[x] > par[y]) swap(x,y); par[x] += par[y]; par[y] = x; return true; } _Tp size(int x) { return -par[root(x)]; } }; #include <map> int main() { int n, m; cin >> n >> m; Union_Find<ll> uf(n); rep(i, m) { int x, y, z; cin >> x >> y >> z; x--, y--; uf.merge(x, y); } map<int, int> mp; ll ans = 0; for (int i = 0; i < n; ++i) { if (!mp[uf.root(i)]) { ans += uf[i] - 1; mp[uf.root(i)] = 1; } } cout << n - ans << endl; }
#pragma once #include "common.hpp" void failTest(int line = __builtin_LINE(), const char* file = __builtin_FILE()) { fail("Test failed: failTest @ ", file, ":", line); } template <typename T> void checkEqual(T a, T b, int line = __builtin_LINE(), const char* file = __builtin_FILE()) { if(!(bool)(a == b)) { fail("Test failed: checkEqual(", a, ", ", b, ") @ ", file, ":", line); } } template <typename T> void checkNotEqual(T a, T b, int line = __builtin_LINE(), const char* file = __builtin_FILE()) { if(!(bool)(a != b)) { fail("Test failed: checkNotEqual(", a, ", ", b, ") @ ", file, ":", line); } } void checkTrue(bool val, int line = __builtin_LINE(), const char* file = __builtin_FILE()) { if(!val) { fail("Test failed: checkTrue(false) @ ", file, ":", line); } } void checkFalse(bool val, int line = __builtin_LINE(), const char* file = __builtin_FILE()) { if(val) { fail("Test failed: checkFalse(true) @ ", file, ":", line); } } template <typename T> void checkLessOrEqual(T a, T b, int line = __builtin_LINE(), const char* file = __builtin_FILE()) { if(!(bool)(a <= b)) { fail("Test failed: checkLessOrEqual(", a, ", ", b, ") @ ", file, ":", line); } } template <typename T> void checkLess(T a, T b, int line = __builtin_LINE(), const char* file = __builtin_FILE()) { if(!(bool)(a < b)) { fail("Test failed: checkLess(", a, ", ", b, ") @ ", file, ":", line); } } template <typename T> void checkGreaterOrEqual(T a, T b, int line = __builtin_LINE(), const char* file = __builtin_FILE()) { if(!(bool)(a >= b)) { fail("Test failed: checkGreaterOrEqual(", a, ", ", b, ") @ ", file, ":", line); } } template <typename T> void checkGreater(T a, T b, int line = __builtin_LINE(), const char* file = __builtin_FILE()) { if(!(bool)(a > b)) { fail("Test failed: checkGreater(", a, ", ", b, ") @ ", file, ":", line); } } template <typename T> void checkBetweenInclusive(T a, T x, T b, int line = __builtin_LINE(), const char* file = __builtin_FILE()) { if(!((bool)(a <= x) && (bool)(x <= b))) { fail("Test failed: checkBetweenInclusive(", a, ", ", x, ", ", b, ") @ ", file, ":", line); } } template <typename T> void checkBetweenExclusive(T a, T x, T b, int line = __builtin_LINE(), const char* file = __builtin_FILE()) { if(!((bool)(a < x) && (bool)(x < b))) { fail("Test failed: checkBetweenExclusive(", a, ", ", x, ", ", b, ") @ ", file, ":", line); } } template <typename T> void checkBetweenHalfOpen(T a, T x, T b, int line = __builtin_LINE(), const char* file = __builtin_FILE()) { if(!((bool)(a <= x) && (bool)(x < b))) { fail("Test failed: checkBetweenHalfOpen(", a, ", ", x, ", ", b, ") @ ", file, ":", line); } }
// Created on: 1997-08-06 // Created by: Philippe MANGIN // Copyright (c) 1997-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 _GeomFill_QuasiAngularConvertor_HeaderFile #define _GeomFill_QuasiAngularConvertor_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <math_Matrix.hxx> #include <math_Vector.hxx> #include <TColgp_Array1OfPnt.hxx> #include <TColStd_Array1OfReal.hxx> #include <TColgp_Array1OfVec.hxx> class gp_Pnt; class gp_Vec; //! To convert circular section in QuasiAngular Bezier //! form class GeomFill_QuasiAngularConvertor { public: DEFINE_STANDARD_ALLOC Standard_EXPORT GeomFill_QuasiAngularConvertor(); //! say if <me> is Initialized Standard_EXPORT Standard_Boolean Initialized() const; Standard_EXPORT void Init(); Standard_EXPORT void Section (const gp_Pnt& FirstPnt, const gp_Pnt& Center, const gp_Vec& Dir, const Standard_Real Angle, TColgp_Array1OfPnt& Poles, TColStd_Array1OfReal& Weights); Standard_EXPORT void Section (const gp_Pnt& FirstPnt, const gp_Vec& DFirstPnt, const gp_Pnt& Center, const gp_Vec& DCenter, const gp_Vec& Dir, const gp_Vec& DDir, const Standard_Real Angle, const Standard_Real DAngle, TColgp_Array1OfPnt& Poles, TColgp_Array1OfVec& DPoles, TColStd_Array1OfReal& Weights, TColStd_Array1OfReal& DWeights); Standard_EXPORT void Section (const gp_Pnt& FirstPnt, const gp_Vec& DFirstPnt, const gp_Vec& D2FirstPnt, const gp_Pnt& Center, const gp_Vec& DCenter, const gp_Vec& D2Center, const gp_Vec& Dir, const gp_Vec& DDir, const gp_Vec& D2Dir, const Standard_Real Angle, const Standard_Real DAngle, const Standard_Real D2Angle, TColgp_Array1OfPnt& Poles, TColgp_Array1OfVec& DPoles, TColgp_Array1OfVec& D2Poles, TColStd_Array1OfReal& Weights, TColStd_Array1OfReal& DWeights, TColStd_Array1OfReal& D2Weights); protected: private: Standard_Boolean myinit; math_Matrix B; math_Vector Px; math_Vector Py; math_Vector W; math_Vector Vx; math_Vector Vy; math_Vector Vw; }; #endif // _GeomFill_QuasiAngularConvertor_HeaderFile
#ifndef PITCH_YAW_H #define PITCH_YAW_H #include "FreeRTOS.h" #include "PID.h" #include <main.h> #include "motor.h" #include "mpu6050_config.h" #include "dr16.h" #include "PCvision.h" extern CAN_HandleTypeDef hcan1; extern CAN_HandleTypeDef hcan2; extern myPID pitchSpeed,pitchAngle,yawSpeed,yawAngle; extern MPUData_Typedef MPUData; extern float IMUPitchOffset; enum E_pitchYawPidType { PITCH_SPEED = 0, PITCH_ANGLE = 1, YAW_SPEED = 2, YAW_ANGLE = 3, }; enum E_pitchYawMode { REMOTE_CTRL_P = 0, KEY_BOARD_P = 1, MINI_PC_P = 2, LOST_P = 3, }; class C_Pitch_Yaw { public: void IMU_cala(float); void pitch_cal(); void pid_init(E_pitchYawPidType type,float kp,float ki,float kd, float ki_max,float out_max); void Control(E_pitchYawMode mode, float pitch_data, float yaw_data, float motor_pitch_angle, float IMU_pitch_speed, float IMU_yaw_angle, float IMU_yaw_speed); void Reset(); void targetUpdate(); void pidCalc(); void pithchAngleLimit(); float feedforward(float target); myPID pitchSpeed,yawSpeed,pitchAngle,yawAngle; float lastPitchAngleOut,trgAngle,totalYawAngle,lastYawAngle,recPitchData,recYawData,pitchScale,yawScale,lastTotalYawAngle,lastPitchAngle; float lastPitchAngleTarget,lastYawAngleTarget; int16_t cnt; E_pitchYawMode Mode; uint8_t snipermode; int8_t feedforward_stste = 1; int8_t isLandMode = 1; }; #endif
#include "KickOutPlayerProc.h" #include "HallHandler.h" #include "Logger.h" #include "Configure.h" #include "GameServerConnect.h" #include "PlayerManager.h" #include <string> using namespace std; KickOutPlayerProc::KickOutPlayerProc() { this->name = "KickOutPlayerProc"; } KickOutPlayerProc::~KickOutPlayerProc() { } int KickOutPlayerProc::doRequest(CDLSocketHandler* client, InputPacket* pPacket, Context* pt ) { return 0; } int KickOutPlayerProc::doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt) { HallHandler* hallHandler = reinterpret_cast <HallHandler*> (clientHandler); Player* player = PlayerManager::getInstance()->getPlayer(hallHandler->uid); int retcode = inputPacket->ReadShort(); string retmsg = inputPacket->ReadString(); /*printf("Recv KickOutPlayerProc Packet From Server\n"); printf("Data Recv: retcode=[%d]\n",retcode); printf("Data Recv: retmsg=[%s]\n",retmsg.c_str());*/ if(retcode < 0 || player == NULL) { return EXIT; } int uid = inputPacket->ReadInt(); short ustatus = inputPacket->ReadShort(); int tid = inputPacket->ReadInt(); short tstatus = inputPacket->ReadShort(); int leaver = inputPacket->ReadInt(); if(uid == leaver) return EXIT; return 0; //return EXIT; }
// Fill out your copyright notice in the Description page of Project Settings. #include "FinalMachineInteractorComponent.h" #include "FinalMachine.h" #include "FPS_test_5Character.h" bool UFinalMachineInteractorComponent::Interact(UObjectInfo* info) { int flaskUsed = 0; if (FirstFlaskId.Equals(info->ObjectId)) { flaskUsed = 1; } else if (SecondFlaskId.Equals(info->ObjectId)) { flaskUsed = 2; } else if (ThirdFlaskId.Equals(info->ObjectId)) { flaskUsed = 3; } if (flaskUsed != 0) { AFPS_test_5Character* player = (AFPS_test_5Character*)GetWorld()->GetFirstPlayerController()->GetPawn(); if (player) { AFinalMachine* owner = Cast<AFinalMachine>(GetOwner()); if (owner) { owner->NotifyFlaskUsed(flaskUsed, info); player->UnequipCurrentItem(); return true; } } } return false; }
#include <QThread> class MumuThreadSend : public QThread { Q_OBJECT public: void run(); };
#include "CMyOpenGlWidget.h" CMyOpenGlWidget::CMyOpenGlWidget(QWidget * parent , Qt::WindowFlags f ) : QOpenGLWidget(parent,f) { //setFixedSize(200, 200); } CMyOpenGlWidget::~CMyOpenGlWidget() { } void CMyOpenGlWidget::initializeGL() { QSurfaceFormat theFormat = format(); int a1 = theFormat.depthBufferSize(); int a2 = theFormat.stencilBufferSize(); auto a3 = theFormat.version(); int a4 = theFormat.redBufferSize(); int a5 = theFormat.greenBufferSize(); int a6 = theFormat.blueBufferSize(); int a7 = theFormat.alphaBufferSize(); QSurfaceFormat::OpenGLContextProfile a8 = theFormat.profile(); int gg = 0; } void CMyOpenGlWidget::resizeGL(int w, int h) { if( mRenderingCore ) mRenderingCore->resizeGL(w,h); } void CMyOpenGlWidget::paintGL() { if( mRenderingCore ) mRenderingCore->paintGL(); }
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- // // Copyright (C) 2003-2007 Opera Software AS. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // // Julien Picalausa // //The delete operation will attempt to rename the file when do is called, since //that effectively moves it out of the way and ensures that we have delete rights. //It will destroy the moved file once the transaction is complete and the operation //is deleted. It will also try to remove the folder containing the file if empty, //then the parent of that folder and so on, until finding a folder that has content //or can't be deleted. #ifndef DELETE_FILE_OPERATION_H #define DELETE_FILE_OPERATION_H #include "adjunct/desktop_util/transactions/OpUndoableOperation.h" #include "modules/util/opfile/opfile.h" #include "platforms/windows/utils/authorization.h" class DeleteFileOperation : public OpUndoableOperation { public: DeleteFileOperation(const OpFile &file, BOOL remove_empty_folders = TRUE); ~DeleteFileOperation(); virtual OP_STATUS Do(); virtual void Undo(); private: OpFile *m_file; OpFile *m_temp_file; BOOL m_init_success; BOOL m_remove_empty_folders; OpString m_file_name; WindowsUtils::RestoreAccessInfo* m_restore_access_info; }; #endif //DELETE_FILE_OPERATION_H
(English:'Romanian'; Native:'Română'; LangFile:''; DicFile:'romana.dic'; FlagID:'ro'; Letters:'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z'; LetterCount:'11,2,5,4,9,2,2,1,10,1,0,4,3,6,5,4,0,7,5,7,6,2,0,1,0,1'; LetterValue:'1,9,1,2,1,8,9,10,1,10,0,1,4,1,1,2,0,1,1,1,1,8,0,10,0,10'; NumberOfJokers:2; ReadingDirection:rdLeftToRight; ExcludedCat:''; RulesValid:true; NumberOfLetters:7; NumberOfRandoms:0; TimeControl:2; TimeControlEnd:true; TimeControlBuy:false; TimePerGame:'0:50:00'; PenaltyValue:1; //this value ought to be zero, but zero is prohibited in the program PenaltyCount:1; //this value ought to be zero, but zero is prohibited in the program GameLostByTime:true; WordCheckMode:2; ChallengePenalty:10; //point 5.10.15. and http://17085.homepagemodules.de/t1239f330-Assistant-Which-default-settings-do-you-wish-for-Romanian-games.html#msg9872524 ChallengeTime:20; //chosen arbitrarily JokerExchange:false; ChangeIsPass:true; CambioSecco:false; SubstractLetters:true; AddLetters:true; JokerPenalty:0; NumberOfPasses:3; LimitExchange:7; EndBonus:0; ScrabbleBonus:50) {References: http://www.scrabblero.ro/reg/reg-libera2011.doc http://www.scrabblero.ro/ http://www.scrabblero.ro/regulamente.htm http://17085.homepagemodules.de/t1239f330-Assistant-Which-default-settings-do-you-wish-for-Romanian-games.html - Current state of implementation in this *.inc file: 2012-08-10}
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 2007-2011 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef POSIX_CAPABILITIES_H #define POSIX_CAPABILITIES_H __FILE__ /* Capabilities (newest first): */ /** Added PosixModule::InitLocale() and PosixNativeUtil::TransientLocale. */ #define POSIX_CAP_LOCALE_INIT /** PosixLocale::{To,From}Native return OP_STATUS and change signature */ #define POSIX_CAP_NATIVE_STATUS /** PosixModule provides OnCoreThread() instead of GetMainThread(). */ #define POSIX_CAP_ONCORE /** PosixSelector provides Button, defines virtual Poll(), changes Watch() signature. */ #define POSIX_CAP_SELECTOR_POLL /** PosixSelector has the SetMode() methods and its Type has a NONE mode. */ #define POSIX_CAP_SELECTOR_SETMODE /** Reverted: PosixSelectListener's On*Ready briefly returned bool but are back to void. */ #undef POSIX_CAP_SELECTOR_FEEDBACK /** Separated PosixSocketAddress's extensions out into PosixNetworkAddress */ #define POSIX_CAP_NETWORK_ADDRESS /** PosixSystemInfo provides GetUserLanguages and GetUserCountry */ #define POSIX_CAP_USER_LANGUAGE /** Support for sockets, socket addresses and host resolvers (2007/Aug). */ #define POSIX_CAP_SOCKET /** PosixSystemInfo provides OpFileLengthToString */ #define POSIX_CAP_FILE_LENGTH_SYSIO #endif /* POSIX_CAPABILITIES_H */
#pragma once #include <QOpenGLWidget> #include "opencv2/core.hpp" class XVideoWidget : public QOpenGLWidget { Q_OBJECT public: XVideoWidget(QWidget* p); virtual ~XVideoWidget(); public: void paintEvent(QPaintEvent* e); public slots: //½çÃæË¢Ð void SetImage(cv::Mat mat); protected: QImage img; };
#include <iostream> #include <vector> #include <algorithm> #include <fstream> #include <queue> #include <unordered_set> #include <unordered_map> #include <stack> #include <cstdio> #include <cmath> #include <cstring> using namespace std; #define INT_MIN (1<<31) #define INT_MAX (~INT_MIN) #define UNREACHABLE (INT_MAX>>2) #define INF (1e300) #define eps (1e-9) #define MODULO 1000000007 ifstream fin("11402_input.txt"); #define cin fin #define MAX_LEN 1048576 #define F 1 #define E 2 #define I 3 class LazySegmentTree { public: vector<int> tree; vector<int> lazy; int n; int unit; int filter(char ch) { return ch - '0'; } int get_mid(int a, int b) { return a + (b - a) / 2; } int calc(int a, int b) { return a + b; } LazySegmentTree(string & s, int nn) { n = nn; unit = 0; int x = ceil(log(n) / log(2)); tree = vector<int>(2 * (1 << x) - 1, 0); lazy = vector<int>(2 * (1 << x) - 1, 0); constructSTUtil(s, 0, n - 1, 0); } int constructSTUtil(string & s, int ss, int se, int si) { if (ss > se) return unit; if (ss == se) { tree[si] = filter(s[ss]); return tree[si]; } int mid = get_mid(ss, se); int a = constructSTUtil(s, ss, mid, si * 2 + 1); int b = constructSTUtil(s, mid + 1, se, si * 2 + 2); tree[si] = calc(a, b); return tree[si]; } void ease_lazy(int ss, int se, int si) { switch(lazy[si]) { case F: tree[si] = se - ss + 1; break; case E: tree[si] = 0; break; case I: tree[si] = se - ss + 1 - tree[si]; break; default: break; } if (ss != se) { int cur; switch (lazy[si]) { case F: lazy[si * 2 + 1] = F; lazy[si * 2 + 2] = F; break; case E: lazy[si * 2 + 1] = E; lazy[si * 2 + 2] = E; break; case I: cur = si * 2 + 1; switch (lazy[cur]) { case F: lazy[cur] = E; break; case E: lazy[cur] = F; break; case I: lazy[cur] = 0; break; default: lazy[cur] = lazy[si]; break; } cur = si * 2 + 2; switch (lazy[cur]) { case F: lazy[cur] = E; break; case E: lazy[cur] = F; break; case I: lazy[cur] = 0; break; default: lazy[cur] = lazy[si]; break; } break; default: break; } } lazy[si] = 0; } int get_sum(int qs, int qe) { return getSumUtil(0, n - 1, qs, qe, 0); } int getSumUtil(int ss, int se, int qs, int qe, int si) { // printf("si: %d\tlazy[si]: %d\n", si, lazy[si]); // printf("si: %d\ttree[si]: %d\n", si, tree[si]); if (lazy[si]) { ease_lazy(ss, se, si); } // printf("si: %d\ttree[si]: %d\n", si, tree[si]); if (ss > qe || se < qs) return unit; if (ss >= qs && se <= qe) return tree[si]; int mid = get_mid(ss, se); int a = getSumUtil(ss, mid, qs, qe, 2 * si + 1); int b = getSumUtil(mid + 1, se, qs, qe, 2 * si + 2); // printf("si: %d\ta: %d\tb: %d\n", si, a, b); return calc(a, b); } int updateRange(int us, int ue, int mode) { updateRangeUtil(0, n-1, us, ue, 0, mode); } int updateRangeUtil(int ss, int se, int us, int ue, int si, int mode) { // printf("si: %d\tlazy[si]: %d\n", si, lazy[si]); // printf("si: %d\ttree[si]: %d\n", si, tree[si]); if (lazy[si]) { ease_lazy(ss, se, si); } // printf("si: %d\ttree[si]: %d\n", si, tree[si]); if (ss> ue || se < us) { return tree[si]; } if (ss >= us && se <= ue) { lazy[si] = mode; ease_lazy(ss, se, si); return tree[si]; } int mid = get_mid(ss, se); int a = updateRangeUtil(ss, mid, us, ue, si * 2 + 1, mode); int b = updateRangeUtil(mid + 1, se, us, ue, si * 2 + 2, mode); tree[si] = calc(a, b); // printf("si: %d\ta: %d\tb: %d\n", si, a, b); return tree[si]; } void output() { printf("["); for (auto it : tree) { printf("%d,", it); } printf("]\n"); } }; int main() { int tttt; cin >> tttt; int case_count = 0; string pirates; pirates.resize(MAX_LEN); while (tttt--) { case_count++; printf("Case %d:\n", case_count); int M, Q; cin >> M; int nn = 0; for (int i = 0; i < M; i++) { int t; string s; cin >> t; cin >> s; while (t--) { int j = 0; while (j < s.length()) { pirates[nn++] = s[j++]; // cout << j <<' '; } // cout << endl; } // cout << "yes" << endl; } // cout << pirates << endl; LazySegmentTree stree(pirates, nn); cin >> Q; int query_count = 0; for (int i = 0; i < Q; i++) { string ch; int a, b; cin >> ch >> a >> b; switch(ch[0]) { case 'F': stree.updateRange(a, b, F); break; case 'E': stree.updateRange(a, b, E); break; case 'I': stree.updateRange(a, b, I); break; case 'S': printf("Q%d: %d\n", ++query_count, stree.get_sum(a, b)); break; } // stree.output(); } } }
/***************************************************************************************************************** * File Name : insertionsort.h * File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\tutorials\nptel\DSAndAlgo\lecture01\insertionsort.h * Created on : Dec 28, 2013 :: 1:43:44 AM * Author : AVINASH * Testing Status : TODO * URL : TODO *****************************************************************************************************************/ /************************************************ Namespaces ****************************************************/ using namespace std; using namespace __gnu_cxx; /************************************************ User Includes *************************************************/ #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <ctime> #include <list> #include <map> #include <set> #include <bitset> #include <functional> #include <utility> #include <iostream> #include <fstream> #include <sstream> #include <string.h> #include <hash_map> #include <stack> #include <queue> #include <limits.h> #include <programming/ds/tree.h> #include <programming/ds/linkedlist.h> #include <programming/utils/treeutils.h> #include <programming/utils/llutils.h> /************************************************ User defined constants *******************************************/ #define null NULL /************************************************* Main code ******************************************************/ #ifndef INSERTIONSORT_H_ #define INSERTIONSORT_H_ void insertionSortIterative(vector<int> &userInput){ if(userInput.size() == 0 || userInput.size() == 1){ return; } unsigned int outerCounter,innerCounter; int temp; for(outerCounter = 2;outerCounter < userInput.size();outerCounter++){ for(innerCounter = outerCounter-1;innerCounter >= 0;innerCounter--){ if(userInput[innerCounter] > userInput[innerCounter+1]){ temp = userInput[innerCounter]; userInput[innerCounter] = userInput[innerCounter+1]; userInput[innerCounter+1] = temp; }else{ break; } } } } void insertionSort(vector<int> &userInput,unsigned int currentIndex){ if(userInput.size() == 0 || userInput.size() == 1 || currentIndex >= userInput.size()){ return; } int tempForSwap; for(unsigned int counter = currentIndex-1;counter >= 0;counter--){ if(userInput[counter] > userInput[counter+1]){ tempForSwap = userInput[counter]; userInput[counter] = userInput[counter+1]; userInput[counter+1] = tempForSwap; }else{ break; } } insertionSort(userInput,currentIndex+1); } #endif /* INSERTIONSORT_H_ */ /************************************************* End code *******************************************************/
#include "view/WordScrambleWindow.h" using namespace view; int main (int argc, char ** argv) { srand(time(0)); WordScrambleWindow mainWindow(570, 375, "A4: Word Scramble by Jacob Slattery and Tristen Rivera"); mainWindow.resize(800, 300, 600, 375); mainWindow.show(); int exitCode = Fl::run(); return exitCode; }
#include<iostream> #include<vector> #include<map> using namespace std; typedef vector<int> vi; class UnionFind{ public: vi p,rank,count; UnionFind(int N){ rank.assign(N,0);p.assign(N,0);count.assign(N,1); for(int i=0;i<N;i++)p[i]=i;} int findSet(int i){return (p[i]==i)?i:(p[i]=findSet(p[i]));} bool isSameSet(int i,int j){return (findSet(i)==findSet(j));} void UnionSet(int i, int j){ if(!isSameSet(i,j)) { int x=findSet(i),y=findSet(j); if(rank[x]>rank[y]){p[y]=x;count[x]+=count[y];} else {p[x]=y;count[y]+=count[x]; if(rank[x]==rank[y])rank[y]++; } } } }; int main() { int i,t,n,num,x; string i1,i2; map<string,int> m; map<string,int>::iterator it1,it2; cin>>t,n; while(t--) { UnionFind U(0); m.clear(); num=0; cin>>n; while(n--) { cin>>i1>>i2; it1=m.find(i1); if(it1==m.end()){ m[i1]=num; U.p.push_back(num); U.rank.push_back(0); U.count.push_back(1); num++; } it2=m.find(i2); if(it2==m.end()){ m[i2]=num; U.p.push_back(num); U.rank.push_back(0); U.count.push_back(1); num++; } U.UnionSet(m[i1],m[i2]); x=U.findSet(m[i1]); cout<<U.count[x]<<endl; } } return 0; }
#ifndef MIME_H #define MIME_H /** * Interface to mimedec in url2 */ struct mime_content_type_t { OpStringC* media; OpStringC* sub; }; // both able to decode whole rfc822 structures as well as single parts // to Mime_Decoder - add LoadData(FILE, file start pos (and length?)) /* class MimeDecoder { Decode(Buffer data); Decode(Header headers, Buffder content); Decode(Header header, Header header, ... Buffer content); }; class MimePart { const char* MediaType(); const char* MediaSubType(); // MIMEVersion // content-type // content-id // content-description // GetContentDisposition // content-transfer-encoding // size // data // parse(tex from pop) // totext() (ala rfc822 & http) // MD5 // language }; */ #endif // MIME_H
//NAME: StackLinked.cpp //DESC: linked list implementation of stack //USAGE: #include "StackLinked.cpp" //COMPILER: GNU g++ compiler on Linux //AUTHOR: Bri Schmidt //LAST UPDATED: September 30, 2018 20:17 #include "StackLinked.h" //default constructor template <typename DataType> StackLinked<DataType>::StackLinked() : top(nullptr), itemsInStack(0) { } //copy constructor //precondition: none //postcondition: stack constructed from another stack template <typename DataType> StackLinked<DataType>::StackLinked(const StackLinked& other) { StackNode* origPtr = other->top; if(other->isEmpty()) { top = nullptr; itemsInStack = 0; } else { top = new StackNode(); this->dataItem = other->dataItem; StackNode* newPtr = top; origPtr = origPtr->next; while (origPtr != nullptr) { DataType nextItem = origPtr->dataItem; StackNode* newNodePtr = new StackNode; newPtr->dataItem = newNodePtr->dataItem; newPtr = newPtr->next; origPtr = origPtr->next; } } } //overloaded assignment operator //precondition: none (accepts empty Stack) //postcondition: stack with reassigned values from other stack template <typename DataType> StackLinked<DataType>& StackLinked<DataType>::operator=(const StackLinked& other) { StackNode* origPtr = other->top; if(other->isEmpty()) { top = nullptr; itemsInStack = 0; } else { top = new StackNode(); this->dataItem = other->dataItem; StackNode* newPtr = top; origPtr = origPtr->next; while (origPtr != nullptr) { DataType nextItem = origPtr->dataItem; StackNode* newNodePtr = new StackNode; newPtr->dataItem = newNodePtr->dataItem; newPtr = newPtr->next; origPtr = origPtr->next; } } } //destructor //precondition: stack isn't Empty //postcondition: stack is emptied template <typename DataType> StackLinked<DataType>::~StackLinked() { while (!isEmpty()) { pop(); } } //push function //precondition: data to push //postcondition: stack has additional item template <typename DataType> void StackLinked<DataType>::push(const DataType& newDataItem) throw (logic_error) { itemsInStack++; StackNode* newNodePtr = new StackNode(newDataItem, top); top = newNodePtr; newNodePtr = nullptr; } //pop function //precondition: stack isn't empty //postcondition: stack loses the item on top template <typename DataType> DataType StackLinked<DataType>::pop() throw (logic_error) { DataType popped; if(isEmpty()) { cout << "Could not pop, stack is empty" << endl; } else { itemsInStack--; popped = top->dataItem; StackNode* nodeToDeletePtr = top; top = top->next; nodeToDeletePtr->next = nullptr; delete nodeToDeletePtr; nodeToDeletePtr = nullptr; } return popped; } //peek function //precondition: stack is not Empty //postcondition: copy of the top of stack is returned template <typename DataType> DataType StackLinked<DataType>::peek() throw (logic_error) { if(isEmpty()) { cout << "Stack is empty, cannot peek" << endl; return 0; } else { return top->dataItem; } } //clear function //precondition: stack is not Empty //postcondition: stack is emptied template <typename DataType> void StackLinked<DataType>::clear() { if(isEmpty()) { cout << "Could not clear stack, stack is already empty" << endl; } else { while (!isEmpty()) { pop(); } } } //empty function //precondition: none //postcondition: returns true if stack is empty, false otherwise template <typename DataType> bool StackLinked<DataType>::isEmpty() const { if(top == nullptr) { return true; } else { return false; } } //only for array implementation? template <typename DataType> bool StackLinked<DataType>::isFull() const { return false; } //shows the Stack //precondition: stack must not be Empty //postcondition: the contents of the stack are displayed template <typename DataType> void StackLinked<DataType>::showStructure() const { if( isEmpty() ) { cout << "Empty stack" << endl; } else { cout << "Top\t"; for (StackNode* temp = top; temp != 0; temp = temp->next) { if( temp == top ) { cout << "[" << temp->dataItem << "]\t"; } else { cout << temp->dataItem << "\t"; } } cout << "Bottom" << endl; } } //overloaded node constructor, assigns data and next ptr as passed //precondition: data for the node, pointer for the node //postcondition: a node is created from the data passed template <typename DataType> StackLinked<DataType>::StackNode::StackNode(const DataType& nodeData, StackNode* nextPtr) { dataItem = nodeData; next = nextPtr; }
#include <iostream> const int EMPTY = -987654321; int n, board[50]; int cache[50][50]; int play(int left, int right) { if (left > right) return 0; int& ret = cache[left][right]; if (ret != EMPTY) return ret; ret = std::max(board[left] - play(left + 1, right), board[right] - play(left, right - 1)); if (right - left + 1 >= 2) { ret = std::max(ret, -play(left + 2, right)); ret = std::max(ret, -play(left, right - 2)); } return ret; } int main() { int n_case; std::cin >> n_case; while (n_case) { for (int i = 0; i < 50; ++i) for (int j = 0; j < 50; ++j) cache[i][j] = EMPTY; std::cin >> n; for (int i = 0; i < n; ++i) { int num; std::cin >> num; board[i] = num; } std::cout << play(0, n - 1) << std::endl; --n_case; } return 0; }
#pragma once class GameCursor; class AIEditNodeMenu; class AIEditNodeMenuSave; class AIEditNodeMenuOpen; class AIEditNodeProcess; class AIEditNodeSelectButtons : public GameObject { public: ~AIEditNodeSelectButtons(); bool Start(); void Update(); void Setmenuselect(bool a) { menuselect = a; } bool GetMenuSelect() { return menuselect; } private: bool menuselect = false; bool m_bmenu = false; //mouseover no bool m_bopen = false; //mouseover no bool m_bsave = false; //mouseover no CVector3 m_position2 = CVector3::Zero(); CVector3 m_position3 = CVector3::Zero(); CVector3 m_position4 = CVector3::Zero(); CVector3 m_position5 = CVector3::Zero(); SpriteRender* m_spriterender2 = nullptr; SpriteRender* m_spriterender3 = nullptr; SpriteRender* m_spriterender4 = nullptr; SpriteRender* m_spriterender5 = nullptr; FontRender* m_fmenu = nullptr; //menu no font FontRender* m_fopen = nullptr; //open no font FontRender* m_fsave = nullptr; //save no font GameCursor* m_gamecursor = nullptr; AIEditNodeMenu* m_aieditnodemenu = nullptr; AIEditNodeMenuSave* m_aieditnodemenusave = nullptr; AIEditNodeMenuOpen* m_aieditnodemenuopen = nullptr; AIEditNodeProcess* m_proc = nullptr; };
#include "TeamSprite.h" #include "GameDimens.h" TeamSprite::TeamSprite(){} TeamSprite::TeamSprite(const Team& t) { for(unsigned int i=0; i< t.getTeam().size(); i++) { cout << "on construit un charactersprite" << endl; CharacterSprite* c = new CharacterSprite(t.get(i)); cout << "on ajoute le sprite dans la team" << endl; sprites.push_back(c); cout << "sprite ajoute" << endl; } } TeamSprite::~TeamSprite() { for(unsigned int i=0; i< sprites.size(); i++){ delete sprites[i]; } sprites.clear(); } TeamSprite::TeamSprite(const TeamSprite& other) { for(unsigned int i=0; i< other.sprites.size(); i++) { sprites.push_back(new CharacterSprite(*other.sprites[i])); } } TeamSprite& TeamSprite::operator=(const TeamSprite& rhs) { if (this == &rhs) return *this; // handle self assignment for(unsigned int i=0; i< sprites.size(); i++){ delete sprites[i]; } sprites.clear(); for(unsigned int i=0; i< rhs.sprites.size(); i++) { sprites.push_back(new CharacterSprite(*rhs.sprites[i])); } return *this; } void TeamSprite::add(CharacterSprite* c) { for(unsigned int i=0; i<sprites.size(); i++) { if(sprites[i] == c) { return; } } sprites.push_back(new CharacterSprite(*c)); } void TeamSprite::remove(CharacterSprite* c) { for(unsigned int i=0; i<sprites.size(); i++) { if(sprites[i] == c) { sprites.erase(sprites.begin()+i); delete c; } } } vector <CharacterSprite*> TeamSprite::getTeam() const { return sprites; }
#include <vector> #include <cmath> #include <algorithm> #include <iostream> /* Auxiliary class to calculate characteristics from the data distribution */ struct Sample{ std::vector<double> features; int label; int size; }; class Statistics { public: Statistics(); Statistics(std::size_t); ~Statistics(); std::vector<double> getMean(std::vector<Sample>); std::vector<double> getVariance(std::vector<Sample>); std::vector<double> getStdDev(std::vector<Sample>); std::vector<Sample> normalize(std::vector<Sample>); void setChange(int, bool); private: std::vector<double> mean; std::vector<double> variance; std::vector<double> std_dev; bool changed[3]; };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2011 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef SCOPE_WIDGET_INFO_H #define SCOPE_WIDGET_INFO_H #include "adjunct/desktop_scope/src/generated/g_scope_desktop_window_manager_interface.h" /** @brief Used to get more information about widget contents */ class OpScopeWidgetInfo { public: virtual ~OpScopeWidgetInfo() {} /** Create a list of items this widget consists of * @param list List of items * @param include_invisible Whether items contained in the widget that are not visible should be included in the list */ virtual OP_STATUS AddQuickWidgetInfoItems(OpScopeDesktopWindowManager_SI::QuickWidgetInfoList &list, BOOL include_nonhoverable, BOOL include_invisible = TRUE) = 0; }; #endif // SCOPE_WIDGET_INFO_H
#include<bits/stdc++.h> using namespace std; class Solution { public: int maxProfit(vector<int>& prices) { int min; int maxprofit=0; min=prices[0]; for(int i=0;i<prices.size();i++) { if(min>prices[i]) min=prices[i]; if( (prices[i]-min) > maxprofit) maxprofit=prices[i]-min; } return maxprofit; } };
// Algorithm :Linear Regression // Data : pop.csv #include <iostream> #include <vector> #include "algorithms/GradientDescent.h" using namespace std; int main(int argc, char const *argv[]) { mat X, y,theta; csv_to_xy("datasets/pop.csv", {"X1" ,"X2" ,"X3" , "X4"}, "X5", X, y); gradientDescent(X, y, theta, LeastSquaesCost, LeastSquaesGradient) ; theta.print("Theta found by gradient descent:"); return 0; }
#pragma once #ifndef MAT4_H #define MAT4_H #include <math/Vec3.h> #include <math/Vec4.h> namespace NoHope { class Mat4 { public: Mat4(); Mat4(const Vec4& column1, const Vec4& column2, const Vec4& column3, const Vec4& column4); Mat4(const float a11, const float a12, const float a13, const float a14, const float a21, const float a22, const float a23, const float a24, const float a31, const float a32, const float a33, const float a34, const float a41, const float a42, const float a43, const float a44); ~Mat4(); Mat4(const Mat4& mat4); const float* data(); static Mat4 identity(); static Mat4 createRotationX(const float rotation); static Mat4 createRotationY(const float rotation); static Mat4 createRotationZ(const float rotation); static Mat4 createScale(const Vec3& scale); static Mat4 createScale(const float scale); static Mat4 createTranslation(const Vec3& translation); const Vec4& operator [](unsigned int index) const; Mat4 operator *(const Vec4& vector); Mat4 operator *(const Mat4& mat4); private: Vec4 columns[4]; }; } #endif
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* This library implements coding of a stream of I2S Philips * format audio samples into a mono (left channel) real-time * protocol like format suitable for transmission as datagrams * over an IP link. The coding used is NICAM-like and hence * offers close to 50% compression. * * Speed and efficiency of memory usage are really important here, * hence the heavy use of #defines rather than variables and * run-time calculations. */ #ifndef _URTP_ #define _URTP_ #include <fir.h> /** Urtp class. * * This class takes in block of Philips I2S protocol samples * and encodes them into URTP datagrams. * * URTP: u-blox real time protocol; encode blocks of * audio into simple RTP-like mono audio datagrams. * * The header looks like this: * * Byte | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | * -------------------------------------------------------- * 0 | Sync byte = 0x5A | * 1 | Audio coding scheme | * 2 | Sequence number MSB | * 3 | Sequence number LSB | * 4 | Timestamp MSB | * 5 | Timestamp byte | * 6 | Timestamp byte | * 7 | Timestamp byte | * 8 | Timestamp byte | * 9 | Timestamp byte | * 10 | Timestamp byte | * 11 | Timestamp LSB | * 12 | Number of samples in datagram MSB | * 13 | Number of samples in datagram LSB | * * ...where: * * - Sync byte is always 0x5A, used to sync a frame over a * streamed connection (e.g. TCP). * - Audio coding scheme is one of: * - PCM_SIGNED_16_BIT (0) * - UNICAM_COMPRESSED_8_BIT (1) * - Sequence number is a 16 bit sequence number, incremented * on sending of each datagram. * - Timestamp is a uSecond timestamp representing the moment * of the start of the audio in this datagram. * - Number of bytes to follow is the size of the audio payload * the follows in this datagram. * * There are two audio coding schemes. The default, and most * efficient, is 8 bit UNICAM compression. If UNICAM is not * used, 16 bit RAW PCM is used. * * When the audio coding scheme is PCM_SIGNED_16_BIT, * the payload is as follows: * * Byte | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | *-------------------------------------------------------- * 14 | Sample 0 MSB | * 15 | Sample 0 LSB | * 16 | Sample 1 MSB | * 17 | Sample 1 LSB | * | ... | * N | Sample M MSB | * N+1 | Sample M LSB | * * ...where the number of [big-endian] signed 16-bit samples is between * 0 and 320, so 5120 bits, plus 112 bits of header, gives * an overall data rate of 261.6 kbits/s. * * When the audio coding scheme is UNICAM_COMPRESSED_8_BIT, * the payload is as follows: * * Byte | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | *-------------------------------------------------------- * 14 | Block 0, Sample 0 | * 15 | Block 0, Sample 1 | * | ... | * 28 | Block 0, Sample 14 | * 29 | Block 0, Sample 15 | * 30 | Block 0 shift | Block 1 shift | * 31 | Block 1, Sample 0 | * 32 | Block 1, Sample 1 | * | ... | * 45 | Block 1, Sample 14 | * 46 | Block 1, Sample 15 | * 47 | Block 2, Sample 0 | * 48 | Block 2, Sample 1 | * | ... | * 61 | Block 2, Sample 14 | * 62 | Block 2, Sample 15 | * 63 | Block 2 shift | Block 3 shift | * 64 | Block 3, Sample 0 | * 65 | Block 3, Sample 1 | * | ... | * 78 | Block 3, Sample 14 | * 79 | Block 3, Sample 15 | * | ... | * N | Block M, Sample 0 | * N+1 | Block M, Sample 1 | * | ... | * N+14 | Block M, Sample 14 | * N+15 | Block M, Sample 15 | * N+16 | Block M shift | Block M+1 shift | * N+17 | Block M+1, Sample 0 | * N+18 | Block M+1, Sample 1 | * | ... | * N+31 | Block M+1, Sample 14 | * N+32 | Block M+1, Sample 15 | * * ...where the number of blocks is between 0 and 20, so 330 * bytes in total, plus a 14 byte header gives an overall data * rate of 132 kbits/s. * * The receiving end should be able to reconstruct an audio * stream from this. */ class Urtp { public: /** The audio sampling frequency in Hz. * This is the frequency of the WS signal on the I2S interface */ # ifndef SAMPLING_FREQUENCY # define SAMPLING_FREQUENCY 16000 # endif /** The amount of audio encoded into one URTP block in milliseconds. */ # ifndef BLOCK_DURATION_MS # define BLOCK_DURATION_MS 20 # endif /** The number of bits that a sample is coded into for UNICAM. * Only 8 is supported. */ # ifndef UNICAM_CODED_SAMPLE_SIZE_BITS # define UNICAM_CODED_SAMPLE_SIZE_BITS 8 # endif /** The maximum number of URTP datagrams that will be stored * (old ones will be overwritten). With a block duration of * 20 ms a value of 100 represents around 2 seconds. */ # ifndef MAX_NUM_DATAGRAMS # define MAX_NUM_DATAGRAMS 250 # endif /** The desired number of unused bits to keep in the audio processing * to avoid clipping when we can't move fast enough due to averaging. */ # ifndef AUDIO_DESIRED_UNUSED_BITS # define AUDIO_DESIRED_UNUSED_BITS 4 # endif /** The hysteresis in the gain control in bits. */ # ifndef AUDIO_SHIFT_HYSTERESIS_BITS # define AUDIO_SHIFT_HYSTERESIS_BITS 3 # endif /** The maximum audio shift to use (established by experiment). */ # ifndef AUDIO_MAX_SHIFT_BITS # define AUDIO_MAX_SHIFT_BITS 12 # endif /** Thresholding: audio levels that are within +/- this value * are not shifteed. Set to 0 for no thresholding. */ # ifndef AUDIO_SHIFT_THRESHOLD # define AUDIO_SHIFT_THRESHOLD 0 # endif /** The default shift to use. */ # ifndef AUDIO_SHIFT_DEFAULT # define AUIDIO_SHIFT_DEFAULT (AUDIO_MAX_SHIFT_BITS - AUDIO_SHIFT_HYSTERESIS_BITS) # endif /** The number of consecutive up-shifts that have to be indicated * before a real increase in gain is applied. Each individual * upshift is of BLOCK_DURATION_MS so 50 is 1 second */ # ifndef AUDIO_NUM_UP_SHIFTS_FOR_A_SHIFT # define AUDIO_NUM_UP_SHIFTS_FOR_A_SHIFT 500 # endif /** The number of samples in BLOCK_DURATION_MS. Note that a * sample is stereo when the audio is in raw form but is reduced * to mono when we organise it into URTP packets, hence the size * of a sample is different in each case (64 bits for stereo, * 32 bits for mono). */ # define SAMPLES_PER_BLOCK (SAMPLING_FREQUENCY * BLOCK_DURATION_MS / 1000) /** UNICAM parameters: number of samples in a UNICAM block. */ # define SAMPLES_PER_UNICAM_BLOCK (SAMPLING_FREQUENCY / 1000) /** UNICAM parameters: number of UNICAM blocks per block. */ # define UNICAM_BLOCKS_PER_BLOCK (SAMPLES_PER_BLOCK / SAMPLES_PER_UNICAM_BLOCK) /** UNICAM parameters: the size of two UNICAM blocks (has to be a two since * the shift nibble for two blocks are encoded into one byte). */ # define TWO_UNICAM_BLOCKS_SIZE (((SAMPLES_PER_UNICAM_BLOCK * UNICAM_CODED_SAMPLE_SIZE_BITS) / 8) * 2 + 1) /** The maximum size that we want a decoded unicam sample to end up. */ # define UNICAM_MAX_DECODED_SAMPLE_SIZE_BITS 16 /** URTP parameters: the size of the header */ # define URTP_HEADER_SIZE 14 /** URTP parameters: the size of one input sample, which * is the size of one PCM sample. */ # define URTP_SAMPLE_SIZE 2 # ifndef DISABLE_UNICAM /** URTP parameters: the maximum size of the payload. */ # define URTP_BODY_SIZE ((UNICAM_BLOCKS_PER_BLOCK / 2) * TWO_UNICAM_BLOCKS_SIZE) # else /** URTP parameters: the maximum size of the payload. */ # define URTP_BODY_SIZE (URTP_SAMPLE_SIZE * SAMPLES_PER_BLOCK) # endif /** URTP parameters: the size of a URTP datagram. */ # define URTP_DATAGRAM_SIZE (URTP_HEADER_SIZE + URTP_BODY_SIZE) /** The amount of datagram memory which must be supplied for URTP * to operate. */ # define URTP_DATAGRAM_STORE_SIZE (URTP_DATAGRAM_SIZE * MAX_NUM_DATAGRAMS) /** URTP parameters: the sync byte. */ # define SYNC_BYTE 0x5a /** Constructor. * * @param datagramReadyCb Callback to be invoked once a URTP datagram * has been encoded. IMPORTANT: don't do much * in this callback, simply flag that something * is ready or send a signal saying so to a task. * @param datagramOverflowStartCb Callback to be invoked once the URTP datagram * buffer has begun to overflow. Please don't do * much in this function either, maybe toggle * an LED or set a flag. * @param datagramOverflowStopCb Callback to be invoked once the URTP datagram * buffer is no longer overflowing. Please don't do * much in this function either, maybe toggle * an LED or set a flag. */ Urtp(void(*datagramReadyCb)(const char *), void(*datagramOverflowStartCb)(void) = NULL, void(*datagramOverflowStopCb)(int) = NULL); /** Destructor. */ ~Urtp(); /** Initialise URTP. * * @param datagramStorage a pointer to URTP_DATAGRAM_STORE_SIZE of * memory for datagram buffers. * @param audioShiftMax the maximum audio shift, default is * AUDIO_MAX_SHIFT_BITS, lower numbers will * lower the maximum gain. * @return true if successful, otherwise false. */ bool init(void *datagramStorage, int audioShiftMax = AUDIO_MAX_SHIFT_BITS); /** URTP encode an audio block. * Only the samples from the LEFT CHANNEL (i.e. the even uint32_t's) are * used. * * The Philips I2S protocol (24-bit frame with CPOL = 0 to read * the data on the rising edge) looks like this. Each data bit * is valid on the rising edge of SCK and the MSB of the data word is * clocked out on the second clock edge after WS changes. WS is low * for the left channel and high for the right channel. * ___ ______________________ ___ * WS \____________...________..._____/ ... \______ * 0 1 2 23 24 31 32 33 34 55 56 63 * SCK ___ _ _ _ _ _ _ _ _ _ _ _ _ _ * \_/ \_/ \_/ \...\_/ \_/ ...\_/ \_/ \_/ \_/ \...\_/ \_/ ...\_/ \_/ \_ * * SD ________--- --- --- --- ___________--- --- --- ---_____________ * --- --- ... --- --- --- --- ... --- --- * 23 22 1 0 23 22 1 0 * Left channel data Right channel data * * @param rawAudio a pointer to a buffer of SAMPLES_PER_BLOCK * 2 uint32_t's * (i.e. stereo) of Philips I2S protocol data: 24-bit frame * with CPOL = 0. */ void codeAudioBlock(const uint32_t *rawAudio); /** Call this to obtain a pointer to a URTP datagram that has been * prepared. * * @return a pointer to the next URTP datagram that has been * prepared, NULL if there is none. */ const char * getUrtpDatagram(); /** Call this to free a URTP datagram and move the read pointer on. * * @param datagram a pointer to a member of the datagram array * that should be freed. */ void setUrtpDatagramAsRead(const char *datagram); /** Call this to get the number of URTP datagrams available. * * @return the number of datagrams available. */ int getUrtpDatagramsAvailable(); /** Call this to get the number of URTP datagrams free. * * @return the number of datagrams free. */ int getUrtpDatagramsFree(); /** Call this to get the low water mark of the number of * URTP datagrams free. * * @return the minimum number of datagrams free. */ int getUrtpDatagramsFreeMin(); /** Call this to get the last URTP sequence number. * * @return the lsat URTP sequence number. */ int getUrtpSequenceNumber(); protected: /** The number of valid bytes in each mono sample of audio received * on the I2S stream (the number of bytes received may be larger * but some are discarded along the way). */ # define MONO_INPUT_SAMPLE_SIZE 3 /** The audio coding schemes. */ typedef enum { PCM_SIGNED_16_BIT = 0, UNICAM_COMPRESSED_8_BIT = 1 } AudioCoding; /** The possible states for a container. * * The normal life cycle for a container is: * * EMPTY * WRITING * READY_TO_READ * READING * EMPTY */ typedef enum { CONTAINER_STATE_EMPTY, CONTAINER_STATE_WRITING, CONTAINER_STATE_READY_TO_READ, CONTAINER_STATE_READING, MAX_NUM_CONTAINER_STATES } ContainerState; /** A linked list container, used to manage datagrams * as a FIFO. */ typedef struct ContainerTag { ContainerState state; void *contents; ContainerTag *next; } Container; /** Callback to be called when a datagram has been populated. * The parameter is a pointer to the datagram. */ void(*_datagramReadyCb)(const char *); /** Callback to be called when the datagram buffer begins overflowing. */ void(*_datagramOverflowStartCb)(void); /** Callback to be called when the datagram buffer stops overflow. * The parameter indicates hte number of datagram overflows that * occurred. */ void(*_datagramOverflowStopCb)(int); /** The number of samples that have been used so far in * evaluation the audio bit-shift */ int _audioShiftSampleCount; /** The minimum value of the number of unused bits */ int _audioUnusedBitsMin; /** The current audio shift value. */ int _audioShift; /** A count of the number of times that an * increase in shift has been suggested. */ int _audioUpShiftCount; /** The maximum audio shift value. */ int _audioShiftMax; /** Buffer for UNICAM coding. */ int _unicamBuffer[SAMPLES_PER_UNICAM_BLOCK]; /** The FIR pre-emphasis filter for unicam encoding */ Fir _preemphasis; /** Pointer to the URTP datagrams. */ char *_datagramMemory; /** A linked list to manage the datagrams, must have the same * number of elements as gDatagram. */ Container _container[MAX_NUM_DATAGRAMS]; /** A sequence number for the URTP datagrams. */ int _sequenceNumber; /** Pointer to the next container to write to. */ Container *_containerNextForWriting; /** Pointer to the first filled container for reading. */ Container *_containerNextForReading; /** Diagnostics: a count of the number of consecutive datagram * overflows that have occurred. */ int _numDatagramOverflows; /** Diagnostics: The current number of datagrams free. */ unsigned int _numDatagramsFree; /** Diagnostics: The minimum number of datagrams free. */ unsigned int _minNumDatagramsFree; /** Take an audio sample and from it produce a signed * output that uses the maximum number of bits * in a 32 bit word (hopefully) without clipping. * The algorithm is as follows: * * Calculate how many of bits of the input value are unused. * Add this to a rolling average of unused bits of length * AUDIO_AVERAGING_INTERVAL_MILLISECONDS, which starts off at 0. * Every AUDIO_AVERAGING_INTERVAL_MILLISECONDS work out whether. * the average number of unused is too large and, if it is, * increase the gain, or if it is too small, decrease the gain. * * @param monoSample a mono audio sample. * @return the output mono audio sample. */ int processAudio(int monoSample); /** Take a stereo sample and return an int * containing a sample that will fit within * MONO_INPUT_SAMPLE_SIZE but sign extended * so that it can be treated as an int for * maths purposes. * * @param stereoSample a pointer to a 2 uint32_t * stereo audio sample in * Philips I2S 24-bit format. * @return the output mono audio sample. */ inline int getMonoSample(const uint32_t *stereoSample); /** Take a buffer of rawAudio and code the samples from * the left channel (i.e. the even uint32_t's) into dest. * * Here we use the principles of NICAM coding, see * http:www.doc.ic.ac.uk/~nd/surprise_97/journal/vol2/aps2/ * We take 1 ms of audio data, so 16 samples (SAMPLES_PER_UNICAM_BLOCK), * and work out the peak. Then we shift all the samples in the * block down so that they fit in just UNICAM_CODED_SAMPLE_SIZE_BITS. * Then we put the shift value in the lower four bits of the next * byte. In order to pack things neatly, the shift value for the * following block is encoded into the upper four bits, followed by * the shifted samples for that block, etc. * * This represents UNICAM_COMPRESSED_8_BIT. * * @param rawAudio a pointer to a buffer of * SAMPLES_PER_BLOCK * 2 uint32_t's * (i.e. stereo), each in Philips I2S * 24-bit format. * @param dest a pointer to an empty datagram. */ int codeUnicam(const uint32_t *rawAudio, char *dest); /** Take a buffer of rawAudio and copy the samples from * the left channel (i.e. the even uint32_t's) into dest. * Each byte is passed through processAudio() before it * is coded. * * This represents PCM_SIGNED_16_BIT. * * @param rawAudio a pointer to a buffer of * SAMPLES_PER_BLOCK * 2 uint32_t's * (i.e. stereo), each in Philips I2S * 24-bit format. * @param dest a pointer to an empty datagram. */ int codePcm(const uint32_t *rawAudio, char *dest); /** Fill a datagram with the audio from one block. * Only the samples from the left channel * (i.e. the even uint32_t's) are used. * * @param rawAudio a pointer to a buffer of * SAMPLES_PER_BLOCK * 2 uint32_t's * (i.e. stereo), each in Philips I2S * 24-bit format. */ void fillMonoDatagramFromBlock(const uint32_t *rawAudio); /** For the UNICAM compression scheme, we need * the right shift operation to be arithmetic * (so preserving the sign bit) rather than * logical. This function tests that this is * the case. * * @return true if OK for UNICAM, otherwise false. */ bool unicamTest(); /** Get the next container for writing. Always returns * something, even if it is necessary to overwrite old data. * The container will be marked as WRITING. * * @return a pointer to the container. */ inline Urtp::Container * getContainerForWriting(); /** Set the given container as ready to read. * * @param container a pointer to the container. */ inline void setContainerAsReadyToRead(Urtp::Container * container); /** Get the next container for reading. If there is a container, * that can be read, it will be marked READING. If there are no * containers for reading, NULL will be returned. * * @return a pointer to the container, may be NULL. */ inline Urtp::Container * getContainerForReading(); /** Set the given container as read. * * @param container a pointer to the container. */ inline void setContainerAsRead(Urtp::Container * container); /** Set the given container as empty. * * @param container a pointer to the container. */ inline void setContainerAsEmpty(Urtp::Container * container); }; #endif // _URTP_
INSANE_SKIP_xmlsec1-dev-static = "staticdev" xmlsec1-dev_files += "${prefix}/lib/lib*.so*" DEPENDS += "libgcrypt"
#include <iostream> #include <queue> #include <vector> #include "Graph.h" using namespace std; class GraphBFS{ private: Graph g; vector<bool> visited; vector<int> order; void bfs(int s){ queue<int> q; q.push(s); visited[s] = true; while (!q.empty()){ int vertex = q.front(); q.pop(); order.push_back(vertex); for (int x : g.adjL(vertex)){ if (!visited[x]){ q.push(x); visited[x] = true; } } } } public: GraphBFS(const Graph& g):g(g){ visited = vector<bool>(g.getV(), false); for (int i = 0; i < g.getV(); ++i){ if (!visited[i]) bfs(i); } } vector<int> getOrder() const{ return order; } }; int main(){ Graph g("bfsg.txt"); GraphBFS gbfs(g); vector<int> ans = gbfs.getOrder(); for (int i : ans){ cout << i << ' '; } cout << endl; return 0; }
//算法:DP/01背包 //本题为01背包变体,除体积外,另增一维质量 //只需要将一维数组转变为二维数组, //并多加一层循环即可 //状态转移方程式:f[j][k]=max(f[j][k],f[j-v[i]][k-w[i]]+c[i]); #include<cstdio> #include<algorithm> using namespace std; int vm,mm; int n; int v[51];//体积 int w[51];//质量 int c[51];//价值 int f[410][410];//前体积,后质量 int main() { scanf("%d%d%d",&vm,&mm,&n); for(int i=1;i<=n;i++) scanf("%d%d%d",&v[i],&w[i],&c[i]); for(int i=1;i<=n;i++) for(int j=vm;j>=v[i];j--) for(int k=mm;k>=w[i];k--) f[j][k]=max(f[j][k],f[j-v[i]][k-w[i]]+c[i]); printf("%d",f[vm][mm]); }
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2011 Bryce Lelbach // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) //////////////////////////////////////////////////////////////////////////////// #pragma once #include <pika/config.hpp> #if defined(PIKA_MSVC) # include <pika/timing/detail/timestamp/msvc.hpp> #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || \ defined(_M_X64) # if (defined(PIKA_HAVE_RDTSC) || defined(PIKA_HAVE_RDTSCP)) && !defined(PIKA_NVHPC_VERSION) # include <pika/timing/detail/timestamp/linux_x86_64.hpp> # else # include <pika/timing/detail/timestamp/linux_generic.hpp> # endif #elif defined(i386) || defined(__i386__) || defined(__i486__) || defined(__i586__) || \ defined(__i686__) || defined(__i386) || defined(_M_IX86) || defined(__X86__) || \ defined(_X86_) || defined(__THW_INTEL__) || defined(__I86__) || defined(__INTEL__) # if (defined(PIKA_HAVE_RDTSC) || defined(PIKA_HAVE_RDTSCP)) && !defined(PIKA_NVHPC_VERSION) # include <pika/timing/detail/timestamp/linux_x86_32.hpp> # else # include <pika/timing/detail/timestamp/linux_generic.hpp> # endif #elif (defined(__ANDROID__) && defined(ANDROID)) # include <pika/timing/detail/timestamp/linux_generic.hpp> #elif defined(__arm__) || defined(__arm64__) || defined(__aarch64__) # include <pika/timing/detail/timestamp/linux_generic.hpp> #elif defined(__ppc__) || defined(__ppc) || defined(__powerpc__) # include <pika/timing/detail/timestamp/linux_generic.hpp> #elif defined(__s390x__) # include <pika/timing/detail/timestamp/linux_generic.hpp> #elif defined(__bgq__) # include <pika/timing/detail/timestamp/bgq.hpp> #else # error Unsupported platform. #endif
#ifndef FRAMEVIEWER_H #define FRAMEVIEWER_H #include <QTableWidget> class FrameViewer : public QTableWidget { Q_OBJECT public: explicit FrameViewer(QWidget *parent = 0); QModelIndexList selectedIndexesList(void); }; #endif // FRAMEVIEWER_H
/* -*- coding: utf-8 -*- !@time: 2020/1/11 上午10:02 !@author: superMC @email: 18758266469@163.com !@fileName: 0034_the_first_character_that_appears_only_once.cpp */ #include <environment.h> class Solution { public: int FirstNotRepeatingChar(string str) { map<char, int> mp; for (char i : str) mp[i]++; for (int i = 0; i < str.size(); ++i) { if (mp[str[i]] == 1) return i; } return -1; } }; int fun() { string str = "Hello World"; int ret = Solution().FirstNotRepeatingChar(str); printf("%d", ret); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- * * Copyright (C) Opera Software ASA 1999-2004 */ #include "core/pch.h" #include "modules/ecmascript/carakan/src/es_pch.h" #include "modules/ecmascript/carakan/src/object/es_boolean_object.h" #include "modules/ecmascript/carakan/src/object/es_global_object.h" #include "modules/ecmascript/carakan/src/builtins/es_boolean_builtins.h" /* static */ ES_Boolean_Object * ES_Boolean_Object::Make(ES_Context *context, ES_Global_Object *global_object, BOOL value) { ES_Boolean_Object *boolean; GC_ALLOCATE(context, boolean, ES_Boolean_Object, (boolean, global_object->GetBooleanClass(), value)); ES_CollectorLock gclock(context); boolean->AllocateProperties(context); return boolean; } /* static */ ES_Boolean_Object * ES_Boolean_Object::MakePrototypeObject(ES_Context *context, ES_Global_Object *global_object, ES_Class *&instance) { JString **idents = context->rt_data->idents; ES_Boolean_Object *prototype_object; ES_Class_Singleton *prototype_class = ES_Class::MakeSingleton(context, global_object->GetObjectPrototype(), "Boolean", idents[ESID_Boolean], ES_BooleanBuiltins::ES_BooleanBuiltinsCount); prototype_class->Prototype()->AddInstance(context, prototype_class, TRUE); ES_CollectorLock gclock(context); ES_BooleanBuiltins::PopulatePrototypeClass(context, prototype_class); GC_ALLOCATE(context, prototype_object, ES_Boolean_Object, (prototype_object, prototype_class, FALSE)); prototype_class->AddInstance(context, prototype_object); prototype_object->AllocateProperties(context); ES_BooleanBuiltins::PopulatePrototype(context, global_object, prototype_object); instance = ES_Class::MakeRoot(context, prototype_object, "Boolean", idents[ESID_Boolean], TRUE); prototype_object->SetSubObjectClass(context, instance); return prototype_object; }
class Solution { public: bool isToeplitzMatrix(vector<vector<int>>& matrix) { int a = 0; int b = 0; while(a<matrix.size()&&b<matrix[0].size()){ int i = a; int j = b; ++a; while(i+1<matrix.size()&&j+1<matrix[0].size()){ if(matrix[i][j]==matrix[i+1][j+1]){ ++i; ++j; }else{ return false; } } } a = 0; b = 0; while(a<matrix.size()&&b<matrix[0].size()){ int i = a; int j = b; ++b; while(i+1<matrix.size()&&j+1<matrix[0].size()){ if(matrix[i][j]==matrix[i+1][j+1]){ ++i; ++j; }else{ return false; } } } return true; } };
#pragma once #include "ResourceManager.h" #include "EngineUtil.h" #include "FreeImage.h" class Image{ public: string name;//file name string filepath; enum ImageFormat { IM_JPEG, IM_PNG, IM_TGA, IM_BMP, IM_HDR, IM_UNKNOWN }; enum ImagePixelFormat { UNSIGNED_BYTE, UNSIGNED_SHORT, UNSIGNED_INT, UNSIGNED_INT_24_8, UNSIGNED_CHAR_8_8_8, UNSIGNED_CHAR_8_8_8_8, UNSIGNED_CHAR_10_10_10_2, FLOAT_32, FLOAT_32_32_32, FLOAT_32_32_32_32, FLOAT_16_16_16_16, FLOAT_16_16_16, UNSIGNED_INT_16_16_16_16 }; ImageFormat mImageformat = IM_UNKNOWN; ImagePixelFormat mPixelformat; unsigned int width=0, height=0; unsigned int bpp=0; void * pdata=NULL; bool bgra = false; Image* LoadImage(string filepath); Image* CreateImageFromData(ImagePixelFormat format,int width,int height,void* data,string name=""); bool m_valid = false; void test(); private: void readDataBytes(FIBITMAP * fib, void*& dst); ImageFormat getImageFormat(FREE_IMAGE_FORMAT fm); void ConvertBetweenBGRandRGB(unsigned char* input, int pixel_width, int pixel_height,int bytes_per_pixel); }; class ImageManager :public as_ResourceManager<Image*>{ public: static ImageManager& getInstance() { static ImageManager instance; return instance; } Image* CreateImageFromFile(string filepath); vector<Image*> CreateImageListFromFiles(vector<string> paths); private: ImageManager(){ } ImageManager(ImageManager const&); // Don't Implement. void operator=(ImageManager const&); // Don't implement };
#include <cstdio> #include <cstdlib> #include <fstream> #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Weverything" #endif #include "cxxopts.hpp" #include "json.hpp" #define DR_WAV_IMPLEMENTATION #include "dr_wav.h" #ifdef __clang__ #pragma clang diagnostic pop #endif #include "tf_synthesizer.h" template<typename T> bool GetNumberArray(const nlohmann::json &j, const std::string &name, std::vector<T> *value) { if (j.find(name) == j.end()) { std::cerr << "Property not found : " << name << std::endl; return false; } if (!j.at(name).is_array()) { std::cerr << "Property is not an array type : " << name << std::endl; return false; } std::vector<T> v; for (auto &element : j.at(name)) { if (!element.is_number()) { std::cerr << "An array element is not a number" << std::endl; return false; } v.push_back(static_cast<T>(element.get<double>())); } (*value) = v; return true; } // Load sequence from JSON array bool LoadSequence(const std::string &sequence_filename, std::vector<int32_t> *sequence) { std::ifstream is(sequence_filename); if (!is) { std::cerr << "Failed to open/read file : " << sequence_filename << std::endl; return false; } nlohmann::json j; is >> j; return GetNumberArray(j, "sequence", sequence); } static uint16_t ftous(const float x) { int f = int(x); return std::max(uint16_t(0), std::min(std::numeric_limits<uint16_t>::max(), uint16_t(f))); } bool SaveWav(const std::string &filename, const std::vector<float> &samples, const int sample_rate) { // We want to save audio with 32bit float format without loosing precision, // but librosa only supports PCM audio, so save audio data as 16bit PCM. drwav_data_format format; format.container = drwav_container_riff; // <-- drwav_container_riff = normal WAV files, drwav_container_w64 = Sony Wave64. format.format = DR_WAVE_FORMAT_PCM; format.channels = 1; format.sampleRate = sample_rate; format.bitsPerSample = 16; drwav* pWav = drwav_open_file_write(filename.c_str(), &format); std::vector<unsigned short> data; data.resize(samples.size()); float max_value = std::fabs(samples[0]); for (size_t i = 0; i < samples.size(); i++) { max_value = std::max(max_value, std::fabs(samples[i])); } std::cout << "max value = " << max_value; float factor = 32767.0f / std::max(0.01f, max_value); // normalize & 16bit quantize. for (size_t i = 0; i < samples.size(); i++) { data[i] = ftous(factor * samples[i]); } drwav_uint64 n = static_cast<drwav_uint64>(samples.size()); drwav_uint64 samples_written = drwav_write(pWav, n, data.data()); drwav_close(pWav); if (samples_written > 0) return true; return false; } int main(int argc, char **argv) { cxxopts::Options options("tts", "Tacotron text to speec in C++"); options.add_options()("i,input", "Input sequence file(JSON)", cxxopts::value<std::string>())( "g,graph", "Input freezed graph file", cxxopts::value<std::string>()) ("h,hparams", "Hyper parameters(JSON)", cxxopts::value<std::string>()); ("o,output", "Output WAV filename", cxxopts::value<std::string>()); auto result = options.parse(argc, argv); if (!result.count("input")) { std::cerr << "Please specify input sequence file with -i or --input option." << std::endl; return -1; } if (!result.count("graph")) { std::cerr << "Please specify freezed graph with -g or --graph option." << std::endl; return -1; } if (result.count("hparams")) { } std::string input_filename = result["input"].as<std::string>(); std::string graph_filename = result["graph"].as<std::string>(); std::string output_filename = "output.wav"; if (result.count("output")) { output_filename = result["output"].as<std::string>(); } std::vector<int32_t> sequence; if (!LoadSequence(input_filename, &sequence)) { std::cerr << "Failed to load sequence data : " << input_filename << std::endl; return EXIT_FAILURE; } std::cout << "sequence = ["; for (size_t i = 0; i < sequence.size(); i++) { std::cout << sequence[i]; if (i != (sequence.size() - 1)) { std::cout << ", "; } } std::cout << "]" << std::endl; // Synthesize(generate wav from sequence) tts::TensorflowSynthesizer tf_synthesizer; tf_synthesizer.init(argc, argv); if (!tf_synthesizer.load(graph_filename, "inputs", "model/griffinlim/Squeeze")) { std::cerr << "Failed to load/setup Tensorflow model from a frozen graph : " << graph_filename << std::endl; return EXIT_FAILURE; } std::cout << "Synthesize..." << std::endl; std::vector<int32_t> input_lengths; input_lengths.push_back(int(sequence.size())); std::vector<float> output_wav; if (!tf_synthesizer.synthesize(sequence, input_lengths, &output_wav)) { std::cerr << "Failed to synthesize for a given sequence." << std::endl; return EXIT_FAILURE; } if (!SaveWav(output_filename, output_wav, /* sample rate */20000)) { std::cerr << "Failed to save wav file :" << output_filename << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
#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; const int maxn = 20000 + 100; const int maxm = 100000 + 100; struct Edge{ int from,to,dist; }; struct Qes{ int d,loc; }; int f[maxn],num[maxn],sav[5010]; Edge edge[maxm]; Qes qes[5010]; bool cmp(Edge a,Edge b) { return a.dist < b.dist; } bool cmp2(Qes a,Qes b) { return a.d < b.d; } int find(int k) { stack<int> S; while (f[k] != k) { S.push(k); k = f[k]; } while (!S.empty()) { int t = S.top();S.pop(); f[t] = k; } return k; } int fig(int k) { return k*(k-1); } int main() { int t; int n,m,q; scanf("%d",&t); while (t--) { scanf("%d%d%d",&n,&m,&q); for (int i = 1;i <= n; i++) { f[i] = i; num[i] = 1; } for (int i = 0;i < m; i++) scanf("%d%d%d",&edge[i].from,&edge[i].to,&edge[i].dist); sort(edge,edge+m,cmp); for (int i = 0;i < q; i++) { scanf("%d",&qes[i].d); qes[i].loc = i; } sort(qes,qes+q,cmp2); int j = 0,ans = 0; for (int i = 0;i < q; i++) { while (j < m && edge[j].dist <= qes[i].d) { int a = find(edge[j].from); int b = find(edge[j].to); if (a != b) { f[b] = a; ans = ans - fig(num[a]) - fig(num[b]) + fig(num[a] + num[b]); num[a] += num[b]; } j++; } sav[qes[i].loc] = ans; } for (int i = 0;i < q; i++) printf("%d\n",sav[i]); } return 0; }
#include <cstdio> int main(int argc, char** argv) { int c; while ( (c=getchar()) != EOF ) { putchar(c); } return 0; }
// Created on: 2016-07-07 // Copyright (c) 2016 OPEN CASCADE SAS // Created by: Oleg AGASHIN // // 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 _BRepMesh_DefaultRangeSplitter_HeaderFile #define _BRepMesh_DefaultRangeSplitter_HeaderFile #include <IMeshData_Face.hxx> struct IMeshTools_Parameters; //! Default tool to define range of discrete face model and //! obtain grid points distributed within this range. class BRepMesh_DefaultRangeSplitter { public: //! Constructor. BRepMesh_DefaultRangeSplitter() : myIsValid (Standard_True) { } //! Destructor. virtual ~BRepMesh_DefaultRangeSplitter() { } //! Resets this splitter. Must be called before first use. Standard_EXPORT virtual void Reset(const IMeshData::IFaceHandle& theDFace, const IMeshTools_Parameters& theParameters); //! Registers border point. Standard_EXPORT virtual void AddPoint(const gp_Pnt2d& thePoint); //! Updates discrete range of surface according to its geometric range. Standard_EXPORT virtual void AdjustRange(); //! Returns True if computed range is valid. Standard_EXPORT virtual Standard_Boolean IsValid(); //! Scales the given point from real parametric space //! to face basis and otherwise. //! @param thePoint point to be scaled. //! @param isToFaceBasis if TRUE converts point to face basis, //! otherwise performs reverse conversion. //! @return scaled point. Standard_EXPORT gp_Pnt2d Scale(const gp_Pnt2d& thePoint, const Standard_Boolean isToFaceBasis) const; //! Returns list of nodes generated using surface data and specified parameters. //! By default returns null ptr. Standard_EXPORT virtual Handle(IMeshData::ListOfPnt2d) GenerateSurfaceNodes( const IMeshTools_Parameters& theParameters) const; //! Returns point in 3d space corresponded to the given //! point defined in parameteric space of surface. gp_Pnt Point(const gp_Pnt2d& thePoint2d) const { return GetSurface()->Value(thePoint2d.X(), thePoint2d.Y()); } protected: //! Computes parametric tolerance taking length along U and V into account. Standard_EXPORT virtual void computeTolerance (const Standard_Real theLenU, const Standard_Real theLenV); //! Computes parametric delta taking length along U and V and value of tolerance into account. Standard_EXPORT virtual void computeDelta (const Standard_Real theLengthU, const Standard_Real theLengthV); public: //! Returns face model. const IMeshData::IFaceHandle& GetDFace() const { return myDFace; } //! Returns surface. const Handle(BRepAdaptor_Surface)& GetSurface() const { return myDFace->GetSurface(); } //! Returns U range. const std::pair<Standard_Real, Standard_Real>& GetRangeU() const { return myRangeU; } //! Returns V range. const std::pair<Standard_Real, Standard_Real>& GetRangeV() const { return myRangeV; } //! Returns delta. const std::pair<Standard_Real, Standard_Real>& GetDelta () const { return myDelta; } const std::pair<Standard_Real, Standard_Real>& GetToleranceUV() const { return myTolerance; } private: //! Computes length along U direction. Standard_Real computeLengthU(); //! Computes length along V direction. Standard_Real computeLengthV(); //! Updates discrete range of surface according to its geometric range. void updateRange(const Standard_Real theGeomFirst, const Standard_Real theGeomLast, const Standard_Boolean isPeriodic, Standard_Real& theDiscreteFirst, Standard_Real& theDiscreteLast); protected: IMeshData::IFaceHandle myDFace; std::pair<Standard_Real, Standard_Real> myRangeU; std::pair<Standard_Real, Standard_Real> myRangeV; std::pair<Standard_Real, Standard_Real> myDelta; std::pair<Standard_Real, Standard_Real> myTolerance; Standard_Boolean myIsValid; }; #endif
// The MIT License (MIT) // Copyright (c) 2013 lailongwei<lailongwei@126.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef __LLBC_CORE_EVENT_EVENT_H__ #define __LLBC_CORE_EVENT_EVENT_H__ #include "llbc/common/Common.h" #include "llbc/core/variant/Variant.h" __LLBC_NS_BEGIN /** * \brief The event class encapsulation. */ class LLBC_EXPORT LLBC_Event { public: LLBC_Event(int id = 0); virtual ~LLBC_Event(); public: /** * Get the event Id. * @return int - the event Id. */ int GetId() const; public: /** * Add sequential event param. * @param[in] param - the event param. * @return LLBC_Event & - this reference. */ LLBC_Event &AddParam(const LLBC_Variant &param); /** * Add sequential event param(template version). * @param[in] param - the event param. * @return LLBC_Event & - this reference. */ template <typename ParamType> LLBC_Event &AddParam(const ParamType &param); /** * Add naming event param. * @param[in] key - the param key. * @param[in] param - the param. * @return LLBC_Event & - this reference. */ LLBC_Event &AddParam(const LLBC_String &key, const LLBC_Variant &param); /** * Add naming event param(template version). * @param[in] key - the param key. * @param[in] param - the param. * @return LLBC_Event & - this reference. */ template <typename ParamType> LLBC_Event &AddParam(const LLBC_String &key, const ParamType &param); public: /** * Get all sequential params. * @return const std::vector<LLBC_Variant> & - the sequential params const reference. */ const std::vector<LLBC_Variant> &GetSequentialParams() const; /** * Get sequential params count. * @return size_t - the sequential params count. */ size_t GetSequentialParamsCount() const; /** * Get all naming params. * @return const std::map<LLBC_String, LLBC_Variant> & - the naming params const reference. */ const std::map<LLBC_String, LLBC_Variant> &GetNamingParams() const; /** * Get naming params count. * @return size_t - the naming params count. */ size_t GetNamingParamsCount() const; public: /** * Subscript supports. */ const LLBC_Variant &operator [](size_t index) const; const LLBC_Variant &operator [](const LLBC_String &key) const; /** * Disable assignment. */ LLBC_DISABLE_ASSIGNMENT(LLBC_Event); protected: int _id; typedef std::vector<LLBC_Variant> _SeqParams; _SeqParams *_seqParams; typedef std::map<LLBC_String, LLBC_Variant> _NamingParams; _NamingParams *_namingParams; }; __LLBC_NS_END #include "llbc/core/event/EventImpl.h" #endif // !__LLBC_CORE_EVENT_EVENT_H__
#include "../../include/Jogo/graph.h" #include <unistd.h> void Gbase::printG(int color){ int i,j; CubePoint p; for(i = x; i < x+3; i++) for(j = y; j < y+3; j++) { if(a[i - x][j - y] == 1) { p.setLocate(i,j); p.setColor(color); p.printPoint(); } } } int Gbase::move(int dir){ switch(dir){ case DOWN:x++;break; case LEFT:y--;break; case RIGHT:y++;break; default: break; } return 0; } int Gbase::roll(){ int i,j; int b[3][3]; for(i = 0; i < 3; i++){ for(j = 0; j < 3; j++) { b[2-j][i] = a[i][j]; } } for(i = 0; i < 3; i++){ for(j = 0; j < 3; j++) { a[i][j] = b[i][j]; } } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** 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" #include "modules/logdoc/htm_ldoc.h" #include "modules/logdoc/logdoc_util.h" #include "modules/doc/loadinlineelm.h" #include "modules/encodings/decoders/inputconverter.h" #include "modules/encodings/encoders/outputconverter.h" #include "modules/encodings/utility/charsetnames.h" #include "modules/formats/uri_escape.h" #include "modules/logdoc/htm_elm.h" #include "modules/logdoc/htm_lex.h" #include "modules/logdoc/html5parser.h" #include "modules/logdoc/logdoc.h" #include "modules/prefs/prefsmanager/collections/pc_network.h" #ifdef PICTOGRAM_SUPPORT # include "modules/logdoc/src/picturlconverter.h" #endif // PICTOGRAM_SUPPORT #include "modules/logdoc/attr_val.h" #include "modules/logdoc/data/entities_len.h" #include "modules/probetools/probepoints.h" #include "modules/security_manager/include/security_manager.h" #include "modules/url/url_man.h" #include "modules/encodings/utility/opstring-encodings.h" const int AttrvalueNameMaxSize = 14; /** * This denotes where ATTR_value_name-s of a particular length begin. * So, at 34 those attribute values of length 5 start and such */ static const short ATTR_value_idx[] = { 0, // start idx size 0 0, // start idx size 1 0, // start idx size 2 3, // start idx size 3 15, // start idx size 4 34, // start idx size 5 46, // start idx size 6 63, // start idx size 7 67, // start idx size 8 74, // start idx size 9 78, // start idx size 10 78, // start idx size 11 78, // start idx size 12 78, // start idx size 13 78, // start idx size 14 79 // start idx size 15 }; /// Table of attribute values. CONST_ARRAY(ATTR_value_name, char*) CONST_ENTRY("NO"), // pos 0 CONST_ENTRY("EN"), CONST_ENTRY("UP"), CONST_ENTRY("PUT"), // pos 3 CONST_ENTRY("GET"), CONST_ENTRY("YES"), CONST_ENTRY("ALL"), CONST_ENTRY("TOP"), CONST_ENTRY("LTR"), CONST_ENTRY("RTL"), CONST_ENTRY("BOX"), CONST_ENTRY("LHS"), CONST_ENTRY("RHS"), CONST_ENTRY("TEL"), CONST_ENTRY("URL"), CONST_ENTRY("AUTO"), // pos 15 CONST_ENTRY("DISC"), CONST_ENTRY("POST"), CONST_ENTRY("TEXT"), CONST_ENTRY("FILE"), CONST_ENTRY("CIRC"), CONST_ENTRY("POLY"), CONST_ENTRY("LEFT"), CONST_ENTRY("HIDE"), CONST_ENTRY("SHOW"), CONST_ENTRY("VOID"), CONST_ENTRY("NONE"), CONST_ENTRY("ROWS"), CONST_ENTRY("COLS"), CONST_ENTRY("DOWN"), CONST_ENTRY("BOTH"), CONST_ENTRY("DATE"), CONST_ENTRY("WEEK"), CONST_ENTRY("TIME"), CONST_ENTRY("COLOR"), // pos 34 CONST_ENTRY("RESET"), CONST_ENTRY("IMAGE"), CONST_ENTRY("RIGHT"), CONST_ENTRY("FALSE"), CONST_ENTRY("RADIO"), CONST_ENTRY("ABOVE"), CONST_ENTRY("BELOW"), CONST_ENTRY("SLIDE"), CONST_ENTRY("EMAIL"), CONST_ENTRY("RANGE"), CONST_ENTRY("MONTH"), CONST_ENTRY("BUTTON"), // pos 46 CONST_ENTRY("BOTTOM"), CONST_ENTRY("CIRCLE"), CONST_ENTRY("PIXELS"), CONST_ENTRY("SEARCH"), CONST_ENTRY("SQUARE"), CONST_ENTRY("SUBMIT"), CONST_ENTRY("MIDDLE"), CONST_ENTRY("CENTER"), CONST_ENTRY("HIDDEN"), CONST_ENTRY("SILENT"), CONST_ENTRY("HSIDES"), CONST_ENTRY("VSIDES"), CONST_ENTRY("BORDER"), CONST_ENTRY("GROUPS"), CONST_ENTRY("SCROLL"), CONST_ENTRY("NUMBER"), CONST_ENTRY("DEFAULT"), // pos 63 CONST_ENTRY("JUSTIFY"), CONST_ENTRY("POLYGON"), CONST_ENTRY("INHERIT"), CONST_ENTRY("FILEOPEN"), // pos 67 CONST_ENTRY("BASELINE"), CONST_ENTRY("RELATIVE"), CONST_ENTRY("CHECKBOX"), CONST_ENTRY("PASSWORD"), CONST_ENTRY("INFINITE"), CONST_ENTRY("DATETIME"), CONST_ENTRY("ABSBOTTOM"), // pos 74 CONST_ENTRY("ABSMIDDLE"), CONST_ENTRY("MOUSEOVER"), CONST_ENTRY("ALTERNATE"), CONST_ENTRY("DATETIME-LOCAL") // pos 78 CONST_END(ATTR_value_name) /// Numeric values for each attribute string. Offset must match the string table. static const BYTE ATTR_value_tok[] = { ATTR_VALUE_no, ATTR_VALUE_en, ATTR_VALUE_up, ATTR_VALUE_put, ATTR_VALUE_get, ATTR_VALUE_yes, ATTR_VALUE_all, ATTR_VALUE_top, ATTR_VALUE_ltr, ATTR_VALUE_rtl, ATTR_VALUE_box, ATTR_VALUE_lhs, ATTR_VALUE_rhs, ATTR_VALUE_tel, ATTR_VALUE_url, ATTR_VALUE_auto, ATTR_VALUE_disc, ATTR_VALUE_post, ATTR_VALUE_text, ATTR_VALUE_file, ATTR_VALUE_circ, ATTR_VALUE_poly, ATTR_VALUE_left, ATTR_VALUE_hide, ATTR_VALUE_show, ATTR_VALUE_void, ATTR_VALUE_none, ATTR_VALUE_rows, ATTR_VALUE_cols, ATTR_VALUE_down, ATTR_VALUE_both, ATTR_VALUE_date, ATTR_VALUE_week, ATTR_VALUE_time, ATTR_VALUE_color, ATTR_VALUE_reset, ATTR_VALUE_image, ATTR_VALUE_right, ATTR_VALUE_false, ATTR_VALUE_radio, ATTR_VALUE_above, ATTR_VALUE_below, ATTR_VALUE_slide, ATTR_VALUE_email, ATTR_VALUE_range, ATTR_VALUE_month, ATTR_VALUE_button, ATTR_VALUE_bottom, ATTR_VALUE_circle, ATTR_VALUE_pixels, ATTR_VALUE_search, ATTR_VALUE_square, ATTR_VALUE_submit, ATTR_VALUE_middle, ATTR_VALUE_center, ATTR_VALUE_hidden, ATTR_VALUE_silent, ATTR_VALUE_hsides, ATTR_VALUE_vsides, ATTR_VALUE_border, ATTR_VALUE_groups, ATTR_VALUE_scroll, ATTR_VALUE_number, ATTR_VALUE_default, ATTR_VALUE_justify, ATTR_VALUE_polygon, ATTR_VALUE_inherit, ATTR_VALUE_fileopen, ATTR_VALUE_baseline, ATTR_VALUE_relative, ATTR_VALUE_checkbox, ATTR_VALUE_password, ATTR_VALUE_infinite, ATTR_VALUE_datetime, ATTR_VALUE_absbottom, ATTR_VALUE_absmiddle, ATTR_VALUE_mouseover, ATTR_VALUE_alternate, ATTR_VALUE_datetime_local }; BYTE ATTR_GetKeyword(const uni_char* str, int len) { if (len <= AttrvalueNameMaxSize) { short end_idx = ATTR_value_idx[len+1]; for (short i=ATTR_value_idx[len]; i<end_idx; i++) if (uni_strni_eq(str, ATTR_value_name[i], len) != 0) return ATTR_value_tok[i]; } return 0; } int SetLoop(const uni_char* str, UINT len) { int lloop; if (str && len) { BYTE loop_val = ATTR_GetKeyword(str, len); if (loop_val == ATTR_VALUE_infinite) lloop = LoopInfinite; else lloop = uni_atoi(str); } else lloop = LoopInfinite; if (lloop > LoopInfinite) lloop = LoopInfinite; return lloop; } short GetFirstFontNumber(const uni_char* face_list, int face_list_len, WritingSystem::Script script) { uni_char* face_start = const_cast<uni_char*>(face_list); // casting to be able to do the temp termination const uni_char* end = face_list + face_list_len; uni_char* next_face; while (face_start < end) { while (face_start < end && HTML5Parser::IsHTML5WhiteSpace(*face_start) || *face_start == ',') face_start++; next_face = face_start; while (next_face < end && *next_face != ',') next_face++; int len = next_face - face_start; while (len && HTML5Parser::IsHTML5WhiteSpace(face_start[len - 1])) len--; if (len) { uni_char save_c = face_start[len]; face_start[len] = '\0'; // temporarily terminate the string int font_num; StyleManager::GenericFont generic_font = styleManager->GetGenericFont(face_start); if (generic_font != StyleManager::UNKNOWN) font_num = styleManager->GetGenericFontNumber(generic_font, script); else font_num = styleManager->GetFontNumber(face_start); face_start[len] = save_c; // remove temporary termination if (font_num >= 0 && styleManager->HasFont(font_num)) return font_num; } face_start = next_face; } return -1; // font_num; } BOOL WhiteSpaceOnly(const uni_char* txt, int len) { for (; len--; txt++) { if (*txt != ' ' && !uni_iscntrl(*txt)) return FALSE; } return TRUE; } BOOL WhiteSpaceOnly(const uni_char* txt) { for (; *txt; txt++) { if (*txt != ' ' && !uni_iscntrl(*txt)) return FALSE; } return TRUE; } void ReplaceWhitespace(const uni_char* src_txt, int src_txt_len, uni_char* target_txt, int target_txt_len, BOOL preserve_whitespace_type) { // don't put anything in the string if we don't have anything if (src_txt_len) { BOOL skip_ws = FALSE; for (int in = 0; in < src_txt_len; ++in) { uni_char c = src_txt[in]; if (uni_isspace(c)) { if (!skip_ws) { *(target_txt++) = preserve_whitespace_type ? c : ' '; skip_ws = TRUE; } } else { *(target_txt++) = c; skip_ws = FALSE; } } } // We always assume there's an extra byte at the end of the string *target_txt = 0; } #include "modules/logdoc/data/entities.inl" /** * Look up an HTML character entity reference by name. * * @param esc_seq The character entity (without leading ampersand) to look up. * @param len Length of character entity string, in uni_chars. * @return the referenced character. */ inline uni_char GetEscapeChar(const uni_char* esc_seq, int len) { if (len <= AMP_ESC_MAX_SIZE) { const char * const *end = AMP_ESC + AMP_ESC_idx[len + 1]; for (const char * const *p = AMP_ESC + AMP_ESC_idx[len]; p < end; ++ p) { int n = 0; while (n < len && (*p)[n] == esc_seq[n]) n++; if (n == len) return AMP_ESC_char[p - AMP_ESC]; } } return 0; } void RemoveTabs(uni_char* txt) { uni_char* dst = txt; while (*txt) { if (*txt != '\t') { if (dst != txt) { *dst = *txt; } dst++; } txt++; } *dst = '\0'; } OP_BOOLEAN ReplaceAttributeEntities(HtmlAttrEntry* hae) { BOOL has_ampersand = FALSE; for (unsigned i = 0; i < hae->value_len; i++) { if (hae->value[i] == '&') { has_ampersand = TRUE; break; } } if (has_ampersand) { uni_char* output = UniSetNewStrN(hae->value, hae->value_len); if (!output) return OpStatus::ERR_NO_MEMORY; hae->value_len = ReplaceEscapes(output, hae->value_len, FALSE, FALSE, FALSE); hae->value = output; return OpBoolean::IS_TRUE; // We replaced hae->value with a new string } return OpBoolean::IS_FALSE; } int ReplaceEscapes(uni_char* txt, int txt_len, BOOL require_termination, BOOL remove_tabs, BOOL treat_nbsp_as_space) { if (!txt || txt_len <= 0) return 0; const unsigned short *win1252 = g_opera->logdoc_module.GetWin1252Table(); int scan_idx = 0; uni_char* replace = txt; while (scan_idx < txt_len) { uni_char* scan = txt + scan_idx; if (*scan == '&') { unsigned int char_no = 32; // the referenced character number uni_char* esc_end = scan; if (*(scan + 1) == '#') { // Look for numeric reference if ((*(scan + 2) == 'x' || *(scan + 2) == 'X') && uni_isxdigit(scan[3])) { // Hexadecimal esc_end = scan + 3; while (uni_isxdigit(*esc_end)) esc_end++; uni_char* dummy; char_no = uni_strtol(scan + 3, &dummy, 16); } else if (Unicode::IsDigit(scan[2])) { // Decimal esc_end = scan + 2; while (uni_isdigit(*esc_end)) esc_end++; char_no = uni_atoi(scan + 2); } else // no number after the &# stuff should not be converted { *replace++ = *scan++; *replace++ = *scan; // skip both characters scan_idx += 2; // update the index when scan is updated continue; } if (char_no == 0 || char_no > 0x10FFFF) { // Nul character or non-Unicode character is replaced // with U+FFFD. char_no = 0xFFFD; } if (*esc_end == ';') esc_end++; } else { // Look for character entity esc_end = scan + 1; // Supported entities are made up of alphanumerical // characters which are all ASCII. while (uni_isalnum(*esc_end) && *esc_end < 128) esc_end++; char_no = GetEscapeChar(scan + 1, esc_end - scan - 1); if (*esc_end == ';') esc_end++; else if (char_no == '<' || char_no == '>' || char_no == '&' || char_no == '"') { // We always accept these because MSIE does, regardless of require_termination // setting } else if (require_termination || char_no > 255) { // We're less tolerant against errors with non latin-1 chars regardless // of the require_termination setting. This makes us compatible with MSIE. char_no = 0; // We required this to be terminated and it is not. } } if (char_no) scan_idx += (esc_end - scan); if(char_no == 9 && remove_tabs) char_no = 0; // skip tabs if remove_tabs is true (for URLs) else if (char_no == NBSP_CHAR && treat_nbsp_as_space) char_no = ' '; // encode and insert character if (char_no >= 128 && char_no < 160) { // Treat numerical entities in the [128,160) range as // Windows-1252. Although not according to the standard, // this is what is used today. *replace++ = win1252 ? win1252[char_no - 0x80] : NOT_A_CHARACTER; } else if (char_no > 0 && char_no < 0x10000) { *replace++ = char_no; } else if (char_no >= 0x10000) { // a character outside the BMP was referenced, so we must // encode it using surrogates (grrrmph!) the procedure is // described in RFC 2781. char_no -= 0x10000; *replace++ = 0xD800 | (char_no >> 10); *replace++ = 0xDC00 | (char_no & 0x03FF); } else { *replace++ = *scan; scan_idx++; } } // if(*scan == '&') else { *replace++ = *scan; scan_idx++; } } // while(*scan) *replace = 0; return replace - txt; } int ReplaceEscapes(uni_char* txt, BOOL require_termination, BOOL remove_tabs/*=FALSE*/, BOOL treat_nbsp_as_space/*=FALSE*/) { return ReplaceEscapes(txt, txt ? uni_strlen(txt) : 0, require_termination, remove_tabs, treat_nbsp_as_space); } void EncodeFormsData(const char *charset, uni_char *url, size_t startidx_arg, unsigned int &len, unsigned int maxlen) { // May be clobbered by longjmp (TRAP on Unix) OP_MEMORY_VAR size_t startidx = startidx_arg; // Check number of characters we need to encode; we start at the first // character of the forms data section, and end when we hit a fragment // identifier (bug#227310) uni_char * OP_MEMORY_VAR form_start = url + startidx; uni_char * OP_MEMORY_VAR fragment = uni_strchr(form_start, '#'); if (fragment == form_start) return; if (!fragment) fragment = form_start + uni_strlen(form_start); // Create a reverse converter for this character set OutputConverter *converter; if (OpStatus::IsError(OutputConverter::CreateCharConverter(charset, &converter, TRUE))) return; // Convert forms data section OpString8 encoded; TRAPD(err, SetToEncodingL(&encoded, converter, form_start, (fragment ? fragment - form_start : int(KAll)))); OP_DELETE(converter); if(err) //if a error happens we set the len to 0 and return. { len = 0; return; } else { unsigned char *buffer = reinterpret_cast<unsigned char *>(encoded.DataPtr()); unsigned char *end = buffer + encoded.Length(); size_t fragment_length = fragment ? uni_strlen(fragment) : 0; if (fragment_length) { // We need to calculate how much the forms data section grew, so // that we can move the fragment identifier into place uni_char *new_fragment = fragment; // First it grew because of the encoding into some 8-bit charset (commonly utf-8) int start_len = fragment - form_start; int current_len = end - buffer; int growth = current_len - start_len; new_fragment += growth; // Then it grows because we url encode some chars for (unsigned char *p = buffer; p < end; p ++) { if (*p & 0x80) { // Each character needing escape shifts the fragment by // two characters new_fragment += 2; } } // Copy the fragment up in memory if (new_fragment != fragment) { unsigned int position = new_fragment - url; if (position < maxlen) { fragment_length = MIN(fragment_length, maxlen - position); op_memmove(new_fragment, fragment, UNICODE_SIZE(fragment_length)); } else fragment_length = 0; } } // Forget about old formsdata part len = startidx; // Copy our converted data back to the URL, escaping as needed len += UriEscape::Escape(form_start, (int)(maxlen-len), (char*)buffer, end-buffer, UriEscape::Range_80_ff); // Add the length of the fragment identifier, if any len += fragment_length; } } static BOOL IsSupposedToBeScheme(uni_char* scheme, int len = -1 /* -1 means - figure it out by yourself */) { OP_ASSERT(scheme); if (len == -1) { uni_char *colon = uni_strchr(scheme, ':'); if (!colon) return FALSE; len = (colon - scheme); } OP_ASSERT(scheme[len] == ':'); uni_char sch[12]; /* ARRAY OK 2010-12-15 adame */ int sch_idx = 0; for (int cnt = 0; cnt <= len && sch_idx < 11; ++cnt) { if (scheme[cnt] != '\t' && scheme[cnt] != '\n' && scheme[cnt] != '\r') { sch[sch_idx++] = scheme[cnt]; } } sch[sch_idx] = 0; return (uni_stri_eq(sch, "JAVASCRIPT:") || uni_stri_eq(sch, "FILE:") || uni_stri_eq(sch, "MAILTO:") || uni_stri_eq(sch, "DATA:")); } static uni_char* CleanUrlName(uni_char *url_name, unsigned int &len, unsigned int maxlen, HLDocProfile *hld_profile) { const uni_char *colon = uni_strchr(url_name, ':'); const char *charset = hld_profile ? hld_profile->GetCharacterSet() : "UTF-8"; // remove \r and \n and \t... const uni_char *src, *end; uni_char *copy; src = copy = url_name; // ...but not from the scheme part BOOL scheme_detected = FALSE; if (colon) { scheme_detected = IsSupposedToBeScheme(url_name, colon - url_name); if (scheme_detected) { src = copy = url_name + (colon - url_name + 1); len -= (colon - url_name + 1); } } end = src + len; while (src < end) { if (*src != '\r' && *src != '\n' && *src != '\t') *(copy ++) = *src; ++ src; } len = copy - url_name; *copy = '\0'; // Bug#123416: If the page is ISO 2022-JP, there is a chance that we // have links encoded in a JIS-Roman block, which would mean that // tilde and backslash would be replaced with overline and the yen // symbol. If we find these symbols in the URL, we change them back. if (charset && 0 == op_strcmp(charset, "iso-2022-jp")) { StrReplaceChars(url_name, 0x203E, 0x007E); // Overline -> Tilde StrReplaceChars(url_name, 0x00A5, 0x005C); // Yen -> Backslash } // Recode international characters in URLs. We only do this for // network URLs (URLs with a protocol that is followed by a server // name). // // Compare bug#51646 and bug#189961. const uni_char *colonslashslash = NULL; uni_char *forms_data = uni_strchr(url_name, '?'); if (colon) { if (forms_data && colon > forms_data) { colon = NULL; } else { colonslashslash = uni_strstr(colon, UNI_L("://")); } if (!colonslashslash && colon) { // Check if relative url const uni_char *temp_str = url_name; while (*temp_str && *temp_str != ':' && !scheme_detected) { if (!uni_isalnum(*temp_str) && *temp_str != '+' && *temp_str != '-' && *temp_str != '.') { colon = NULL; break; } temp_str++; } } } if ((!colon || (colon && colon == colonslashslash)) #ifdef LU_KDDI_DEVICE_PROTOCOL || 0 == uni_strncmp(url_name, UNI_L("device:"), 7) #endif // LU_KDDI_DEVICE_PROTOCOL ) { // This is a network path, or a path relative to the current // document. // // If the URL contains a question mark, treat everything after it as // GET form data, and %-encode it using the document's character // set. // // If not using UTF-8 encoded URLs, we encode the entire server-part // of the URL in the document encoding. // Fetch the URL of the parent document. We need that for // site-specific configuration of UTF-8 encoding of URLs to work. BOOL use_utf8 = g_pcnet->GetIntegerPref(PrefsCollectionNetwork::UseUTF8Urls, hld_profile ? hld_profile->GetURL()->GetServerName() : NULL); #ifdef _LOCALHOST_SUPPORT_ if (!use_utf8) { OP_ASSERT(hld_profile); // or use_utf8 could never have // been set to FALSE // Bug#197260: Local file URLs should always be UTF-8 encoded, no // matter what the preference setting is. URL *base_url = hld_profile->BaseURL(); /* <base> URL for relative URL */ OP_ASSERT(base_url); URLType parent_type = base_url ? base_url->Type() : URL_NULL_TYPE; if ((parent_type == URL_FILE && !colon /* relative file URL */) || (uni_strni_eq_upper(url_name, "FILE:", 5) /* absolute file URL */)) { use_utf8 = TRUE; } } #endif // _LOCALHOST_SUPPORT_ if (use_utf8) { // Locate the forms data part of the URL (if any). if (forms_data) { ++ forms_data; // Skip question mark } } else { if (colonslashslash) { // Locate the server-part of the URL. forms_data = (uni_char*)uni_strchr(colonslashslash + 3, '/'); if (forms_data) { ++ forms_data; // Skip slash } } else { // There is no server-part since this is a relative URL. // Encode the lot. forms_data = url_name; } } // URL encode if we found something to URL encode if (forms_data && *forms_data) { size_t idx = forms_data - url_name; url_name[len] = '\0'; // URL encode if(idx < len) { EncodeFormsData(charset, url_name, idx, len, maxlen); } } } OP_ASSERT(len <= maxlen); if (len == maxlen) { // Truncate to make room for a null char // FIXME: Let the function work with a dynamic buffer instead of a static one. len--; } url_name[len] = '\0'; return url_name; } void CleanStringForDisplay(uni_char* string) { // Initially true to remove leading whitespace BOOL in_whitespace = TRUE; int j = 0; for (int i = 0; string[i]; i++) { BOOL next_is_whitespace = IsHTML5Space(string[i]); if (in_whitespace && next_is_whitespace) continue; in_whitespace = next_is_whitespace; if (in_whitespace) string[j++] = ' '; // Replace all whitespace with SPACE else string[j++] = string[i]; } if (j > 0 && in_whitespace) // strip trailing whitespace j--; string[j] = '\0'; } void CleanCDATA(uni_char* url_name, unsigned int &len) { uni_char *tmp = url_name; // remove leading white spaces while (len > 0 && (uni_isspace(*tmp) || *tmp == '\r' || *tmp == '\t' || *tmp == '\n')) { tmp++; len--; } // remove trailing white spaces while (len > 0 && (uni_isspace(*(tmp+len-1)) || *(tmp+len-1) == '\r' || *(tmp+len-1) == '\t' || *(tmp+len-1) == '\n')) len--; int j = 0; for (unsigned int i=0; i<len; i++) { if (tmp[i] != '\n') // ignore \n { if (tmp[i] == '\r' || tmp[i] == '\t') // replace \n and \t with space url_name[j++] = ' '; else url_name[j++] = tmp[i]; } } len = j; url_name[j] = '\0'; } int HexToInt(const uni_char* str, int len, BOOL strict) { int val = 0; for (int i = 0; i < len; i++) { val *= 16; if (str[i] >= '0' && str[i] <= '9') val += static_cast<int>(str[i] - '0'); else if (str[i] >= 'A' && str[i] <= 'F') val += static_cast<int>(str[i] - 'A' + 10); else if (str[i] >= 'a' && str[i] <= 'f') val += static_cast<int>(str[i] - 'a' + 10); else if (strict) return -1; } return val; } long GetColorVal(const uni_char* coltxt, int collen, BOOL check_color_name) { /* * Color parsing according to HTML5 on rules for parsing legacy color value. */ while (collen && IsHTML5Space(*coltxt)) { ++coltxt; --collen; } while (collen && IsHTML5Space(coltxt[collen-1])) --collen; if (collen == 0 || (collen == 1 && *coltxt == '#')) return USE_DEFAULT_COLOR; if (check_color_name && uni_isalpha(*coltxt)) { // Reject the keyword 'transparent'. if (collen == 11 && uni_strni_eq(coltxt, "transparent", 11)) return USE_DEFAULT_COLOR; // try predefined colors COLORREF coltmp = HTM_Lex::GetColIdxByName(coltxt, collen); if (coltmp != USE_DEFAULT_COLOR) // Added this to get rgbcolors without '#' (and not a colorname) work... return HTM_Lex::GetColValByIndex(coltmp); } uni_char rgb[129]; // ARRAY OK 2011-06-15 tommyn if (collen == 4 && *coltxt == '#' && HexToInt(coltxt + 1, 1, TRUE) >= 0 && HexToInt(coltxt + 2, 1, TRUE) >= 0 && HexToInt(coltxt + 3, 1, TRUE) >= 0) { rgb[5] = coltxt[3]; rgb[4] = coltxt[3]; rgb[3] = coltxt[2]; rgb[2] = coltxt[2]; rgb[1] = coltxt[1]; rgb[0] = coltxt[1]; } else { if (collen > 128) collen = 128; if (*coltxt == '#') { --collen; ++coltxt; } op_memcpy(rgb, coltxt, UNICODE_SIZE(collen)); for (int i = 0; i < collen; ++i) if (HexToInt(rgb + i, 1, TRUE) < 0) rgb[i] = '0'; for (; collen % 3 != 0; ++collen) rgb[collen] = '0'; if (collen > 6) { unsigned int component = collen / 3; uni_char *r = rgb; uni_char *g = r + component; uni_char *b = g + component; if (component > 8) { const unsigned int offset = component - 8; r += offset; g += offset; b += offset; component = 8; } while (component > 2 && *r == '0' && *g == '0' && *b == '0') { --component; ++r; ++g; ++b; } rgb[0] = r[0]; rgb[1] = r[1]; rgb[2] = g[0]; rgb[3] = g[1]; rgb[4] = b[0]; rgb[5] = b[1]; } else if (collen == 3) { rgb[5] = rgb[2]; rgb[4] = '0'; rgb[3] = rgb[1]; rgb[2] = '0'; rgb[1] = rgb[0]; rgb[0] = '0'; } } return OP_RGB(static_cast<BYTE>(HexToInt(rgb , 2, FALSE)), static_cast<BYTE>(HexToInt(rgb + 2, 2, FALSE)), static_cast<BYTE>(HexToInt(rgb + 4, 2, FALSE))); } /** * Convert backslash to slash in URLs, like IE and NS. * (stighal) * * @param url_name Pointer to a URL string. * @param len Length of url_name. */ inline void Backslash2Slash(uni_char *url_name, UINT len) { for(UINT i = 0; i < len; i++) { if( url_name[i] == '\\' ) url_name[i] = '/'; else if( url_name[i] == '?' ) break; } } static URL* CreateUrlInternal(const uni_char* value, UINT value_len, URL* base_url, HLDocProfile *hld_profile, BOOL check_for_internal_img, BOOL accept_empty #ifdef WEB_TURBO_MODE , BOOL set_context_id/*=FALSE*/ #endif // WEB_TURBO_MODE ) { OP_PROBE4(OP_PROBE_LOGDOC_CREATEURLFROMSTRING); // remove leading whitespace while (value_len && uni_isspace(value[0])) { value++; value_len--; } if (value_len == 0 && !accept_empty) // lets not bother to do anything if we have no string { URL *ret_url = OP_NEW(URL, ()); return ret_url; } unsigned int len = value_len; AutoTempBuffer uni_tmp_buf; if (OpStatus::IsMemoryError(uni_tmp_buf.GetBuf()->Append(value, value_len))) return NULL; uni_char *uni_tmp = uni_tmp_buf.GetBuf()->GetStorage(); size_t max_len = uni_tmp_buf.GetBuf()->GetCapacity(); // Fix forms data and stuff. Also remove any HTML escapes, unless we // are in a X[HT]ML document, in which case they will be unescaped // already. uni_tmp = CleanUrlName(uni_tmp, len, max_len, hld_profile); BOOL is_file_url = uni_strni_eq(uni_tmp, "FILE:", 5); BOOL is_data_url = #ifdef SUPPORT_DATA_URL uni_strni_eq(uni_tmp, "DATA:", 5); #else FALSE; #endif BOOL is_mailto_url = uni_strni_eq(uni_tmp, "MAILTO:", 7); BOOL is_javascript_url = uni_strni_eq(uni_tmp, "JAVASCRIPT:", 11); // don't escape a javascript url !!! BOOL invalid_scheme = FALSE; if ((!is_file_url && !is_data_url && !is_mailto_url && !is_javascript_url) && IsSupposedToBeScheme(uni_tmp)) { #ifdef LOGDOC_IGNORE_SCHEMES_WITH_TABS_OR_NEW_LINES URL *ret_url = OP_NEW(URL, ()); return ret_url; #else // LOGDOC_IGNORE_SCHEMAS_WITH_TABS_OR_NEW_LINES invalid_scheme = TRUE; #endif // LOGDOC_IGNORE_SCHEMAS_WITH_TABS_OR_NEW_LINES } // Bug#191273: Convert backslash in URLs to a forward slash, but only // in quirks mode. if (hld_profile && !hld_profile->IsInStrictMode() && !is_file_url && !is_data_url && !is_javascript_url) Backslash2Slash(uni_tmp, len); uni_char *rel_start = 0; uni_char *url_start = uni_tmp; if (!is_javascript_url && !is_data_url && !is_mailto_url) { rel_start = uni_strchr(uni_tmp, '#'); if(rel_start) { *(rel_start++) = '\0'; } } URL* url = NULL; #ifdef PICTOGRAM_SUPPORT //URL copy_url; if (check_for_internal_img) { if (uni_str_eq(url_start, "pict:")) { OpString file_url; OP_STATUS rc = PictUrlConverter::GetLocalUrl(url_start, uni_strlen(url_start), file_url); if (OpStatus::IsError(rc)) return NULL; if (!file_url.IsEmpty()) { url = OP_NEW(URL, ()); if (url) *url = g_url_api->GetURL(file_url.CStr()); return url; } } } #endif // PICTOGRAM_SUPPORT URL_CONTEXT_ID context_id = 0; #ifdef WEB_TURBO_MODE context_id = (set_context_id && hld_profile) ? hld_profile->GetLogicalDocument()->GetCurrentContextId() : 0; #endif // WEB_TURBO_MODE if (invalid_scheme) { URL temp_url = urlManager->GenerateInvalidHostPageUrl(uni_tmp, context_id #ifdef ERROR_PAGE_SUPPORT , OpIllegalHostPage::KIllegalCharacter #endif // ERROR_PAGE_SUPPORT ); url = OP_NEW(URL, (temp_url)); return url; } URL *doc_url = hld_profile ? hld_profile->GetURL() : NULL; if (base_url && doc_url) { OP_PROBE4(OP_PROBE_LOGDOC_CREATEURLFROMSTRING2); URL use_base = *base_url; #ifdef WEB_TURBO_MODE if (set_context_id && use_base.GetContextId() != context_id) { const OpStringC8 base_str = base_url->GetAttribute(URL::KName_With_Fragment_Username_Password_NOT_FOR_UI, URL::KNoRedirect); use_base = g_url_api->GetURL(base_str.CStr(), context_id); } #endif // WEB_TURBO_MODE if (!is_javascript_url && !is_mailto_url) { if (!url_start || !*url_start) { if (!rel_start) url = OP_NEW(URL, (use_base)); else url = OP_NEW(URL, (use_base, rel_start)); } else if (doc_url->GetAttribute(URL::KUniName_Username_Password_NOT_FOR_UI).Compare(url_start) == 0 && (!doc_url->GetAttribute(URL::KUnique) || rel_start)) { #ifdef WEB_TURBO_MODE if (set_context_id && doc_url->GetContextId() != context_id) { const OpStringC8 base_str = doc_url->GetAttribute(URL::KName_With_Fragment_Username_Password_NOT_FOR_UI, URL::KNoRedirect); use_base = g_url_api->GetURL(base_str.CStr(), context_id); } else #endif // WEB_TURBO_MODE use_base = *doc_url; url = OP_NEW(URL, (use_base, rel_start)); } else { URL tmp_url = g_url_api->GetURL(use_base, url_start, rel_start); url = OP_NEW(URL, (tmp_url)); } } else { URL tmp_url = g_url_api->GetURL(use_base, url_start, rel_start, is_javascript_url); url = OP_NEW(URL, (tmp_url)); } } else if (base_url) { URL use_base = *base_url; #ifdef WEB_TURBO_MODE if (set_context_id && use_base.GetContextId() != context_id) { const OpStringC8 base_str = base_url->GetAttribute(URL::KName_With_Fragment_Username_Password_NOT_FOR_UI, URL::KNoRedirect); use_base = g_url_api->GetURL(base_str.CStr(), context_id); } #endif // WEB_TURBO_MODE URL tmp_url = g_url_api->GetURL(use_base, url_start, rel_start, is_javascript_url); url = OP_NEW(URL, (tmp_url)); } else { #ifdef WEB_TURBO_MODE URL tmp_url = g_url_api->GetURL(url_start, rel_start, is_javascript_url, context_id); #else // WEB_TURBO_MODE URL tmp_url = g_url_api->GetURL(url_start, rel_start, is_javascript_url); #endif // WEB_TURBO_MODE url = OP_NEW(URL, (tmp_url)); } return url; } URL* SetUrlAttr(const uni_char* value, UINT value_len, URL* base_url, HLDocProfile *hld_profile, BOOL check_for_internal_img, BOOL accept_empty) { return CreateUrlInternal(value, value_len, base_url, hld_profile, check_for_internal_img, accept_empty #ifdef WEB_TURBO_MODE , FALSE #endif // WEB_TURBO_MODE ); } URL* CreateUrlFromString(const uni_char* value, UINT value_len, URL* base_url, HLDocProfile *hld_profile, BOOL check_for_internal_img, BOOL accept_empty #ifdef WEB_TURBO_MODE ,BOOL set_context_id/*=FALSE*/ #endif // WEB_TURBO_MODE ) { return CreateUrlInternal(value, value_len, base_url, hld_profile, check_for_internal_img, accept_empty #ifdef WEB_TURBO_MODE , set_context_id #endif // WEB_TURBO_MODE ); } BOOL SetTabIndexAttr(const uni_char *value, int value_len, HTML_Element *elm, long& return_value) { if (value_len && value_len < 20) { uni_char number[20]; /* ARRAY OK 2009-02-05 stighal */ op_memcpy(number, value, sizeof(uni_char) * value_len); number[value_len] = '\0'; uni_char* end_ptr; long num_val = uni_strtol(number, &end_ptr, 10); if (end_ptr == number + value_len) { // Correct number if (num_val > INT_MAX) num_val = INT_MAX; return_value = num_val; return TRUE; } } return FALSE; } uni_char* SetStringAttr(const uni_char* value, int value_len, BOOL replace_ws) { uni_char* str = UniSetNewStrN(value, value_len); // FIXME:REPORT_MEMMAN-KILSMO // OOM check if (str) { if (replace_ws) { // remove leading whitespace while (value_len && uni_isspace(value[0])) { value++; value_len--; } // remove trailing whitespace while (value_len && uni_isspace(value[value_len - 1])) value_len--; ReplaceWhitespace(value, value_len, str, value_len); } } return str; } /** * @deprecated Only has three arguments now */ uni_char* SetStringAttr(const uni_char* value, int value_len, BOOL replace_ws, BOOL unused1, BOOL unused2) { return SetStringAttr(value, value_len, replace_ws); } uni_char* SetStringAttrUTF8Escaped(const uni_char *value, int value_len, HLDocProfile *hld_profile) { uni_char *uni_tmp = reinterpret_cast<uni_char *>(g_memory_manager->GetTempBuf()); unsigned int uni_tmp_len = UNICODE_DOWNSIZE(g_memory_manager->GetTempBufLen()) - 1; // Crop URL length to the size of the buffer unsigned int len = (uni_tmp_len <= static_cast<unsigned int>(value_len)) ? uni_tmp_len : static_cast<unsigned int>(value_len); if (len) uni_strncpy(uni_tmp, value, len); uni_tmp[len] = '\0'; uni_tmp = CleanUrlName(uni_tmp, len, uni_tmp_len, hld_profile); return SetStringAttr(uni_tmp, len, FALSE); } const uni_char* GetCurrentBaseTarget(HTML_Element* from_he) { HTML_Element* he = from_he; while (he) { const uni_char* btarget = he->GetBase_Target(); if (btarget) return btarget; he = he->Prev(); } return NULL; } BOOL IsHtmlInlineElm(HTML_ElementType type, HLDocProfile *hld_profile) { OP_ASSERT(hld_profile); switch (type) { case HE_TEXT: case HE_TEXTGROUP: case HE_COMMENT: case HE_PROCINST: case HE_DOCTYPE: case HE_ENTITY: case HE_ENTITYREF: case HE_UNKNOWN: case HE_A: case HE_IMG: case HE_BR: case HE_I: case HE_B: case HE_TT: case HE_FONT: case HE_SMALL: case HE_BIG: case HE_STRIKE: case HE_S: case HE_U: case HE_EMBED: #ifdef MEDIA_HTML_SUPPORT case HE_VIDEO: #endif // MEDIA_HTML_SUPPORT #ifdef CANVAS_SUPPORT case HE_CANVAS: #endif case HE_METER: case HE_PROGRESS: case HE_SUB: case HE_SUP: case HE_CITE: case HE_EM: case HE_STRONG: case HE_KBD: case HE_DFN: case HE_VAR: case HE_CODE: case HE_SAMP: case HE_NOBR: case HE_WBR: case HE_INPUT: case HE_SELECT: case HE_OPTION: case HE_TEXTAREA: case HE_LABEL: #if defined(_SSL_SUPPORT_) && !defined(_EXTERNAL_SSL_SUPPORT_) case HE_KEYGEN: #endif //case HE_TABLE: case HE_NOEMBED: case HE_MAP: case HE_AREA: case HE_SPAN: case HE_MARK: case HE_SCRIPT: case HE_OPTGROUP: case HE_INS: // <ins> and <del> are special cases who are sometimes blocks and sometimes inlines. See bug 216970 case HE_DEL: return TRUE; case HE_NOSCRIPT: return hld_profile->GetESEnabled(); default: return FALSE; } } AutoTempBuffer::AutoTempBuffer() { m_buf = g_opera->logdoc_module.GetTempBuffer(); } AutoTempBuffer::~AutoTempBuffer() { g_opera->logdoc_module.ReleaseTempBuffer(m_buf); } unsigned short int GetSuggestedCharsetId(HTML_Element *html_element, HLDocProfile *hld_profile, LoadInlineElm *elm) { unsigned short int parent_charset_id = 0; uni_char *charset_attr = reinterpret_cast<uni_char *>(html_element->GetAttr(ATTR_CHARSET, ITEM_TYPE_STRING, NULL)); if (charset_attr && *charset_attr) { OpString8 charset_utf8; if (OpStatus::IsError(charset_utf8.SetUTF8FromUTF16(charset_attr))) return 0; if (OpStatus::IsError(g_charsetManager->GetCharsetID(charset_utf8.CStr(), &parent_charset_id))) return 0; } else { if (OpStatus::IsError(g_charsetManager->GetCharsetID(hld_profile->GetCharacterSet(), &parent_charset_id))) return 0; } if (parent_charset_id) { g_charsetManager->IncrementCharsetIDReference(parent_charset_id); const char *parent_charset_string = g_charsetManager->GetCanonicalCharsetFromID(parent_charset_id); // Perform security check BOOL allowed = FALSE; OP_STATUS rc = OpStatus::OK; if (parent_charset_string) { OpSecurityContext source(*hld_profile->GetURL(), hld_profile->GetCharacterSet() ? hld_profile->GetCharacterSet() : ""), target(*elm->GetUrl(), parent_charset_string, TRUE); rc = OpSecurityManager::CheckSecurity( OpSecurityManager::DOC_SET_PREFERRED_CHARSET, source, target, allowed); } g_charsetManager->DecrementCharsetIDReference(parent_charset_id); if (OpStatus::IsError(rc) || !allowed) return 0; // FIXME: Log to console when blocking attribute? } return parent_charset_id; }
#include<iostream> #include<iomanip> #include <windows.h> #include <SFML/Graphics.hpp> #include<time.h> #include "Globals.h" #include"region.h" const int size = 2500;//rowSize ^2 const int rowSize = 50; const int maxDistance = 4; //declared as globals. Variables are declared to the heap rather than the stack, prevents memory overflow issues. // matrices are row x col //The distribution matrix is symetrical about the diagonal //however, in general it will be used as dM[from][to] static float distributionMatrix[size][size]; static int strainMatrix[numStrains][size]; float transmissionMatrix[numStrains][size]; static float strainVector[size]; static float transmissionVector[size]; //helper functions to keep the main function neater. void updateTransmissionMatrix(region **regions); void updateTransmissionVector(region **regions); void printDistributionMatrix(); void printStrainMatrix(); void printTransmissionMatrix(); void printDebug(); int main() { std::cout << std::fixed; std::cout << std::setprecision(2); srand(time(NULL)); std::cout << "start\n"; region* regionLattice[size]; // sum(r2.infected * Dist(r1,r2) ) //initialise the region connectivity network, it's stored as just a vector for ease of calculation; for (int i = 0; i < rowSize; i++ ) { for (int j = 0; j < rowSize; j++) { //std::cout << i << " " << j << "\n"; regionLattice[i*rowSize+j] = new region(500, 1, i, j); // 500 people, 1 person per unit space, (i,j) } } //initialise the distribution matrix. //naive initialisation atm, will fix later int m, n; for (int i = 0; i < size; i++) { //zero the entire row. for (int j = 0; j < size; j++) { distributionMatrix[i][j] = 0.0f; } m = i / rowSize; // rounded down because int. n = i - m*rowSize; //fix this 'cause it doesn't actually work :Y for (int j = -maxDistance; j <= maxDistance; j++) { for (int k = -maxDistance; k <= maxDistance; k++) { int temp_m = m + j; int temp_n = n + k; int index = rowSize*temp_m + temp_n; //fuck you c++ if (j == 0 && k == 0) continue; //skip dist, it's just the current index if (index >= 0 && index < size && temp_n >=0 && temp_n <rowSize && temp_m >= 0 && temp_m <rowSize ) { distributionMatrix[i][index] = 0.5 / sqrt(j*j + k*k); } //std::cout << m << " " << n << " : " << temp_m << " " << temp_n << " " << index << "\n"; } } //set the diagonal to 1. distributionMatrix[i][i] = 1; } regionLattice[40]->infectNIndividuals(1); std::cout << "Initialisation completed\n"; int screensize = 600; float scale = screensize / rowSize; sf::RenderWindow window(sf::VideoMode(screensize,screensize), "TB model"); int step = 0; while (window.isOpen()){ sf::Event event; //check for close. while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::P)) { printDebug(); } } window.clear(); updateTransmissionMatrix(regionLattice); //major bottleneck in this sim. for (int i = 0; i < numStrains; i++ ) { for (int j = 0; j < size; j++) { regionLattice[j]->update(i , transmissionMatrix[i][j]); } } int totalInfected = 0; //draw the lattice for (int i = 0; i < rowSize; i++) { for (int j = 0; j < rowSize; j++) { sf::RectangleShape rectangle(sf::Vector2f(scale , scale)); rectangle.setPosition(j * scale, i*scale); float red = 255 * ((float)regionLattice[i*rowSize + j]->getStrainInfected(0) / 10) ; float blue = 255 * ((float)regionLattice[i*rowSize + j]->getStrainInfected(1) / 10); float green = 255 * ((float)regionLattice[i*rowSize + j]->getStrainInfected(2) / 10); rectangle.setFillColor(sf::Color(red, 0 ,blue)); window.draw(rectangle); totalInfected += regionLattice[i*rowSize + j]->getTotalInfected(); } } window.display(); std::cout << step << " " << totalInfected << std::endl; step++; } return 0; } //make the program work with just the vector again??? wtf happened void updateTransmissionVector(region **regions) { for (int region = 0; region < size; region++) { strainVector[region] = regions[region]->getTotalInfected(); //std::cout << regions[region]->getTotalInfected() << std::endl; } //clear the transmissionVector; for (int j = 0; j < size; j++) { transmissionVector[j] = 0; } for (int j = 0; j < size; ++j){ for (int k = 0; k<size; ++k) { // transmission[to] += strain[from] * distribution[from][to] transmissionVector[j] += strainVector[k] * distributionMatrix[k][j]; //std::cout << strainVector[k] << " x " << distributionMatrix[j][k] << std::endl; } } } void updateTransmissionMatrix(region **regions) { int totalInfectious = 0; //update strain matrix. for (int strain = 0; strain < numStrains; strain++ ) { for (int region = 0; region < size; region++) { strainMatrix[strain][region] = regions[region]->getStrainInfected(strain); totalInfectious += regions[region]->getStrainInfected(strain); } } if (totalInfectious == 0) return; //clear the transmissionmatrix for (int i = 0; i < numStrains; i++) { for (int j = 0; j < size; j++) { transmissionMatrix[i][j] = 0; } } // Multiplying matrix firstMatrix and secondMatrix and storing in array mult. for (int i = 0; i < numStrains; ++i) { for (int j = 0; j < size; ++j) { for (int k = 0; k<size; ++k) { //transmission[strain][to] += strain[strain][from] * distribution[from][to] if(distributionMatrix[k][j] != 0 ) transmissionMatrix[i][j] += (float)strainMatrix[i][k] * distributionMatrix[k][j]; } } } } void printDistributionMatrix() { std::cout << "Distribution Matrix" << std::endl; for (int i = 0; i < size; i++) { std::cout << "["; for (int j = 0; j < size; j++) { std::cout << distributionMatrix[i][j] << ", "; } std::cout << "]\n"; } } void printStrainMatrix() { std::cout << "Strain Matrix" << std::endl; for (int i = 0; i < numStrains; i++) { std::cout << "["; for (int j = 0; j < size; j++) { std::cout << strainMatrix[i][j] << ", "; } std::cout << "]\n"; } } void printTransmissionMatrix() { std::cout << "transmission Matrix" << std::endl; for (int i = 0; i < numStrains; i++) { std::cout << "["; for (int j = 0; j < size; j++) { std::cout << transmissionMatrix[i][j] << ", "; } std::cout << "]\n"; } } void printDebug() { printDistributionMatrix(); printStrainMatrix(); printTransmissionMatrix(); Sleep(10000); }
#pragma once #include "FwdDecl.h" #include <vector> #include "GlyphInfo.h" namespace keng::graphics::free_type { class Face : public core::RefCountImpl<core::IRefCountObject> { public: Face(Library& library, std::vector<uint8_t> fileData); ~Face(); GlyphData RenderGlyph(const GlyphParameters& params); private: FT_Face m_face; LibraryPtr m_library; std::vector<uint8_t> m_fileData; }; }
#include <bits/stdc++.h> using namespace std; long long int camion[10009]; long long int x,i,n,p; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> p; for(i=1;i<=n;i++){ cin >> x; camion[i] = x; } for(i=1;i<=p;i++){ cin >> x; cout << camion[x] << '\n'; } return 0; }
//---------------------------------------------------------------------------- // // This file should process command line arguments and call the main game function. //---------------------------------------------------------------------------- #include "game.h" //---------------------------------------------------------------------------- SLONG main(UWORD argc, CBYTE **argv) { SLONG return_buffer; argc = argc; argv = argv; display_copyright(); return_buffer = game(); display_copyright(); return (return_buffer); } //----------------------------------------------------------------------------
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2002 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef OP_THUMBNAIL_PAGEBAR_H #define OP_THUMBNAIL_PAGEBAR_H #include "adjunct/quick/widgets/OpPagebar.h" #include "adjunct/quick/widgets/PagebarButton.h" #include "adjunct/quick/widgets/OpDragScrollbar.h" #include "modules/util/adt/oplisteners.h" class OpIndicatorButton; /** * @brief Listener to get notification when the pagebar switches to/from thumbnails * @author Petter Nilsen * * * Declaration: * Allocation: * Deletion: * */ class PagebarThumbnailStatusListener { public: virtual ~PagebarThumbnailStatusListener() {} /** * */ virtual void OnShowThumbnails(BOOL force_update = FALSE) = 0; /** * */ virtual void OnHideThumbnails(BOOL force_update = FALSE) = 0; }; /** * @brief Head/Tail toolbar subclass used to override toolbar layout * @author Petter Nilsen * * * Declaration: * Allocation: * Deletion: * */ class PagebarHeadTail : public PagebarThumbnailStatusListener, public OpToolbar { public: enum HeadTailType { PAGEBAR_UNKNOWN = 0, PAGEBAR_HEAD, PAGEBAR_TAIL, PAGEBAR_FLOATING }; /** * @param obj * @param prefs_setting * @param autoalignment_prefs_setting */ static OP_STATUS Construct(PagebarHeadTail** obj, PrefsCollectionUI::integerpref prefs_setting = PrefsCollectionUI::DummyLastIntegerPref, PrefsCollectionUI::integerpref autoalignment_prefs_setting = PrefsCollectionUI::DummyLastIntegerPref); /** * * @param button */ OP_STATUS CreateButton(OpButton **button); void OnLayout(BOOL compute_size_only, INT32 available_width, INT32 available_height, INT32& used_width, INT32& used_height); // used to know what skin we will be using void SetHeadTailType(HeadTailType type) { m_type = type; } // Implementing the PagebarThumbnailStatusListener interface virtual void OnShowThumbnails(BOOL force_update = FALSE); virtual void OnHideThumbnails(BOOL force_update = FALSE); // OpWidgetListener override to check if we allow the drop void OnDragMove(OpWidget* widget, OpDragObject* drag_object, INT32 pos, INT32 x, INT32 y); protected: PagebarHeadTail(PrefsCollectionUI::integerpref prefs_setting = PrefsCollectionUI::DummyLastIntegerPref, PrefsCollectionUI::integerpref autoalignment_prefs_setting = PrefsCollectionUI::DummyLastIntegerPref); void UpdateButtonSkins(const char *name, const char *fallback_name); private: HeadTailType m_type; BOOL m_use_thumbnails; }; /** * @brief Thumbnail/image control inside a PagebarButton, painting is handled differently * than a normal button so it needs custom code * @author Petter Nilsen * * * Declaration: * Allocation: * Deletion: * */ class PagebarImage : public OpWidget { public: PagebarImage(PagebarButton* parent); static OP_STATUS Construct(PagebarImage** obj, PagebarButton* parent); void ShowThumbnailImage(Image& image, const OpPoint &logoStart, BOOL fixed_image); OP_STATUS SetTitle(const uni_char* title); OP_STATUS GetTitle(OpString& title) { return m_title_button->GetText(title); } OpButton* GetIconButton() { return m_icon_button; } // Implementing OpToolTipListener // no tooltip data to be found here but our parent might have it virtual BOOL HasToolTipText(OpToolTip* tooltip) { return GetParent()->HasToolTipText(tooltip); } virtual void GetToolTipText(OpToolTip* tooltip, OpInfoText& text) { GetParent()->GetToolTipText(tooltip, text); } virtual void GetToolTipThumbnailText(OpToolTip* tooltip, OpString& title, OpString& url_string, URL& url) { GetParent()->GetToolTipThumbnailText(tooltip, title, url_string, url); } virtual BOOL GetPreferredPlacement(OpToolTip* tooltip, OpRect &ref_rect, PREFERRED_PLACEMENT &placement) { return GetParent()->GetPreferredPlacement(tooltip, ref_rect, placement); } // == OpWidget Hooks ====================== void OnPaint(OpWidgetPainter* widget_painter, const OpRect &paint_rect); void OnLayout(); BOOL GetTextRect(OpRect &text_rect); BOOL GetIconRect(OpRect &icon_rect); void SetCloseButtonRect(OpRect& rect) { m_close_button_rect = rect; } void SetIndicatorButton(OpIndicatorButton* button) { m_indicator_button = button; } protected: OpRect GetContentRect(); INT32 GetTitleHeight(); OpRect GetThumbnailRect(const OpRect& content_rect); void SetSkinState(OpWidget* parent); void AddBorder(OpRect& content_rect, int border); void RemoveTextHeight(OpRect& content_rect, const OpRect& text_rect); virtual void DrawSkin(VisualDevice* visual_device, OpRect& content_rect); virtual void DrawThumbnail(VisualDevice* vd, OpRect& content_rect); private: PagebarButton* m_parent; Image m_thumbnail; OpPoint m_logoStart; ///< position of logo in thumbnail OpButton* m_icon_button; OpButton* m_title_button; OpIndicatorButton* m_indicator_button; OpRect m_close_button_rect; // Position of the close button BOOL m_fixed_image; // TRUE if this is a fixed skin image }; /** * @brief * @author Petter Nilsen * * * Declaration: * Allocation: * Deletion: * */ class OpThumbnailPagebarButton : public PagebarButton, public PagebarThumbnailStatusListener { public: OpThumbnailPagebarButton(class OpThumbnailPagebar* pagebar, DesktopWindow* desktop_window); virtual ~OpThumbnailPagebarButton(); static OP_STATUS Construct(OpThumbnailPagebarButton** obj, OpThumbnailPagebar* pagebar, DesktopWindow* desktop_window); virtual void OnDeleted(); virtual BOOL CanUseThumbnails() { return m_use_thumbnail && !IsCompactButton(); } virtual void RequestUpdateThumbnail(); // Implementing the MessageObject interface virtual void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2); // Implementing the DesktopWindowListener interface // page content or privacy mode change virtual void OnDesktopWindowContentChanged(DesktopWindow* desktop_window) { SetSkin(); RequestUpdateThumbnail(); } virtual void OnLayout(); // Implementing the DocumentDesktopWindow::DocumentWindowListener interface virtual void OnStartLoading(DocumentDesktopWindow* document_window); virtual void OnLoadingFinished(DocumentDesktopWindow* document_window, OpLoadingListener::LoadingFinishStatus status, BOOL was_stopped_by_user = FALSE); // Implementing the OpWidget interface virtual OP_STATUS GetText(OpString& text) { return GetTitle(text); } virtual void OnPaint(OpWidgetPainter* widget_painter, const OpRect &paint_rect); virtual void GetRequiredSize(INT32& width, INT32& height); virtual void GetPreferedSize(INT32* w, INT32* h, INT32 cols, INT32 rows); // Implementing the PagebarThumbnailStatusListener interface virtual void OnShowThumbnails(BOOL force_update = FALSE) { SetUseThumbnail(!IsCompactButton()); } virtual void OnHideThumbnails(BOOL force_update = FALSE) { SetUseThumbnail(FALSE); } virtual void OnCompactChanged(); virtual void UpdateTextAndIcon(bool update_icon = true, bool update_text = true, bool delay_update = false); virtual OpWidgetImage* GetIconSkin(); virtual BOOL ShouldShowFavicon(); protected: void ClearRegularFields(); virtual void SetUseThumbnail(BOOL use_thumbnail); virtual void UpdateThumbnail(); virtual OP_STATUS InitPagebarButton(); virtual OP_STATUS GetTitle(OpString& title); virtual OP_STATUS SetTitle(const OpStringC& title); void SetSkin(); OpThumbnailPagebar* m_pagebar; ///< PagebarImage* m_thumbnail_button; ///< BOOL m_use_thumbnail; ///< }; /** * @brief * @author Petter Nilsen * * * Declaration: * Allocation: * Deletion: * */ class OpThumbnailPagebar : public OpPagebar, public OpDragScrollbarTarget { friend class OpPagebar; public: virtual void OnRelayout(); virtual void OnLayout(BOOL compute_size_only, INT32 available_width, INT32 available_height, INT32& used_width, INT32& used_height); // Subclassing OpToolbar virtual void OnSettingsChanged(DesktopSettings* settings); virtual BOOL SupportsThumbnails() { return TRUE; } virtual BOOL SetAlignment(Alignment alignment, BOOL write_to_prefs = FALSE); virtual void OnDeleted(); // == OpInputContext ====================== virtual BOOL OnInputAction(OpInputAction* action); // Implementing the OpDragScrollbarTarget interface virtual OpRect GetWidgetSize() { return GetRect(); } virtual void SizeChanged(const OpRect& rect); virtual BOOL IsDragScrollbarEnabled(); virtual INT32 GetMinHeightSnap(); virtual void GetMinMaxHeight(INT32& min_height, INT32& max_height); virtual void GetMinMaxWidth(INT32& min_height, INT32& max_height); virtual void EndDragging(); virtual BOOL CanUseThumbnails(); OP_STATUS AddThumbnailStatusListener(PagebarThumbnailStatusListener* listener) { return m_thumbnail_status_listeners.Add(listener); } OP_STATUS RemoveThumbnailStatusListener(PagebarThumbnailStatusListener* listener) { return m_thumbnail_status_listeners.Remove(listener); } virtual void SetExtraTopPaddings(unsigned int head_top_padding, unsigned int normal_top_padding, unsigned int tail_top_padding, unsigned int tail_top_padding_width); protected: OpThumbnailPagebar(BOOL privacy); virtual OP_STATUS CreateToolbar(OpToolbar** toolbar); virtual OP_STATUS CreatePagebarButton(PagebarButton*& button, DesktopWindow* desktop_window); virtual INT32 GetRowHeight(); virtual INT32 GetRowWidth(); virtual OP_STATUS InitPagebar(); void NotifyButtons(BOOL force_update = FALSE); void ToggleThumbnailsEnabled(); void SetupDraggedHeight(INT32 used_height); void SetupDraggedWidth(INT32 used_width); BOOL HeightAllowsThumbnails(); void CommitThumbnailsEnabled(); void RestoreThumbnailsEnabled(); void SetMinimalHeight(INT32 minimal_height) { m_minimal_height = minimal_height;} void SetDraggedHeight(INT32 dragged_height) { m_dragged_height = dragged_height;} BOOL IsThumbnailsEnabled() const { return m_thumbnails_enabled; } void SetupButton(PagebarButton* button); void ResetLayoutCache(); private: INT32 m_dragged_height; ///< height as set by dragging INT32 m_dragged_width; ///< width as set by dragging BOOL m_thumbnails_enabled; ///< BOOL m_first_layout; ///< TRUE on first layout, otherwise FALSE INT32 m_minimal_height; ///< minimal height, any scaling can not go below this height INT32 m_maximum_width; INT32 m_minimum_width; BOOL m_hide_tab_thumbnails; /// if we're on the left or right and there's not enough space to show tab thumbnails OpListeners<PagebarThumbnailStatusListener> m_thumbnail_status_listeners; ///< }; #endif // OP_THUMBNAIL_PAGEBAR_H
/* *@author: profgrammer *@date: 31-12-2018 */ #include <bits/stdc++.h> #define inf 100000000 using namespace std; string s1, s2; int dp[1500][1500]; // function that returns minimum edits required to convert s1[0 .. i-1] into s2[0 .. j-1] int minEdit(int i, int j){ // base cases. if s1 finishes we need j insertions, if s2 finishes we need i insertions if(i == 0) return j; if(j == 0) return i; // housekeeping for dp with memoisation if(dp[i][j] != inf) return dp[i][j]; // if the last characters are the same, no need to change anything and move both pointers by 1 unit if(s1[i-1] == s2[j-1]) { return dp[i][j] = minEdit(i-1, j-1); } // replace s1[i] to be s2[j]. the strings to be checked are still s1[0 .. i-1] and s2[0 .. j-1] but the cost is +1 int minReplace = 1 + minEdit(i-1, j-1); // delete s1[i], cost is +1 and the strings are now s1[0 .. i-1] and s2[0 .. j] because we need to compare the i-1th character with the jth character int minDelete = 1 + minEdit(i-1, j); // insert a character into s1 at index i. cost is +1 and now the strings to be checked are s1[0 .. i] because the ith character isn't compared yet and s2[0 .. j-1] int minInsert = 1 + minEdit(i, j-1); // return min of these 3 values return dp[i][j] = min(minReplace, min(minDelete, minInsert)); } int main() { for(int i = 0;i < 1500;i++){ for(int j = 0;j < 1500;j++) dp[i][j] = inf; } cin>>s1>>s2; if(minEdit(s1.size(), s2.size()) <= 1) cout<<"The strings are 1 edit away\n"; else cout<<"The strings are not 1 edit away\n"; }
#ifndef ___URL_CODE___HHH___ #define ___URL_CODE___HHH___ #include <string> using namespace std; //URL½âÂë string urldecode(string &str_source); //URL±àÂë string urlencode(string &str_source); string urlencode(const char* str_source, int nLen); #endif
// should produce same result with interact.cpp // use wrapped API in src/treeface/gl #include <SDL.h> #define GLEW_STATIC #include <GL/glew.h> #include <stdio.h> #include <stdlib.h> #include <set> #include "treeface/gl/GLBuffer.h" #include "treeface/gl/Program.h" #include "treeface/gl/VertexArray.h" #include "treeface/gl/VertexTemplate.h" #include <treecore/AlignedMalloc.h> #include <vector> #include <set> #include <treecore/ArrayRef.h> #include <treecore/PlatformDefs.h> #include <treecore/RefCountHolder.h> #include <treecore/Logger.h> #include <treecore/HashMultiMap.h> using namespace std; using namespace treeface; using namespace treecore; struct BBox { float x = 0; float y = 0; float width = 0; float height = 0; }; struct ColoredPoint { float x; float y; float z; float w; float r; float g; float b; float a; }; TypedTemplate attr_desc_position{"in_position", 4, treeface::TFGL_TYPE_FLOAT}; TypedTemplate attr_desc_color{"in_color", 4, treeface::TFGL_TYPE_FLOAT}; const char* src_vertex = "#version 130\n" "" "in vec4 in_position;\n" "in vec4 in_color;\n" "" "out vec4 frag_color;\n" "" "uniform bool is_active;\n" "uniform mat4 matrix;\n" "" "void main()\n" "{\n" " frag_color = in_color;\n" " if (!is_active)\n" " {\n" " frag_color = vec4(0.2, 0.2, 0.2, 1);\n" " }\n" " gl_Position = matrix * in_position;\n" "}\n"; const char* src_fragment = "#version 130\n" "in vec4 frag_color;\n" "" "void main()\n" "{\n" " gl_FragColor = frag_color;\n" "}\n"; void show_matrix( Mat4f& mat ) { printf( "%f %f %f %f\n" "%f %f %f %f\n" "%f %f %f %f\n" "%f %f %f %f\n", mat.get<0, 0>(), mat.get<0, 1>(), mat.get<0, 2>(), mat.get<0, 3>(), mat.get<1, 0>(), mat.get<1, 1>(), mat.get<1, 2>(), mat.get<1, 3>(), mat.get<2, 0>(), mat.get<2, 1>(), mat.get<2, 2>(), mat.get<2, 3>(), mat.get<3, 0>(), mat.get<3, 1>(), mat.get<3, 2>(), mat.get<3, 3>() ); } TREECORE_ALN_BEGIN( 16 ) struct Widget { TREECORE_ALIGNED_ALLOCATOR( Widget ); Widget( float x, float y, float width, float height ) { bound.x = x; bound.y = y; bound.width = width; bound.height = height; trans.data[0].set<0>( width ); trans.data[1].set<1>( height ); trans.data[3].set<0>( x ); trans.data[3].set<1>( y ); printf( "after construction\n" ); show_matrix( trans ); } void set_position( float x, float y ) { if (x != bound.x && y != bound.y) { bound.x = x; bound.y = y; trans.data[3].set<0>( x ); trans.data[3].set<1>( y ); } } void move( float dx, float dy ) { bound.x += dx; bound.y += dy; trans.data[3] += treecore::SimdObject<float, 4>( dx, dy, 0.0f, 0.0f ); } void bound_geometry_with_program() { VertexTemplate vtx_temp; vtx_temp.add_attrib( attr_desc_position, false, 0 ); vtx_temp.add_attrib( attr_desc_color, false, 0 ); array = new VertexArray( vtx_buffer, idx_buffer, vtx_temp, program ); } BBox bound; Mat4f trans; bool is_active = false; bool is_pressed = false; treecore::RefCountHolder<Program> program; treecore::RefCountHolder<GLBuffer> vtx_buffer; treecore::RefCountHolder<GLBuffer> idx_buffer; treecore::RefCountHolder<VertexArray> array; size_t n_vertex = 0; size_t n_index = 0; } TREECORE_ALN_END( 16 ); typedef bool (* is_inside_func)( float x, float y, const BBox& bound ); bool is_inside_rect( float x, float y, const BBox& bound ) { return !(x < bound.x || x > bound.x + bound.width || y < bound.y || y > bound.y + bound.height); } int window_w = 400; int window_h = 400; void build_up_sdl( SDL_Window** window, SDL_GLContext* context ) { SDL_Init( SDL_INIT_VIDEO & SDL_INIT_TIMER & SDL_INIT_EVENTS ); printf( "create window\n" ); *window = SDL_CreateWindow( "sdl_setup test", 50, 50, window_w, window_h, SDL_WINDOW_OPENGL ); if (!*window) { fprintf( stderr, "error: failed to create window: %s\n", SDL_GetError() ); exit( 1 ); } printf( "create opengl context\n" ); *context = SDL_GL_CreateContext( *window ); if (!context) { fprintf( stderr, "error: failed to create GL context: %s\n", SDL_GetError() ); exit( 1 ); } SDL_GL_MakeCurrent( *window, *context ); printf( "init glew\n" ); { GLenum glew_err = glewInit(); if (glew_err != GLEW_OK) { fprintf( stderr, "error: failed to init glew: %s\n", glewGetErrorString( glew_err ) ); exit( 1 ); } } } void show_buffer_info( GLenum target ) { int mapped = -1; int size = -1; int usage = -1; int map_length = -1; int map_offset = -1; glGetBufferParameteriv( target, GL_BUFFER_MAPPED, &mapped ); glGetBufferParameteriv( target, GL_BUFFER_SIZE, &size ); glGetBufferParameteriv( target, GL_BUFFER_USAGE, &usage ); glGetBufferParameteriv( target, GL_BUFFER_MAP_LENGTH, &map_length ); glGetBufferParameteriv( target, GL_BUFFER_MAP_OFFSET, &map_offset ); printf( "mapped: %d at %d + %d, size %d, usage %d\n", mapped, map_offset, map_length, size, usage ); } struct WidgetRenderer { void add_widget( Widget* widget ) { widgets_by_program.store( widget->program, widget ); } void render() { HashMultiMap<Program*, Widget*>::Iterator it_program_widgets( widgets_by_program ); while ( it_program_widgets.nextKey() ) { Program* program = it_program_widgets.key(); Array<Widget*>& widgets = it_program_widgets.values(); program->bind(); GLint loc_matrix = program->get_uniform_location( "matrix" ); GLint loc_is_active = program->get_uniform_location( "is_active" ); for (int i = 0; i < widgets.size(); i++) { Widget* widget = widgets[i]; program->set_uniform( loc_is_active, widget->is_active ); program->set_uniform( loc_matrix, widget->trans ); widget->array->bind(); glDrawElements( GL_TRIANGLES, 6, GLTypeEnumHelper<IndexType>::value, nullptr ); widget->array->unbind(); } program->bind(); } } HashMultiMap<Program*, Widget*> widgets_by_program; }; vector<ColoredPoint> vertex_rect = { {1, 1, 0, 1, 1, 0, 0, 1}, {1, 0, 0, 1, 0, 1, 0, 1}, {0, 1, 0, 1, 0, 0, 1, 1}, {0, 0, 0, 1, 0.5, 0.5, 0.5, 1}, }; vector<unsigned short> index_rect = { 0, 2, 1, 2, 3, 1 }; //vector<ColoredPoint> vertex_hex = { // {0.5, 1, 0, 1, 1, 0, 0, 1}, // {1, 0, 0, 1, 1, 0, 0, 1}, // {0.5, -1, 0, 1, 1, 0, 0, 1}, // {-0.5, -1, 0, 1, 1, 0, 0, 1}, // {-1, 0, 0, 1, 1, 0, 0, 1}, // {-0.5, 1, 0, 1, 1, 0, 0, 1} //}; //vector<unsigned short> index_hex = { // 0, 2, 1, // 0, 3, 2, // 0, 5, 3, // 5, 4, 3 //}; float iden_mat[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}; WidgetRenderer renderer; set<Widget*> pressed_widgets; void on_mouse_motion( SDL_MouseMotionEvent& e ) { float x = float(e.x) / float(window_w) * 2 - 1; float y = -(float(e.y) / float(window_h) * 2 - 1); HashMultiMap<Program*, Widget*>::Iterator it_program_widgets( renderer.widgets_by_program ); while ( it_program_widgets.next() ) { Array<Widget*>& widgets = it_program_widgets.values(); for (int i = 0; i < widgets.size(); i++) { if ( is_inside_rect( x, y, widgets[i]->bound ) ) { widgets[i]->is_active = true; } else { widgets[i]->is_active = false; } } } float xrel = float(e.xrel) / float(window_w) * 2; float yrel = -float(e.yrel) / float(window_h) * 2; if ( pressed_widgets.size() ) { for (Widget* widget : pressed_widgets) { widget->move( xrel, yrel ); } } } void on_mouse_down( SDL_MouseButtonEvent& e ) { if (e.button == SDL_BUTTON_LEFT) { float x = float(e.x) / float(window_w) * 2 - 1; float y = -(float(e.y) / float(window_h) * 2 - 1); printf( "press at %f %f: %d\n", x, y, e.state ); HashMultiMap<Program*, Widget*>::Iterator it_program_widgets( renderer.widgets_by_program ); while ( it_program_widgets.next() ) { Array<Widget*>& widgets = it_program_widgets.values(); for (int i = 0; i < widgets.size(); i++) { Widget* widget = widgets[i]; if ( is_inside_rect( x, y, widget->bound ) ) { printf( " widget %p\n", widget ); widget->is_pressed = true; pressed_widgets.insert( widget ); } } } printf( "%lu widgets pressed\n", pressed_widgets.size() ); } } void on_mouse_up( SDL_MouseButtonEvent& e ) { if (e.button == SDL_BUTTON_LEFT) { printf( "left released\n" ); for (Widget* widget : pressed_widgets) { widget->is_pressed = false; } pressed_widgets.clear(); } } //#ifdef TREEFACE_OS_WINDOWS //int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) //#else #undef main int main( int argc, char** argv ) //#endif { SDL_Window* window = nullptr; SDL_GLContext context = nullptr; build_up_sdl( &window, &context ); RefCountHolder<Program> program = new Program( src_vertex, src_fragment ); RefCountHolder<GLBuffer> buf_vtx = new GLBuffer( TFGL_BUFFER_VERTEX, TFGL_BUFFER_STATIC_DRAW ); RefCountHolder<GLBuffer> buf_idx = new GLBuffer( TFGL_BUFFER_INDEX, TFGL_BUFFER_STATIC_DRAW ); buf_vtx->bind(); buf_vtx->upload_data( vertex_rect.data(), vertex_rect.size() * sizeof(ColoredPoint) ); buf_vtx->unbind(); buf_idx->bind(); buf_idx->upload_data( index_rect.data(), index_rect.size() * sizeof(short) ); buf_idx->unbind(); Logger::writeToLog( "geometry vertex: " + String( buf_vtx->get_gl_handle() ) + ", index: " + String( buf_idx->get_gl_handle() ) ); vector<Widget*> widgets; for (int i = 0; i < 1; i++) { float x = -1 + 2 * float(i) / 10; for (int j = 0; j < 1; j++) { float y = -1 + 2 * float(j) / 10; Widget* widget = new Widget( x, y, 0.15f, 0.1f ); widget->program = program; widget->vtx_buffer = buf_vtx; widget->idx_buffer = buf_idx; widget->n_vertex = vertex_rect.size(); widget->n_index = index_rect.size(); widget->bound_geometry_with_program(); renderer.add_widget( widget ); } } while (1) { // process events SDL_Event event{}; bool should_exit = false; while ( SDL_PollEvent( &event ) ) { switch (event.type) { case SDL_QUIT: should_exit = true; break; case SDL_MOUSEMOTION: on_mouse_motion( event.motion ); break; case SDL_MOUSEBUTTONDOWN: on_mouse_down( event.button ); break; case SDL_MOUSEBUTTONUP: on_mouse_up( event.button ); break; } if (event.type == SDL_QUIT) { should_exit = true; } } if (should_exit) break; // do render glClear( GL_COLOR_BUFFER_BIT ); renderer.render(); SDL_GL_SwapWindow( window ); SDL_Delay( 20 ); } SDL_GL_DeleteContext( context ); SDL_Quit(); return 0; }
#include<iostream> #include<fstream> #include<iomanip> #include<queue> // limit of unsigned int using namespace std; int vCount, nEdges; bool writeToFile=false; struct nodeDistance { int node; long int distance; }; class Comparator { public: bool operator()(nodeDistance& n1, nodeDistance& n2) { if (n1.distance > n2.distance) return true; else return false; } }; void dijkstra(int s, vector< vector<int> > graph, vector < vector<int> > weight) { int mini; bool *visited = new bool [vCount]; long int *dist = new long int [vCount]; for (int i = 0; i < vCount;i++) { dist[i] = 9999999999; visited[i] = false; } dist[s] = 0; priority_queue< nodeDistance, vector< nodeDistance >, Comparator> pq; nodeDistance first = {s,0}; pq.push(first); while(!pq.empty()) { nodeDistance temp = pq.top(); pq.pop(); int node= temp.node; for(int i=0;i < graph[node].size();i++) { if(dist[graph[node][i]] > (dist[node] + weight[node][i])) dist[graph[node][i]] = dist[node] + weight[node][i]; if(!visited[graph[node][i]]) { nodeDistance newNode; newNode.node=graph[node][i]; newNode.distance=dist[graph[node][i]]; pq.push(newNode); visited[graph[node][i]]=true; } } } if(writeToFile){ ofstream myfile("dijkstra.txt"); if(myfile.is_open()){ for(int i=0;i < vCount;i++) { myfile << i << "," << dist[i] << "\n"; } myfile.close(); } } } int main(int argc, char **argv){ int src, dst, wght; int sourceNode; sourceNode = atoi(argv[2]); char *filename = argv[1]; cout << "reading file" << endl; if(argc > 3){ writeToFile = true; } ifstream read(filename); read >> vCount >> nEdges; vector< vector<int> > graph(vCount); vector< vector<int> > weight(vCount); while(read >> src >> dst >> wght){ graph[src].push_back(dst); weight[src].push_back(wght); } dijkstra(sourceNode, graph, weight); return 0; }
#include "Graph.h" void createGraph (Graph &G){ Start(G) = NULL; } adrPr AlokasiPr (string name,string type,string username){ adrPr p = new elmPr; nama(p) = name; jenis(p) = type; id(p) = username; nextCh(p) = NULL; nextPr(p) = NULL; return p; } adrCh AlokasiCh(string username){ adrCh p = new elmCh; idCh(p) = username; nextCh(p) = NULL; return p; } void inserPr (Graph &G, adrPr p){ if (Start(G) == NULL){ Start(G) = p; } else { adrPr q = Start(G); while (nextPr(q) != NULL){ q = nextPr(q); } nextPr(q) = p; } } void insertCh(Graph &G, adrCh p, adrPr q){ if (nextCh(adrPr(q)) == NULL){ nextCh(adrPr(q)) = p; } else { adrCh i = nextCh(adrPr(q)); while (nextCh(i) != NULL){ i = nextCh(i); } nextCh(i) = p; } } void connecting(string id1,string id2, Graph &G){ adrPr pr = searchId1(G,id1); adrCh ch = AlokasiCh(id2); insertCh(G,ch,pr); } adrPr searchId1(Graph G,string id1){ adrPr p = Start(G); while ((p != NULL) && (id(p) != id1)) { p = nextPr(p); } if (id(p) == id1){ return p; } else { return NULL; } } void disconnecting(Graph &G, string u1, string u2){ adrPr p = searchId1(G,u1); adrCh q = nextCh(p); while ((q != NULL) && (idCh(q) != u2)){ q = nextCh(q); } if ((nextCh(p) == q) && (nextCh(q) == NULL)){ nextCh(p) = NULL; } else if (nextCh(q) == NULL){ adrCh i = nextCh(p); while (nextCh(nextCh(i)) != NULL){ i = nextCh(i); } nextCh(i) = NULL; } else { adrCh s = nextCh(p); while (nextCh(s) != q){ s = nextCh(s); } nextCh(s) = nextCh(q); nextCh(q) = NULL; } } void deleteNode(Graph &G, adrPr &p){ if (p != NULL){ if ((p == Start(G)) && (nextPr(nextPr(p)) == NULL)){ Start(G) = nextPr(p); nextPr(p) = NULL; } else if (nextPr(p) == NULL){ adrPr i = Start(G); while (nextPr(nextPr(i)) != NULL){ i = nextPr(i); } nextPr(i) = NULL; } else { adrPr i = Start(G); while (nextPr(i) != p){ i = nextPr(i); } nextPr(i) = nextPr(p); nextPr(p) = NULL; } } else { cout << "node tidak ditemukan"<<endl; } } void jmlhFollowersnFollowing(Graph G){ if (Start(G) != NULL){ int folls = 0; int follw = 0; adrPr i = Start(G); while (i != NULL){ adrCh j = nextCh(i); while (j != NULL){ j = nextCh(j); follw++; } i = nextPr(i); folls++; } cout << "Followers: " << folls <<endl; cout << "Following: " << follw <<endl; } else { cout << "Graph empty"<<endl; } }
#include "treeface/gl/Errors.h" #include "treeface/gl/TypeUtils.h" #include "treeface/gl/VertexTemplate.h" #include "treeface/misc/Errors.h" #include "treeface/misc/PropertyValidator.h" #include "treeface/misc/StringCast.h" #include <treecore/Array.h> #include <treecore/DynamicObject.h> #include <treecore/NamedValueSet.h> #include <treecore/Result.h> #include <treecore/Variant.h> using namespace treecore; namespace treeface { inline GLsizei _expand_to_align_( GLsizei value, GLsizei align ) { if (align == 0) return value; GLsizei rem = value % align; if (rem > 0) return value - rem + align; else return value; } struct VertexTemplate::Impl { treecore::Array<TypedTemplateWithOffset> attrs; treecore::Array<size_t> elem_offsets; treecore::Array<int> elem_attr_index; uint32 size = 0; }; VertexTemplate::VertexTemplate(): m_impl( new Impl() ) {} #define KEY_NAME "name" #define KEY_N_ELEM "n_elem" #define KEY_TYPE "type" #define KEY_NORM "normalize" #define KEY_ALN "align" Result _validate_attr_kv_( const NamedValueSet& kv ) { static PropertyValidator* validator = nullptr; if (!validator) { validator = new PropertyValidator(); validator->add_item( KEY_NAME, PropertyValidator::ITEM_SCALAR, true ); validator->add_item( KEY_N_ELEM, PropertyValidator::ITEM_SCALAR, true ); validator->add_item( KEY_TYPE, PropertyValidator::ITEM_SCALAR, true ); validator->add_item( KEY_NORM, PropertyValidator::ITEM_SCALAR, false ); validator->add_item( KEY_ALN, PropertyValidator::ITEM_SCALAR, false ); } return validator->validate( kv ); } VertexTemplate::VertexTemplate( const treecore::var& list_node ): m_impl( new Impl() ) { if ( !list_node.isArray() ) throw ConfigParseError( "node is not an array" ); const Array<var>* attr_nodes = list_node.getArray(); for (int i = 0; i < attr_nodes->size(); i++) { const var& attr_node = (*attr_nodes)[i]; if ( !attr_node.isObject() ) throw ConfigParseError( "attrib node at " + String( i ) + " is not a KV" ); const NamedValueSet& attr_kv = attr_node.getDynamicObject()->getProperties(); { Result re = _validate_attr_kv_( attr_kv ); if (!re) throw ConfigParseError( "attrib node at " + String( i ) + " is invalid: " + re.getErrorMessage() ); } bool do_norm = false; if ( attr_kv.contains( Identifier( KEY_NORM ) ) ) do_norm = bool(attr_kv[KEY_NORM]); GLType type; if ( !fromString( attr_kv[KEY_TYPE], type ) ) throw ConfigParseError( "failed to parse OpenGL type from: " + attr_kv[KEY_TYPE].toString() ); int32 n_elem; if ( !fromString( attr_kv[KEY_N_ELEM], n_elem ) ) throw ConfigParseError( "failed to parse number of elements from: " + attr_kv[KEY_N_ELEM].toString() ); TypedTemplate attr_kern( attr_kv[KEY_NAME].toString(), n_elem, type ); uint32 align = size_of_gl_type( type ); if ( attr_kv.contains( KEY_ALN ) && !fromString( attr_kv[KEY_ALN], align ) ) throw ConfigParseError( "failed to parse attribute alignment from: " + attr_kv[KEY_N_ELEM].toString() ); add_attrib( attr_kern, do_norm, align ); } } VertexTemplate::VertexTemplate( const VertexTemplate& other ): m_impl( new Impl() ) { *m_impl = *other.m_impl; } VertexTemplate& VertexTemplate::operator =( const VertexTemplate& other ) { *m_impl = *other.m_impl; return *this; } VertexTemplate::~VertexTemplate() { if (m_impl) delete m_impl; } void VertexTemplate::add_attrib( const TypedTemplate& attr, bool normalize, uint32 align ) { treecore_assert( align <= attr.size() ); size_t attr_offset = _expand_to_align_( m_impl->size, align ); int prev_n_attr = m_impl->attrs.size(); m_impl->attrs.add( TypedTemplateWithOffset( attr, attr_offset, normalize ) ); size_t elem_offset = attr_offset; int elem_size = size_of_gl_type( attr.type ); for (int i = 0; i < attr.n_elem; i++) { m_impl->elem_offsets.add( elem_offset ); m_impl->elem_attr_index.add( prev_n_attr ); elem_offset += elem_size; } // update vertex size m_impl->size = attr_offset + _expand_to_align_( attr.size(), align ); } size_t VertexTemplate::vertex_size() const noexcept { return m_impl->size; } int VertexTemplate::n_elems() const noexcept { return m_impl->elem_offsets.size(); } int VertexTemplate::n_attribs() const noexcept { return m_impl->attrs.size(); } size_t VertexTemplate::get_elem_offset( int i_elem ) const noexcept { return m_impl->elem_offsets[i_elem]; } size_t VertexTemplate::get_elem_offset( int i_attr, int i_elem_in_attr ) const noexcept { const TypedTemplateWithOffset& attr = m_impl->attrs[i_attr]; return attr.offset + attr.get_elem_offset( i_elem_in_attr ); } GLType VertexTemplate::get_elem_type( int i_elem ) const noexcept { int i_attr = m_impl->elem_attr_index[i_elem]; return m_impl->attrs[i_attr].type; } int32 VertexTemplate::get_elem_size( int i_elem ) const noexcept { return size_of_gl_type( get_elem_type( i_elem ) ); } const TypedTemplateWithOffset& VertexTemplate::get_attrib( int i_attr ) const noexcept { return m_impl->attrs[i_attr]; } const TypedTemplateWithOffset& VertexTemplate::get_elem_attrib( int i_elem ) const noexcept { int i_attr = m_impl->elem_attr_index[i_elem]; return m_impl->attrs[i_attr]; } void VertexTemplate::set_value_at( void* vertex, int i_elem, const treecore::var& value ) const noexcept { size_t offset = get_elem_offset( i_elem ); char* value_p = (char*) vertex; value_p += offset; GLenum type = get_elem_attrib( i_elem ).type; switch (type) { case GL_BYTE: *( (GLbyte*) value_p ) = GLbyte( int(value) ); break; case GL_UNSIGNED_BYTE: *( (GLubyte*) value_p ) = GLubyte( int(value) ); break; case GL_SHORT: *( (GLshort*) value_p ) = GLshort( int(value) ); break; case GL_UNSIGNED_SHORT: case GL_UNSIGNED_SHORT_5_5_5_1: // TODO should we support composite type? case GL_UNSIGNED_SHORT_5_6_5: case GL_UNSIGNED_SHORT_4_4_4_4: *( (GLushort*) value_p ) = GLushort( int(value) ); break; case GL_INT: *( (GLint*) value_p ) = GLint( int(value) ); break; case GL_UNSIGNED_INT: case GL_UNSIGNED_INT_8_8_8_8: // TODO should we support composite type? case GL_UNSIGNED_INT_10_10_10_2: *( (GLuint*) value_p ) = GLuint( int(value) ); break; case GL_FLOAT: *( (GLfloat*) value_p ) = float(value); break; case GL_DOUBLE: *( (GLdouble*) value_p ) = double(value); break; default: die( "vertex template got unsupported GL type enum %x", type ); } } } // namespace treeface
#pragma once #include <array> namespace oglml { struct Glyph { Glyph() = default; ~Glyph() = default; unsigned int TextureID; // ID handle of the glyph texture std::array<int, 2> Size; // size of glyph std::array<int, 2> Bearing; // offset from baseline to left/top of glyph unsigned int Advance; // horizontal offset to advance to next glyph }; }
#include <R.h> #include <Rinternals.h> #include <Rdefines.h> #include "mat.h" using namespace std; extern "C" { #ifdef _MSC_VER __declspec(dllexport) #endif SEXP WAPLS_fit(SEXP sexp_SpecData, SEXP sexp_EnvData, SEXP sexpNPLS, SEXP sexpIsWAPLS, SEXP sexpStandX, SEXP sexpLean) { SEXP dims, retNames=R_NilValue, R_meanY, R_meanT, R_sdX; dims = Rf_getAttrib(sexp_SpecData, R_DimSymbol); int nr = INTEGER(dims)[0]; int nc = INTEGER(dims)[1]; int nPLS = INTEGER(sexpNPLS)[0]; bool bIsWAPLS = bool(INTEGER(sexpIsWAPLS)[0]); bool bStandX = bool(INTEGER(sexpStandX)[0]); bool bLean = bool(INTEGER(sexpLean)[0]); // char *str = new char[1000]; int i=0, j=0; dMat X(nr, nc, 0.0); dMat Y(nr, 1, 0.0); PROTECT(sexp_SpecData); PROTECT(sexp_EnvData); for (i=0;i<nr;i++) { Y(i,0) = REAL(sexp_EnvData)[i]; for (int j=0;j<nc;j++) { X(i,j) = REAL(sexp_SpecData)[i + nr*j]; } } UNPROTECT(2); dMat SpecCount = count(X, ColWise); dMat R, C; double meanY; double Ytottot = 1.0; if (!bIsWAPLS) { // we have linear method so centre y and calculate C, column weights meanY = mean(Y); Y -= meanY; R = dMat(nr, 1,1.0); if (bStandX) { C = transpose((sd(X, ColWise))); C *= sqrt(double(nr-1)); for (j=0;j<nc;j++) { if (C(j,0)+1.0 <= 1.0) { (C(j,0)=1.0); } } } else { C = dMat(nc,1,1.0); } } else { // Weighted averaging, calculate column and row weights, centre y C = transpose(sum(X, ColWise)); for (int j=0;j<nc;j++) { if (C(j,0)+1.0 <= 1.0) (C(j,0)=1.0); } R = sum(X, RowWise); Ytottot = sum(R); dMat wtr = R/Ytottot; meanY = sum(Y*wtr); Y -= meanY; } double meant=0.0, tau=0.0, alpha=0.0, gamma=0.0, gamma0=0.0; dMat b(nc,1,0.0), g, d, t, Wc = C / Ytottot, Wr = R / Ytottot, T, P; dMat gam(1,nPLS,0.0), meanT(1,nPLS,0.0), beta; // initialisation: setup starting gradient g // initialised and set to 0 // d is conjugate gradient, t is score vector g = X.tproduct(Y) / C; if (bIsWAPLS) { gamma0 = sum((g*g*Wc)); } else { gamma0 = sumsq(g); } d = g; // start of loop deriving pls components for (i=0;i<nPLS;i++) { if (bIsWAPLS) { t = X.product(d) / R; tau = sum((t*t*Wr)); } else { gam(0,i) = sqrt(gamma0); t = X.product(d/C); if (i>0) { t -= (T / sumsq(T, ColWise) ).product( (transpose(T).product(t) ) ); } meant = mean(t); t -= meant; tau = sumsq(t); } if ((tau+1.0) > 1.0) { alpha = gamma0 / tau; if (!bIsWAPLS) { meanT(0,i) = meant * alpha; // save meant for future calibrations } // update regression coefficients b and residuals r if (i==0) { // add jacknife later P = d * alpha; } else { P = P.concat(d * alpha, ColWise); } b += d * alpha; Y -= t * alpha; // derive new gradient g from current residuals r g = X.tproduct(Y) / C; if (bIsWAPLS) { gamma = sum(g*g*Wc); } else { gamma = sumsq(g); } if ((1.0+gamma0) > 1.0) { d *= gamma/gamma0; d += g; } else { d.fill(0.0); } gamma0 = gamma; if (i==0) { T = copy(t); // est = YOriginal - Y; if (bIsWAPLS) { beta = copy(b); } else { beta = b/C; } } else { T = T.concat(t,ColWise); // est = est.concat((YOriginal - Y),ColWise); if (bIsWAPLS) { beta = beta.concat(b,ColWise); } else { beta = beta.concat(b/C,ColWise); } } } else { break; } } if (i != nPLS) { Index II(i); gam = gam(II, ColWise); // sprintf(str, "Warning: Only %d components can be extracted", i); // SET_STRING_ELT(eMessage, 0, mkChar(str)); nPLS = i; } if (bIsWAPLS) { for (j=0;j<nc;j++) { if (SpecCount(0,j) > 0.0) { for (int kk=0;kk<cols(beta);kk++) beta(j, kk) += meanY; } else { for (int kk=0;kk<cols(beta);kk++) beta(j, kk) = missingValue(beta); } } } else { T /= gam; for (j=0;j<nc;j++) { if (SpecCount(0,j) < 1.0) { for (int kk=0;kk<cols(beta);kk++) beta(j, kk) = missingValue(beta); } } } SEXP ret = R_NilValue, R_coef = R_NilValue; PROTECT(ret = allocVector(VECSXP, 6)); PROTECT(retNames = allocVector(STRSXP, 6)); PROTECT(R_coef = allocVector(REALSXP, nc*nPLS)); for (i=0;i<nc;i++) { for (j=0;j<nPLS;j++) { if (beta.isMissing(i,j)) REAL(R_coef)[i + j*nc] = NA_REAL; else REAL(R_coef)[i + j*nc] = (beta)(i,j); } } PROTECT(R_meanY = allocVector(REALSXP, 1)); REAL(R_meanY)[0] = meanY; SET_VECTOR_ELT(ret, 0, R_coef); SET_VECTOR_ELT(ret, 1, R_meanY); SET_STRING_ELT(retNames, 0, mkChar("Beta")); SET_STRING_ELT(retNames, 1, mkChar("meanY")); UNPROTECT(2); if (!bLean) { SEXP R_T, R_P; PROTECT(R_T = allocVector(REALSXP, nr*nPLS)); for (i=0;i<nr;i++) { for (j=0;j<nPLS;j++) { if (T.isMissing(i,j)) REAL(R_T)[i + j*nr] = NA_REAL; else REAL(R_T)[i + j*nr] = T(i,j); } } PROTECT(R_P = allocVector(REALSXP, nc*nPLS)); for (i=0;i<nc;i++) { for (j=0;j<nPLS;j++) { if (P.isMissing(i,j)) REAL(R_P)[i + j*nc] = NA_REAL; else REAL(R_P)[i + j*nc] = P(i,j); } } SET_VECTOR_ELT(ret, 2, R_T); SET_VECTOR_ELT(ret, 3, R_P); UNPROTECT(2); } SET_STRING_ELT(retNames, 2, mkChar("T")); SET_STRING_ELT(retNames, 3, mkChar("P")); if (!bIsWAPLS) { PROTECT(R_meanT = allocVector(REALSXP, nPLS)); for (j=0;j<nPLS;j++) { if (meanT.isMissing(0,j)) REAL(R_meanT)[j] = NA_REAL; else REAL(R_meanT)[j] = meanT(0,j); } SET_VECTOR_ELT(ret, 4, R_meanT); PROTECT(R_sdX = allocVector(REALSXP, nc)); for (j=0;j<nc;j++) { if (C.isMissing(0,j)) REAL(R_sdX)[j] = NA_REAL; else REAL(R_sdX)[j] = C(j,0); } SET_VECTOR_ELT(ret, 5, R_sdX); UNPROTECT(2); } SET_STRING_ELT(retNames, 4, mkChar("meanT")); SET_STRING_ELT(retNames, 5, mkChar("sdX")); SET_NAMES(ret, retNames); UNPROTECT(2); // delete str; return(ret); } } extern "C" { #ifdef _MSC_VER __declspec(dllexport) #endif SEXP WAPLS_predict(SEXP sexp_SpecData, SEXP sexp_Beta, SEXP sexp_meanY, SEXP sexpIsWAPLS, SEXP sexpStandX, SEXP sexpSDX, SEXP sexp_meanT) { SEXP dims, dims_beta, R_est = R_NilValue; dims = Rf_getAttrib(sexp_SpecData, R_DimSymbol); dims_beta = Rf_getAttrib(sexp_Beta, R_DimSymbol); int nr = INTEGER(dims)[0]; int nc = INTEGER(dims)[1]; int nPLS = INTEGER(dims_beta)[1]; bool bIsWAPLS = bool(INTEGER(sexpIsWAPLS)[0]); double meanY = REAL(sexp_meanY)[0]; dMat meanT; // char *str = new char[1000]; int i=0, j=0, k=0; dMat X(nr, nc, 0.0); dMat beta(nc, nPLS, 0.0); PROTECT(sexp_SpecData); PROTECT(sexp_Beta); for (i=0;i<nr;i++) { for (j=0;j<nc;j++) { X(i,j) = REAL(sexp_SpecData)[i + nr*j]; } } for (i=0;i<nc;i++) { for (j=0;j<nPLS;j++) { if (ISNA(REAL(sexp_Beta)[i + nc*j])) beta(i,j) = missingValue(beta); else beta(i,j) = REAL(sexp_Beta)[i + nc*j]; } } UNPROTECT(2); if (!bIsWAPLS) { // bool bStandX = bool(INTEGER(sexpStandX)[0]); PROTECT(sexp_meanT); if (!bIsWAPLS) { meanT = dMat(1, nPLS); for (j=0;j<nPLS;j++) { meanT(0, j) = REAL(sexp_meanT)[j]; } } UNPROTECT(1); } dMat est(nr, nPLS, 0.0); for (j=0;j<nr;j++) { double sum=0.0; for (k=0;k<nc;k++) { if (!beta.isMissing(k, 0)) { sum += X(j,k); for (i=0;i<cols(beta);i++) { est(j,i) += X(j,k) * beta(k, i); } } } for (i=0;i<cols(beta);i++) { if (bIsWAPLS) { if (sum > 1.0E-6) { est(j,i) /= sum; } else { est(j,i) = missingValue(est); } } else { est(j,i) += meanY; } } if (!bIsWAPLS) { dMat mt = copy(meanT); for (i=1;i<nPLS;i++) { mt(0,i) += mt(0,i-1); } for (i=0;i<nPLS;i++) { est(j, i) -= mt(0, i); } } } PROTECT(R_est = allocVector(REALSXP, nr*nPLS)); for (i=0;i<nr;i++) { for (j=0;j<nPLS;j++) { if (est.isMissing(i,j)) REAL(R_est)[i + j*nr] = NA_REAL; else REAL(R_est)[i + j*nr] = est(i,j); } } UNPROTECT(1); return R_est; } }
#ifndef DPFORAM_H_ #define DPFORAM_H_ #include "fss.h" #include "protocol.h" class dpforam : public protocol { private: static fss1bit fss; uchar **rom[2]; uchar **wom; uchar **stash[2]; dpforam *pos_map; unsigned long stash_ctr; public: uint logN; uint logNBytes; uint nextLogN; uint nextLogNBytes; uint tau; uint ttp; uint DBytes; unsigned long N; bool isFirst; bool isLast; private: void init(); void init_ctr(); void set_zero(uchar **mem); void init_mem(uchar **&mem); void delete_mem(uchar **mem); void block_pir(const unsigned long addr_23[2], const uchar *const *const mem_23[2], unsigned long size, uchar *block_23[2], uchar *fss_out[2]); void rec_pir(const uint idx_23[2], const uchar *const block_23[2], uchar *rec_23[2]); void gen_delta_array(const uint idx_23[2], uint numChunk, uint chunkBytes, const uchar *const delta_23[2], uchar *delta_array_23[2]); void obliv_select(const uchar *const rom_block_23[2], const uchar *const stash_block_23[2], const uchar indicator_23[2], uchar *block_23[2]); void update_wom(const uchar *const delta_block_23[2], const uchar *const fss_out[2]); void append_stash(const uchar *const block_23[2], const uchar *const delta_block_23[2]); void wom_to_rom(); public: dpforam(const char *party, connection *cons[2], CryptoPP::AutoSeededRandomPool *rnd, CryptoPP::CTR_Mode<CryptoPP::AES>::Encryption *prgs, uint tau, uint logN, uint DBytes, bool isLast); ~dpforam(); void access(const unsigned long addr_23[2], const uchar *const new_rec_23[2], bool isRead, uchar *rec_23[2]); void print_metadata(); void test(uint iter); }; #endif /* DPFORAM_H_ */
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. ** It may not be distributed under any circumstances. */ #ifndef ACT_H #define ACT_H #include "modules/search_engine/BlockStorage.h" #include "modules/search_engine/BSCache.h" #include "modules/search_engine/ResultBase.h" // skip non-printable characters #define FIRST_CHAR ' ' #define RANDOM_STATUS_SIZE 17 class TrieBranch; /** * @brief Array Compacted Trie implementation for searching/indexing utf-8 text * @author Pavel Studeny <pavels@opera.com> * * Trie is an array of pointers indexed by appropriate character from a word. * Each pointer points to array for next character. @verbatim Example: "word" [a|b|c|....|w|...] \-> [a|b|c|.....|o|....] \-> [.....] @endverbatim * These tries are very sparse, so the pointer in ACTs can point to a free position in the current array * instead of pointing to next array. * @see http://www.n3labs.com/pdf/fast-and-space-efficient.pdf for more information about ACTs */ class ACT : public BSCache { public: typedef UINT32 WordID; struct PrefixResult : public NonCopyable { PrefixResult(void) : id(0), utf8_word(NULL) {} ~PrefixResult(void) {OP_DELETEA(utf8_word);} WordID id; char *utf8_word; }; /** * @param stored_value should be in uppercase if you use case insensitive insertions; must be allocated by new [] and will be deleted by caller */ typedef CHECK_RESULT(OP_STATUS (* TailCallback)(char **stored_value, WordID id, void *usr_val)); ACT(void); /** * ACT must be opened before you call any other method * @param path file storing the data; file is always created if it doesn't exist * @param mode Read/ReadWrite mode * @param folder might be one of predefind folders * @param tc tail compression callback if tail compression is required * @param callback_val user parameter to TailCallback */ CHECK_RESULT(OP_STATUS Open(const uni_char* path, BlockStorage::OpenMode mode, TailCallback tc = NULL, void *callback_val = NULL, OpFileFolder folder = OPFILE_ABSOLUTE_FOLDER)); /** * flush all unsaved data, commit any pending transaction and close the file */ CHECK_RESULT(OP_STATUS Close(void)); /** * erase all data */ CHECK_RESULT(OP_STATUS Clear(void)); /** * index a new word; it will have the given ID if it doesn't exist in the index already * @param word a word to index * @param id ID for a newly created word, shouldn't be 0 * @param overwrite_existing overwrite ID of the word if it was already present in the database * @return OpBoolean::IS_TRUE if the word has been created, OpBoolean::IS_FALSE if the word has been already indexed, OpStatus::OK on empty word or word without any valid character */ CHECK_RESULT(OP_BOOLEAN AddWord(const uni_char *word, WordID id, BOOL overwrite_existing = TRUE)); CHECK_RESULT(OP_BOOLEAN AddWord(const char *utf8_word, WordID id, BOOL overwrite_existing = TRUE)); /** case-sensitive */ CHECK_RESULT(OP_BOOLEAN AddCaseWord(const uni_char *word, WordID id, BOOL overwrite_existing = TRUE)); CHECK_RESULT(OP_BOOLEAN AddCaseWord(const char *utf8_word, WordID id, BOOL overwrite_existing = TRUE)); /** * delete a word from index, file might be truncated; * be carefull to delete only previously added words if you use tail compression */ CHECK_RESULT(OP_STATUS DeleteWord(const uni_char *word)); CHECK_RESULT(OP_STATUS DeleteWord(const char *utf8_word)); /** case-sensitive */ CHECK_RESULT(OP_STATUS DeleteCaseWord(const uni_char *word)); CHECK_RESULT(OP_STATUS DeleteCaseWord(const char *utf8_word)); /** * abort all write operations since the first AddWord or DeleteWord */ void Abort(void); /** * flushes all data and ends any pending transaction */ CHECK_RESULT(OP_STATUS Commit(void)); /** * write all unsaved data to disk */ // OP_STATUS Flush(ReleaseSeverity severity = ReleaseNo) {return BSCache::Flush(severity);} /** * search for a word * @return ID of the word, 0 on error or if not found */ WordID Search(const uni_char *word); WordID Search(const char *utf8_word); /** case-sensitive */ WordID CaseSearch(const uni_char *word); WordID CaseSearch(const char *utf8_word); /** * @deprecated Use the iterator methods instead */ int PrefixWords(uni_char **result, const uni_char *prefix, int max_results); int PrefixWords(char **result, const char *utf8_prefix, int max_results); int PrefixCaseWords(uni_char **result, const uni_char *prefix, int max_results); int PrefixCaseWords(char **result, const char *utf8_prefix, int max_results); /** * @deprecated Use the iterator methods instead */ int PrefixSearch(WordID *result, const uni_char *prefix, int max_results); int PrefixSearch(WordID *result, const char *utf8_prefix, int max_results); int PrefixCaseSearch(WordID *result, const uni_char *prefix, int max_results); int PrefixCaseSearch(WordID *result, const char *utf8_prefix, int max_results); /** * search for all words with given prefix * @param prefix word prefix * @param single_word if TRUE, the returned iterator will only search the given prefix as a word (and not do prefix search after all) * @return Iterator containing the first result or empty. Must be deleted by caller. NULL on error. */ SearchIterator<PrefixResult> *PrefixSearch(const uni_char *prefix, BOOL single_word = FALSE); SearchIterator<PrefixResult> *PrefixSearch(const char *utf8_prefix, BOOL single_word = FALSE); SearchIterator<PrefixResult> *PrefixCaseSearch(const uni_char *prefix, BOOL single_word = FALSE); SearchIterator<PrefixResult> *PrefixCaseSearch(const char *utf8_prefix, BOOL single_word = FALSE); /** * Used internally by Prefix(Case)Search. * Find the first word with the given prefix, ordered by unicode values, case sensitive. */ CHECK_RESULT(OP_BOOLEAN FindFirst(PrefixResult &res, const char *utf8_prefix)); /** * Used internally by Prefix(Case)Search. * Find the next word with the given prefix, ordered by unicode values, case sensitive. */ CHECK_RESULT(OP_BOOLEAN FindNext(PrefixResult &res, const char *utf8_prefix)); /** * pseudo-random number generator, RANROT B algorithm */ int Random(void); /** * save status of the random number generator */ CHECK_RESULT(OP_STATUS SaveStatus(void)); /** * restore status of the random number generator */ void RestoreStatus(void); /** * case-sensitive word comparison skipping the invalid characters * @return the number of valid common chracters or -1 on match */ static int WordsEqual(const char *w1, const char *w2, int max = -1); /** * @return an estimate of the memory used by this data structure */ #ifdef ESTIMATE_MEMORY_USED_AVAILABLE virtual size_t EstimateMemoryUsed() const; #endif friend class NodePointer; friend class TrieBranch; protected: CHECK_RESULT(OP_BOOLEAN AddCaseWord(const char *utf8_word, WordID id, int new_len, BOOL overwrite_existing)); virtual Item *NewMemoryItem(int id, Item *rbranch, int rnode, unsigned short nur); virtual Item *NewDiskItem(OpFileLength id, unsigned short nur); TailCallback m_TailCallback; void *m_callback_val; private: void InitRandom(void); UINT32 random_status[RANDOM_STATUS_SIZE + 2]; #ifdef _DEBUG // statistics public: // branch_type: 0 ~ all, 1 ~ parents, 2 ~ children int GetFillFactor(int *f_average, int *f_min, int *f_max, int *empty, int branch_type); int GetFillFactor(int *f_average, int *f_min, int *f_max, int branch_type) {return GetFillFactor(f_average, f_min, f_max, NULL, branch_type);} int GetFillDistribution(int *levels, int *counts, int max_level, int *total = NULL, OpFileLength disk_id = 2); int GetFillDistribution(int *levels, int max_level, int *total = NULL, OpFileLength disk_id = 2) {return GetFillDistribution(levels, NULL, max_level, total, disk_id);} int collision_count; #endif public: CHECK_RESULT(OP_BOOLEAN CheckConsistency(void)); static void SkipNonPrintableChars(const char* &s) { #if FIRST_CHAR >= 0 while ((unsigned char)*s <= FIRST_CHAR && *s != 0) ++s; #endif } static void SkipNonPrintableChars(const uni_char* &s) { #if FIRST_CHAR >= 0 while ((unsigned)*s <= FIRST_CHAR && *s != 0) ++s; #endif } }; #endif // ACT_H
#include "hasharr.h" #include "othermethods.h" // // KONSTRUKTOR // template <typename T> MyHashArr<T>::MyHashArr(int size, char type){ if(!isPrime(size)){ std::cerr << "\nLiczba nie jest pierwsza. Przyjmuje domyslnie 7.\n"; size=7; } if(type!='l' && type!='p' && type!='d'){ std::cerr << "\nBledny typ kolizji. Przyjmuje domyslnie linkowanie.\n"; type = 'l'; } collision_type = type; arrsize = size; secondhash = lowerPrime(arrsize); hasharr = new T[arrsize]; linkedhasharr = new MyList<T>[arrsize]; } // // DESTRUKTOR // template <typename T> MyHashArr<T>::~MyHashArr(){ } // // SPRAWDZA CZY TABLICA JEST PELNA // template <typename T> bool MyHashArr<T>::arrayFull(){ for(int i=0; i<arrsize; i++){ if(hasharr[i]==0) return false; } return true; } // // PIERWSZA FUNKCJA HASZUJACA // template <typename T> int MyHashArr<T>::hashFunction(T elem){ return elem%arrsize; } // // DRUGA FUNKCJA HASZUJACA // template <typename T> int MyHashArr<T>::secondHashFunction(T elem){ return (secondhash-(elem%secondhash)); } // // DODANIE ELEMENTU ZALEZNIE OD KOLIZJI // template <typename T> int MyHashArr<T>::addElem(T elem){ int hash = hashFunction(elem); int tmp = hash; int sample = 0; switch(collision_type){ case 'l': { if(!linkedhasharr[hash].findElement(elem)) linkedhasharr[hash].addFront(elem); else std::cerr << "\nTaki element juz istnieje!\n"; sample++; break; } case 'p': { bool added = false; if(hasharr[hash]==0){ hasharr[hash] = elem; sample++;} else{ for(int i=tmp; i<arrsize; i++){ sample++; if(hasharr[i]==elem){ std::cerr << "\nTaki element juz istnieje!\n"; added = true; break; } if(hasharr[i]==0){ hasharr[i] = elem; added = true; break; } } if(!added) for(int i=0; i<hash; i++){ sample++; if(hasharr[i]==elem){ std::cerr << "\nTaki element juz istnieje!\n"; added = true; break; } if(hasharr[i]==0){ hasharr[i] = elem; added = true; break; } } if(!added) std::cerr << "\nTablica jest pelna!\n"; } break; } case 'd': { bool added = false; int hash2 = secondHashFunction(elem); int tmp2 = hash2; while(!added){ // petla wykona sie do konca w najgorszym mozliwym przypadku sample++; if(hasharr[tmp]==0){ hasharr[tmp] = elem; added = true; break; } if(hasharr[tmp]==elem){ std::cerr << "\nTaki element juz istnieje!\n"; added = true; break; } if(arrayFull()){ std::cerr << "\nTablica jest juz pelna!\n"; added = true; break; } tmp = tmp+tmp2; tmp = tmp%arrsize; } break; } default: std::cerr << "\nChyba cos poszlo nie tak..\n"; break; } return sample; } // // ZNAJDOWANIE ELEMENTU ZALEZNIE OD KOLIZJI // template <typename T> int MyHashArr<T>::findElem(T elem){ int hash = hashFunction(elem); int tmp = hash; bool found = false; switch(collision_type){ case 'l': { if(elem == 0){ std::cout << "\nNie mozna wyszukac zera.\n"; return -1; } if(linkedhasharr[hash].findElement(elem)) return hash; else return -1; break; } case 'p': { if(elem == 0){ std::cout << "\nNie mozna wyszukac zera.\n"; return -1; } for(int i=tmp; i<arrsize; i++){ if(hasharr[i]==elem){ found = true; return i; break; } if(hasharr[i]==0){ found = true; std::cout << "\nNie ma takiego elementu!\n"; return -1; break; } } if(!found) for(int i=0; i<hash; i++){ if(hasharr[i]==elem){ found = true; return i; break; } if(hasharr[i]==0){ found = true; std::cout << "\nNie ma takiego elementu!\n"; return -1; break; } } if(!found) std::cerr << "\nNie ma takiego elementu.\n"; return -1; break; } case 'd': { int hash2 = secondHashFunction(elem); int tmp2 = hash2; int counter = 0; while(!found){ // petla wykona sie do konca w najgorszym mozliwym przypadku if(hasharr[tmp]==0){ std::cerr << "\nNie ma takiego elementu.\n"; found = true; return -1; break; } if(hasharr[tmp]==elem){ found = true; return tmp; break; } tmp = tmp+tmp2; tmp = tmp%arrsize; counter++; if(counter>arrsize){ std::cerr << "\nNie ma takiego elementu.\n"; found = true; return -1; break; } } break; } } return 0; } // // USUWANIE ELEMENTU // template <typename T> int MyHashArr<T>::removeElem(T elem){ if(collision_type!='l'){ int tmp = findElem(elem); if(tmp <0) return -1; if(tmp >=0) hasharr[tmp]=0; return tmp; }else{ linkedhasharr[findElem(elem)].removeFront(); return 1; } } // // ZWRACA ELEMENT/WYSWIETLA W PRZYPADKU LINKOWANIA // template <typename T> T MyHashArr<T>::getElem(int k){ if(collision_type=='l'){ if(!linkedhasharr[k].empty()){ linkedhasharr[k].displayList(); return 0; } else{ std::cout << "0"; return 0; } } return hasharr[k]; } template class MyHashArr<int>;
#include "checkersboard.cpp" class HumanPlayer { public: CheckersBoard makeMove(CheckersBoard, bool) const; };
/* 200902 LG codepro - [20년도_1차] 안테나 송수신 4/10 : success (6 Timeouts) timeout solution */ #include <iostream> using namespace std; int N;//송수신 안테나 수 int H[100000 + 10];//송수신 안테나 높이 void InputData(){ cin >> N; for (int i = 0; i < N; i++) cin >> H[i]; } int Solve(){ int cnt = 0; int i, j, h; for (i = 0; i < N; i++){ h = 0; for (j = i+1; j < N; j++){ if (h < H[j]){ cnt++; h = H[j]; } if (H[i] <= H[j]) break; } } return cnt; } int main(){ int ans = -1; InputData();// 입력 함수 ans = Solve();// 코드를 작성하세요 cout << ans << endl;//출력 return 0; }
// Created on: 1992-04-06 // Created by: Jacques GOUSSARD // Copyright (c) 1992-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 _IntPatch_ALine_HeaderFile #define _IntPatch_ALine_HeaderFile #include <Standard_Handle.hxx> #include <IntAna_Curve.hxx> #include <IntPatch_Line.hxx> #include <IntPatch_SequenceOfPoint.hxx> #include <TColStd_ListOfReal.hxx> class IntPatch_Point; class IntPatch_ALine; DEFINE_STANDARD_HANDLE(IntPatch_ALine, IntPatch_Line) //! Implementation of an intersection line described by a //! parametrized curve. class IntPatch_ALine : public IntPatch_Line { public: //! Creates an analytic intersection line //! when the transitions are In or Out. Standard_EXPORT IntPatch_ALine(const IntAna_Curve& C, const Standard_Boolean Tang, const IntSurf_TypeTrans Trans1, const IntSurf_TypeTrans Trans2); //! Creates an analytic intersection line //! when the transitions are Touch. Standard_EXPORT IntPatch_ALine(const IntAna_Curve& C, const Standard_Boolean Tang, const IntSurf_Situation Situ1, const IntSurf_Situation Situ2); //! Creates an analytic intersection line //! when the transitions are Undecided. Standard_EXPORT IntPatch_ALine(const IntAna_Curve& C, const Standard_Boolean Tang); //! To add a vertex in the list. Standard_EXPORT void AddVertex (const IntPatch_Point& Pnt); //! Replaces the element of range Index in the list //! of points. void Replace (const Standard_Integer Index, const IntPatch_Point& Pnt); void SetFirstPoint (const Standard_Integer IndFirst); void SetLastPoint (const Standard_Integer IndLast); //! Returns the first parameter on the intersection line. //! If IsIncluded returns True, Value and D1 methods can //! be call with a parameter equal to FirstParameter. //! Otherwise, the parameter must be greater than //! FirstParameter. Standard_Real FirstParameter (Standard_Boolean& IsIncluded) const; //! Returns the last parameter on the intersection line. //! If IsIncluded returns True, Value and D1 methods can //! be call with a parameter equal to LastParameter. //! Otherwise, the parameter must be less than LastParameter. Standard_Real LastParameter (Standard_Boolean& IsIncluded) const; //! Returns the point of parameter U on the analytic //! intersection line. gp_Pnt Value (const Standard_Real U); //! Returns Standard_True when the derivative at parameter U //! is defined on the analytic intersection line. //! In that case, Du is the derivative. //! Returns Standard_False when it is not possible to //! evaluate the derivative. //! In both cases, P is the point at parameter U on the //! intersection. Standard_Boolean D1 (const Standard_Real U, gp_Pnt& P, gp_Vec& Du); //! Tries to find the parameters of the point P on the curve. //! If the method returns False, the "projection" is //! impossible. //! If the method returns True at least one parameter has been found. //! theParams is always sorted in ascending order. void FindParameter(const gp_Pnt& P, TColStd_ListOfReal& theParams) const; //! Returns True if the line has a known First point. //! This point is given by the method FirstPoint(). Standard_Boolean HasFirstPoint() const; //! Returns True if the line has a known Last point. //! This point is given by the method LastPoint(). Standard_Boolean HasLastPoint() const; //! Returns the IntPoint corresponding to the FirstPoint. //! An exception is raised when HasFirstPoint returns False. const IntPatch_Point& FirstPoint() const; //! Returns the IntPoint corresponding to the LastPoint. //! An exception is raised when HasLastPoint returns False. const IntPatch_Point& LastPoint() const; Standard_Integer NbVertex() const; //! Returns the vertex of range Index on the line. const IntPatch_Point& Vertex (const Standard_Integer Index) const; //! Allows modifying the vertex with index theIndex on the line. IntPatch_Point& ChangeVertex(const Standard_Integer theIndex) { return svtx.ChangeValue(theIndex); } //! Set the parameters of all the vertex on the line. //! if a vertex is already in the line, //! its parameter is modified //! else a new point in the line is inserted. Standard_EXPORT void ComputeVertexParameters (const Standard_Real Tol); Standard_EXPORT const IntAna_Curve& Curve() const; DEFINE_STANDARD_RTTIEXT(IntPatch_ALine,IntPatch_Line) protected: private: IntAna_Curve curv; Standard_Boolean fipt; Standard_Boolean lapt; Standard_Integer indf; Standard_Integer indl; IntPatch_SequenceOfPoint svtx; }; #include <IntPatch_ALine.lxx> #endif // _IntPatch_ALine_HeaderFile
#include <google/protobuf/text_format.h> #include <stdio.h> #include <condition_variable> #include <cstring> #include <experimental/filesystem> #include <fstream> #include <iomanip> #include <iostream> #include <mutex> #include <queue> #include <shared_mutex> #include <string> #include <thread> #include <utility> #include <vector> #include "arraylength.h" #include "errors.h" #include "items.h" #include "locations.h" #include "mt_rand.h" #include "world.h" using namespace std; namespace filesystem = std::experimental::filesystem; using filesystem::path; #define PRODUCER_THREADS (12) #define TRANSACTION_SIZE (1000) #define SEED_GOAL (10000) constexpr long FILE_SIZE_TARGET = 1024 * 1024 * 32; // 32 MiB struct location_and_seed { Location location; int seed; }; queue<int> work; mutex m_work, m_cout; shared_mutex m_shuffle; int stop; bool done = false; queue<struct location_and_seed> shuffle_stage[(int)Item::NUM_ITEMS]; condition_variable consumer_waiting[(int)Item::NUM_ITEMS]; mutex channel_mutex[(int)Item::NUM_ITEMS]; path get_next_filename(path dir) { int max_file = 0; for (auto &dir_ent : filesystem::directory_iterator(dir)) { max_file = max(max_file, atoi(dir_ent.path().filename().c_str())); } char filename[10]; sprintf(filename, "%d", max_file + 1); return dir / path(filename); } void consumer(int item) { FILE *sink[(int)Location::NUM_LOCATIONS]; path dirs[(int)Location::NUM_LOCATIONS]; { char dirname[32]; for (int location = 1; location < (int)Location::NUM_LOCATIONS; location++) { sprintf(dirname, "results/item%03d-location%03d", item, location); dirs[location] = path(dirname); filesystem::create_directories(dirs[location]); path filename = get_next_filename(dirs[location]); sink[location] = fopen(filename.c_str(), "w"); if (!sink[location]) { cerr << "Couldn't open " << filename << endl; exit(1); } } } while (!done) { while (shuffle_stage[item].empty() && !done) { unique_lock<mutex> channel_lock(channel_mutex[item]); consumer_waiting[item].wait(channel_lock); } shared_lock<shared_mutex> lock(m_shuffle); while (!shuffle_stage[item].empty()) { int location = (int)shuffle_stage[item].front().location; fwrite(&shuffle_stage[item].front().seed, sizeof(int), 1, sink[location]); shuffle_stage[item].pop(); } for (int location = 1; location < (int)Location::NUM_LOCATIONS; location++) { if (ftell(sink[location]) > FILE_SIZE_TARGET) { fclose(sink[location]); sink[location] = fopen(get_next_filename(dirs[location]).c_str(), "w"); } } } for (int location = 1; location < (int)Location::NUM_LOCATIONS; location++) { fclose(sink[location]); } } void producer() { int base; while (true) { { lock_guard<mutex> lock(m_work); if (work.empty()) { break; } base = work.front(); work.pop(); } { lock_guard<mutex> lock(m_cout); cout << "Working on " << base << "-" << min(base + TRANSACTION_SIZE, stop) - 1 << endl; } World *result[TRANSACTION_SIZE]; for (int offset = 0; offset < TRANSACTION_SIZE && base + offset < stop; offset++) { try { result[offset] = new World(base + offset); } catch (CannotPlaceItem &e) { exit(1); } } { lock_guard<shared_mutex> lock(m_shuffle); for (int offset = 0; offset < TRANSACTION_SIZE && base + offset < stop; offset++) { auto assignments = result[offset]->view_assignments(); for (int location = 1; location < (int)Location::NUM_LOCATIONS; location++) { int item = (int)assignments[location]; struct location_and_seed temp; temp.location = (Location)location; temp.seed = base + offset; shuffle_stage[item].push(temp); consumer_waiting[item].notify_one(); } delete result[offset]; } } { lock_guard<mutex> lock(m_cout); cout << "Shipped " << base << "-" << min(base + TRANSACTION_SIZE, stop) - 1 << endl; } } { lock_guard<mutex> lock(m_cout); cout << "No more work. Shutting down." << endl; } } int main(int argc, char **argv) { if (argc == 2) { // Create and print a single seed. int seed = atoi(argv[1]); try { World result(seed); result.print(); } catch (CannotPlaceItem &e) { return 1; } return 0; } if (argc == 1) { // Read constraints and generate seeds until goal is reached. Constraints constraints; string line, buffer; while (getline(cin, line)) { buffer += line; } google::protobuf::TextFormat::ParseFromString(buffer, &constraints); mt_rand generator(time(nullptr)); int distribution[(int)Location::NUM_LOCATIONS][(int)Item::NUM_ITEMS]; memset(distribution, 0, sizeof(distribution)); int seeds_needed = SEED_GOAL; int location_required = 0; while (seeds_needed--) { int seed = generator.rand(1000000000, 0x7fffffff); World w(seed, &constraints); const Item *assignments_view = w.view_assignments(); for (int location = 0; location < (int)Location::NUM_LOCATIONS; location++) { distribution[(int)location][(int)assignments_view[location]]++; } Location l = w.where_is[(int)Item::IceRod][0]; w.clear_location(l); w.set_item(l, Item::Nothing); location_required += !w.is_num_reachable(1, Item::DefeatGanon); if (seeds_needed % 1000 == 0) { cerr << seeds_needed << " seeds needed." << endl; } } // for (int item = 0; item < (int)Item::NUM_ITEMS; item++) { // int count = distribution[(int)Location::MasterSwordPedestal][item]; // if (count) { // cout << ITEM_NAMES[item] << ": " << count << "\n"; // } // } // cout << endl << endl; for (int location = 0; location < (int)Location::NUM_LOCATIONS; location++) { int count = distribution[location][(int)Item::Hammer]; if (count) { cout << LOCATION_NAMES[location] << ": " << std::setprecision(2) << ((float)count) / SEED_GOAL * 100 << "%\n"; } } cout << location_required << " / " << SEED_GOAL << " require that location.\n"; cout << flush; return 0; } if (argc != 3) { return 2; } int start = atoi(argv[1]); stop = atoi(argv[2]); thread producers[PRODUCER_THREADS]; thread consumers[(int)Item::NUM_ITEMS]; for (int block = start; block < stop; block += TRANSACTION_SIZE) { work.push(block); } for (int t = 1; t < (int)Item::NUM_ITEMS; t++) { consumers[t] = thread(consumer, t); } for (int t = 0; t < PRODUCER_THREADS; t++) { producers[t] = thread(producer); } for (int t = 0; t < PRODUCER_THREADS; t++) { producers[t].join(); } done = true; for (int t = 1; t < (int)Item::NUM_ITEMS; t++) { consumer_waiting[t].notify_all(); consumers[t].join(); } return 0; }
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { ll n; cin >> n; vector<ll> x; for(int i = 0; i < 5; i++) { ll tmp; cin >> tmp; x.push_back((n - 1)/tmp + 1); } cout << *max_element(x.begin(), x.end()) + 4 << endl; }
#ifndef __WPP__QT__IOS_TIME_ZONE_PICKER_H__ #define __WPP__QT__IOS_TIME_ZONE_PICKER_H__ #include <QQuickItem> #ifdef Q_OS_ANDROID #include <QAndroidActivityResultReceiver> #endif #include <QTimeZone> namespace wpp { namespace qt { #ifdef Q_OS_ANDROID class IOSTimeZonePicker : public QQuickItem, QAndroidActivityResultReceiver #else class IOSTimeZonePicker : public QQuickItem #endif { Q_OBJECT Q_PROPERTY(QString timezoneId READ timezoneId WRITE setTimezoneId NOTIFY timezoneIdChanged) private: QString m_timezoneId; public: explicit IOSTimeZonePicker(QQuickItem *parent = 0); const QString& timezoneId() const { return m_timezoneId; } void setTimezoneId( const QString& timezoneId ) { this->m_timezoneId = timezoneId; emit timezoneIdChanged(); } signals: void timezoneIdChanged(); void picked(const QString& timezoneId); public slots: void open(); private: #ifdef Q_OS_IOS void *m_delegate; #endif #ifdef Q_OS_ANDROID //QAndroidJniObject takePhotoSavedUri; void handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject & data); #endif }; } } #endif
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: State1.cpp * Author: Alessio Portaro * * Created on 10 dicembre 2018, 20.06 */ #include "../State1.h" #include "../State2.h" State1::State1() {} State1* State1::getInstance() { if(instance==__null) instance = new State1(); return instance; } bool State1::isFinal() const{ return false; } AutomaState* State1::handle(char edge) const{ if(edge=='a') State1::getInstance(); if(edge=='b') return State2::getInstance(); return __null; } State1* State1::instance = __null; std::string State1::toString() { return "State1"; }
#include <iostream> #include <string> #include <cstring> #include <algorithm> #include <queue> const int INF = 1e9; struct qn{ int x, y, k; }; int n, m, k; int dist[1001][1001][11]; std::string map[1001]; std::queue<qn> q; int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; int main() { std::cin.sync_with_stdio(false); std::cin.tie(NULL); std::fill(dist[0][0], dist[0][0] + 1001 * 1001 * 11, INF); std::cin >> n >> m >> k; for(int i = 0; i < n; i++) { std::cin >> map[i]; } if(map[0][0] == '1') { k--; } q.push({0, 0, k}); int ans = INF; dist[0][0][k] = 1; while(!q.empty()) { auto [x, y, k] = q.front(); q.pop(); if(x == n - 1 && y == m - 1) { ans = std::min(ans, dist[x][y][k]); } for(int i = 0; i < 4; i++) { int nx = dx[i] + x; int ny = dy[i] + y; if(nx < 0 || ny < 0 || nx >= n || ny >= m || dist[nx][ny][k] <= dist[x][y][k] + 1) { continue; } if(k == 0 && map[nx][ny] == '1') { continue; } dist[nx][ny][k] = dist[x][y][k] + 1; if(map[nx][ny] == '0') { q.push({nx, ny, k}); } else { dist[nx][ny][k - 1] = dist[x][y][k] + 1; q.push({nx, ny, k - 1}); } } } std::cout << (ans == INF ? -1 : ans) << '\n'; return 0; }
#ifndef _PID_CALCULATOR_H #define _PID_CALCULATOR_H #include "PID_v1.h" class PidCalculator { public: PidCalculator(double sp, double kp, double ki, double kd); double calculate(double pv); private: double setpoint; double input; double output; PID *pid; }; #endif
/******************************************************************************************************//** * @file codestatisticswindow.cpp * @brief 代码统计窗口 源文件 * * 统计代码 * 选择路径, 配置后缀名, 计算代码量, 显示结果 * @author coolweedman * @version V1.00 * @date 2016-7-13 *********************************************************************************************************/ #include "codestatisticswindow.h" #include "ui_codestatisticswindow.h" #include <QFileDialog> #include <QLabel> #include <QUrl> #include <QDesktopServices> #include <QProgressBar> #include "filefilterwindow.h" #include <QTime> #include <QDebug> #include <QMessageBox> #include <QClipboard> #include "applanguage.h" /********************************************************************************************************** 宏定义 **********************************************************************************************************/ #define CODE_STAT_VERSION ( 104 ) /** * @fn CodeStatisticsWindow::CodeStatisticsWindow(QWidget *parent) * @brief 代码统计窗口 构造函数 * @param [in] parent 父窗口 * @return 无 */ CodeStatisticsWindow::CodeStatisticsWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::CodeStatisticsWindow) { ui->setupUi(this); statusBarInit(); this->setWindowTitle( tr("Code Statistics V") + QString::number( CODE_STAT_VERSION/100.0, 'f', 2 ) ); mphFileFilterWindow = new FileFilterWindow(this); mphCodeStat = new CCodeStatistics(); connect( mphCodeStat, SIGNAL(codeStatProgressSig(uint32_t,uint32_t)), this, SLOT(codeStatProgressUpdate(uint32_t,uint32_t)) ); connect( mphCodeStat, SIGNAL(codeStatDoneSig(bool)), this, SLOT(codeStatProgressDone(bool)) ); } /** * @fn CodeStatisticsWindow::~CodeStatisticsWindow(QWidget *parent) * @brief 代码统计窗口 析构函数 * @return 无 */ CodeStatisticsWindow::~CodeStatisticsWindow() { delete mphFileFilterWindow; delete mphCodeStat; delete ui; } /** * @fn CodeStatisticsWindow::statusBarInit(void) * @brief 代码统计窗口 状态栏初始化 * @return 无 */ void CodeStatisticsWindow::statusBarInit(void) { mpLabelEffeLine = new QLabel(); mpLabelCommentLine = new QLabel(); mpLabelEmptyLine = new QLabel(); mpLabelTotalLine = new QLabel(); mpLabelTotalFiles = new QLabel(); mpLabelTotalTime = new QLabel(); mpLabelEffeLine->setText( tr("Effe: ?") ); mpLabelCommentLine->setText( tr("Comment: ?") ); mpLabelEmptyLine->setText( tr("Empty: ?") ); mpLabelTotalLine->setText( tr("Total: ?") ); mpLabelTotalFiles->setText( tr("File(s): ?") ); mpLabelTotalTime->setText( tr("Time(s): ?") ); statusBar()->addWidget( mpLabelEffeLine ); statusBar()->addWidget( mpLabelCommentLine ); statusBar()->addWidget( mpLabelEmptyLine ); statusBar()->addWidget( mpLabelTotalLine ); statusBar()->addWidget( mpLabelTotalFiles ); statusBar()->addWidget( mpLabelTotalTime ); mpProgressBar = new QProgressBar(); mpProgressBar->setFixedHeight( 20 ); statusBar()->addWidget( mpProgressBar ); mpProgressBar->setVisible( false ); } /** * @fn CodeStatisticsWindow::codeStatStatusBarUpdate(void) * @brief 代码统计窗口 状态栏更新 * @return 无 */ void CodeStatisticsWindow::codeStatStatusBarUpdate(void) { mpLabelEffeLine->setText( tr(" Effe: ") + QString::number(msCodeStatResult.uiEffeCodeLines) ); mpLabelCommentLine->setText( tr(" Comment: ") + QString::number(msCodeStatResult.uiCommentCodeLines) ); mpLabelEmptyLine->setText( tr(" Empty: ") + QString::number(msCodeStatResult.uiEmptyLineNum) ); mpLabelTotalLine->setText( tr(" Total: ") + QString::number(msCodeStatResult.uiTotalLineNum) ); mpLabelTotalFiles->setText( tr(" File(s): ") + QString::number(msVecCodeStatDetailResult.length()) ); } /** * @fn CodeStatisticsWindow::codeStatTableWidgetUpdate(void) * @brief 代码统计窗口 详细信息更新 * @return 无 */ void CodeStatisticsWindow::codeStatTableWidgetUpdate(void) { ui->tableWidget->clear(); ui->tableWidget->setSortingEnabled( true ); QStringList strTitle; strTitle<<tr("File"); strTitle<<tr("Valid Code Line(s)"); strTitle<<tr("Comment Line(s)"); strTitle<<tr("Empty Line(s)"); strTitle<<tr("Total Line(s)"); ui->tableWidget->setHorizontalHeaderLabels( strTitle ); ui->tableWidget->setRowCount( msVecCodeStatDetailResult.length() ); for ( int i=0; i<msVecCodeStatDetailResult.length(); i++ ) { QVector<QTableWidgetItem *> vecItem; for ( int j=0; j<ui->tableWidget->columnCount(); j++) { vecItem.push_back( new QTableWidgetItem() ); } int iColumnCnt = 0; vecItem[iColumnCnt++]->setText( msVecCodeStatDetailResult.at(i).first ); vecItem[iColumnCnt++]->setData( Qt::DisplayRole, msVecCodeStatDetailResult.at(i).second.uiEffeCodeLines ); vecItem[iColumnCnt++]->setData( Qt::DisplayRole, msVecCodeStatDetailResult.at(i).second.uiCommentCodeLines ); vecItem[iColumnCnt++]->setData( Qt::DisplayRole, msVecCodeStatDetailResult.at(i).second.uiEmptyLineNum ); vecItem[iColumnCnt++]->setData( Qt::DisplayRole, msVecCodeStatDetailResult.at(i).second.uiTotalLineNum ); for ( int j=0; j<iColumnCnt; j++) { ui->tableWidget->setItem( i, j, vecItem.at(j) ); } } } /** * @fn CodeStatisticsWindow::codeStatProgressUpdate(uint32_t ulCur, uint32_t ulTotal) * @brief 代码统计窗口 进度更新 * @param [in] ulCur 已扫描个数 * @param [in] ulTotal 总个数 * @return 无 */ void CodeStatisticsWindow::codeStatProgressUpdate(uint32_t ulCur, uint32_t ulTotal) { mpProgressBar->setVisible( true ); mpProgressBar->setValue( ulCur * 100 / ulTotal ); } /** * @fn CodeStatisticsWindow::codeStatProgressDone(bool bStat) * @brief 代码统计窗口 进度更新 * @param [in] bStat 结束状态 * @return 无 */ void CodeStatisticsWindow::codeStatProgressDone(bool bStat) { mpLabelTotalTime->setText( tr("Time(s): ") + QString::number( mphTime->elapsed()/1000.0, 'f', 3) ); delete mphTime; mpProgressBar->setVisible( false ); mphCodeStat->codeStatResGet( msCodeStatResult ); mphCodeStat->codeStatDetailResGet( msVecCodeStatDetailResult ); mphCodeStat->codeStatResPrint( msCodeStatResult ); codeStatTableWidgetUpdate(); codeStatStatusBarUpdate(); ui->pushButtonOk->setEnabled( true ); if ( !bStat ) { QMessageBox::information( NULL, tr("Scan"), tr("Directory read fail"), QMessageBox::Cancel ); } } /** * @fn CodeStatisticsWindow::on_pushButtonLookFor_clicked(void) * @brief 代码统计窗口 浏览目录 * @return 无 */ void CodeStatisticsWindow::on_pushButtonLookFor_clicked() { QString str = QFileDialog::getExistingDirectory( this ); ui->lineEditDir->setText( str ); } /** * @fn CodeStatisticsWindow::on_pushButtonOk_clicked(void) * @brief 代码统计窗口 统计代码 * @return 无 */ void CodeStatisticsWindow::on_pushButtonOk_clicked() { mphTime = new QTime(); mphTime->start(); ui->pushButtonOk->setEnabled( false ); QStringList listStrFilter; mphFileFilterWindow->ffwFilterGet( listStrFilter ); mphCodeStat->codeStatFilterSet( listStrFilter ); mphCodeStat->codeStatProc( ui->lineEditDir->text() ); } /** * @fn CodeStatisticsWindow::on_actionExit_triggered(void) * @brief 代码统计窗口 关闭窗口 * @return 无 */ void CodeStatisticsWindow::on_actionExit_triggered() { this->close(); } void CodeStatisticsWindow::on_actionAbout_triggered() { QDesktopServices::openUrl ( QUrl::fromLocalFile("Version/Version.txt") ); } void CodeStatisticsWindow::on_actionFilter_triggered() { mphFileFilterWindow->show(); } void CodeStatisticsWindow::on_actionSourceCode_triggered() { #define SOURCE_CODE_GITHUB_ADDR ("git@github.com:coolweedman/CodeStatistics") int iRet; iRet = QMessageBox::information( this, tr("Copy GitHub Address"), SOURCE_CODE_GITHUB_ADDR, QMessageBox::Yes | QMessageBox::Cancel ); if ( QMessageBox::Yes == iRet ) { QClipboard *pClipBoard = QApplication::clipboard(); pClipBoard->setText( SOURCE_CODE_GITHUB_ADDR ); } } void CodeStatisticsWindow::on_actionInstallation_triggered() { #define INSTALLATION_PACKAGE_ADDR ( "http://pan.baidu.com/s/1dEKspTB" ) int iRet; iRet = QMessageBox::information( this, tr("Copy Address"), INSTALLATION_PACKAGE_ADDR, QMessageBox::Yes | QMessageBox::Cancel ); if ( QMessageBox::Yes == iRet ) { QClipboard *pClipBoard = QApplication::clipboard(); pClipBoard->setText( INSTALLATION_PACKAGE_ADDR ); } } void CodeStatisticsWindow::on_actionEnglish_triggered() { CAppLanguage hLanguage; hLanguage.appLanguageSet( LANGUAGE_ENGLISH ); QMessageBox::information( this, tr("Language Setting"), tr("Restart effect") ); } void CodeStatisticsWindow::on_actionChinese_triggered() { CAppLanguage hLanguage; hLanguage.appLanguageSet( LANGUAGE_CHINESE ); QMessageBox::information( this, tr("Language Setting"), tr("Restart effect") ); }
//---------------------------------------------------------------- // Game_Debug.h // // Copyright 2002-2004 Raven Software //---------------------------------------------------------------- #ifndef __GAME_DEBUG_H__ #define __GAME_DEBUG_H__ #define DBGHUD_NONE (0) #define DBGHUD_PLAYER (1<<0) #define DBGHUD_PHYSICS (1<<1) #define DBGHUD_AI (1<<2) #define DBGHUD_VEHICLE (1<<3) #define DBGHUD_PERFORMANCE (1<<4) #define DBGHUD_FX (1<<5) #define DBGHUD_MAPINFO (1<<6) #define DBGHUD_AI_PERFORM (1<<7) #define DBGHUD_SCRATCH (1<<31) #define DBGHUD_ANY (0xFFFFFFFF) #define DBGHUD_MAX 32 typedef struct debugJumpPoint_s { idStr name; idVec3 origin; idAngles angles; } debugJumpPoint_t; class rvGameDebug { public: rvGameDebug( ); void Init ( void ); void Shutdown ( void ); void BeginFrame ( void ); void EndFrame ( void ); void SetFocusEntity ( idEntity* focusEnt ); bool IsHudActive ( int hudMask, const idEntity* focusEnt = NULL ); void DrawHud ( void ); void AppendList ( const char* listname, const char* value ); void SetInt ( const char* key, int value ); void SetFloat ( const char* key, float value ); void SetString ( const char* key, const char* value ); int GetInt ( const char* key ); float GetFloat ( const char* key ); const char* GetString ( const char* key ); void SetStatInt ( const char* key, int value ); void SetStatFloat ( const char* key, float value ); void SetStatString ( const char* key, const char* value ); int GetStatInt ( const char* key ); float GetStatFloat ( const char* key ); const char* GetStatString ( const char* key ); void JumpAdd ( const char* name, const idVec3& origin, const idAngles& angles ); void JumpTo ( const char* name ); void JumpTo ( int jumpIndex ); void JumpNext ( void ); void JumpPrev ( void ); private: idList<debugJumpPoint_t> jumpPoints; int jumpIndex; idEntityPtr<idEntity> focusEntity; idEntityPtr<idEntity> overrideEntity; idUserInterface * hud[DBGHUD_MAX+1]; idUserInterface * currentHud; idDict nonGameState, gameStats; bool inFrame; }; ID_INLINE bool rvGameDebug::IsHudActive ( int hudMask, const idEntity* ent ) { return (g_showDebugHud.GetInteger() && (hudMask & (1 << (g_showDebugHud.GetInteger()-1))) && (!ent || focusEntity == ent ) ); } ID_INLINE void rvGameDebug::SetFocusEntity ( idEntity* ent ) { overrideEntity = ent; } extern rvGameDebug gameDebug; #endif /* !__GAME_DEBUG_H__ */
#include "mutex.h" namespace chidouhu { }
#include <iostream> #include <cstring> using namespace std; bool check_permutation(string str1, string str2){ int len = str1.length(); int len2 = str2.length(); int check[256]; memset(check, 0 , sizeof(check)); for(int i = 0; i<len; i++){ int temp = (int)str1[i]; int temp2 = (int)str2[i]; check[temp]++; check[temp2]--; } for(int x = 0; x<256; x++){ if(check[x] != 0){ return false; } } return true; } int main(){ string str1 = "He"; string str2 = "eH"; bool x = check_permutation(str1, str2); printf("result is %d\n", x ); return 0; }
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <cstdio> #define REP(i,n) for (int i=0; i<n; i++) using namespace std; typedef long long ll; int main() { ll n,k; ll a[100005]; ll pos; cin >> n >> k; REP(i,n){ scanf("%lld", &a[i]); if (a[i] == 1) pos = i; } if (n==k){ cout << 1 << endl; return 0; } ll left = 0,right = 0; ll ans = 0; left = pos; right = n - pos - 1; if (left < k && right < k) { cout << 2 << endl; return 0; } if (left < k) { pos = k-1; ans++; ans += (n - 1 - pos) / (k-1); if (((n-1-pos) % (k-1)) > 0) ans++; } else if (right < k) { pos = n - k; ans++; ans += pos / (k-1); if ((pos % (k-1)) > 0) ans++; } else { ans += left / (k-1); if ((left % (k-1)) > 0) ans++; ans += right / (k-1); if ((right % (k-1)) > 0) ans++; } cout << ans << endl; }
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "NodeRpcProxy.h" #include "NodeErrors.h" #include <atomic> #include <system_error> #include <thread> #include <HTTP/HttpRequest.h> #include <HTTP/HttpResponse.h> #include <System/ContextGroup.h> #include <System/Dispatcher.h> #include <System/Event.h> #include <System/EventLock.h> #include <System/Timer.h> #include <CryptoNoteCore/TransactionApi.h> #include "Common/StringTools.h" #include "CryptoNoteCore/CryptoNoteBasicImpl.h" #include "CryptoNoteCore/CryptoNoteFormatUtils.h" #include "CryptoNoteCore/CryptoNoteTools.h" #include "Rpc/CoreRpcServerCommandsDefinitions.h" #include "Rpc/HttpClient.h" #include "Rpc/JsonRpc.h" #ifndef AUTO_VAL_INIT #define AUTO_VAL_INIT(n) boost::value_initialized<decltype(n)>() #endif using namespace crypto; using namespace common; using namespace platform_system; namespace cn { namespace { std::error_code interpretResponseStatus(const std::string& status) { if (CORE_RPC_STATUS_BUSY == status) { return make_error_code(error::NODE_BUSY); } else if (CORE_RPC_STATUS_OK != status) { return make_error_code(error::INTERNAL_NODE_ERROR); } return std::error_code(); } } NodeRpcProxy::NodeRpcProxy(const std::string& nodeHost, unsigned short nodePort) : m_nodeHost(nodeHost), m_nodePort(nodePort), m_rpcTimeout(10000), m_pullInterval(5000), m_lastLocalBlockTimestamp(0), m_connected(true) { resetInternalState(); } NodeRpcProxy::~NodeRpcProxy() { shutdown(); } void NodeRpcProxy::resetInternalState() { m_stop = false; m_peerCount.store(0, std::memory_order_relaxed); m_nodeHeight.store(0, std::memory_order_relaxed); m_networkHeight.store(0, std::memory_order_relaxed); m_lastKnowHash = cn::NULL_HASH; m_knownTxs.clear(); } void NodeRpcProxy::init(const INode::Callback& callback) { std::lock_guard<std::mutex> lock(m_mutex); if (m_state != STATE_NOT_INITIALIZED) { callback(make_error_code(error::ALREADY_INITIALIZED)); return; } m_state = STATE_INITIALIZING; resetInternalState(); m_workerThread = std::thread([this, callback] { workerThread(callback); }); } bool NodeRpcProxy::shutdown() { std::unique_lock<std::mutex> lock(m_mutex); if (m_state == STATE_NOT_INITIALIZED) { return true; } else if (m_state == STATE_INITIALIZING) { m_cv_initialized.wait(lock, [this] { return m_state != STATE_INITIALIZING; }); if (m_state == STATE_NOT_INITIALIZED) { return true; } } assert(m_state == STATE_INITIALIZED); assert(m_dispatcher != nullptr); m_dispatcher->remoteSpawn([this]() { m_stop = true; // Run all spawned contexts m_dispatcher->yield(); }); if (m_workerThread.joinable()) { m_workerThread.join(); } m_state = STATE_NOT_INITIALIZED; m_cv_initialized.notify_all(); return true; } void NodeRpcProxy::workerThread(const INode::Callback& initialized_callback) { try { Dispatcher dispatcher; m_dispatcher = &dispatcher; ContextGroup contextGroup(dispatcher); m_context_group = &contextGroup; HttpClient httpClient(dispatcher, m_nodeHost, m_nodePort); m_httpClient = &httpClient; Event httpEvent(dispatcher); m_httpEvent = &httpEvent; m_httpEvent->set(); { std::lock_guard<std::mutex> lock(m_mutex); assert(m_state == STATE_INITIALIZING); m_state = STATE_INITIALIZED; m_cv_initialized.notify_all(); } initialized_callback(std::error_code()); contextGroup.spawn([this]() { Timer pullTimer(*m_dispatcher); while (!m_stop) { updateNodeStatus(); if (!m_stop) { pullTimer.sleep(std::chrono::milliseconds(m_pullInterval)); } } }); contextGroup.wait(); // Make sure all remote spawns are executed m_dispatcher->yield(); } catch (std::exception& e) { // TODO Make this pass through file log std::cout << "Exception while attempting to make a worker thread: " << e.what(); } m_dispatcher = nullptr; m_context_group = nullptr; m_httpClient = nullptr; m_httpEvent = nullptr; m_connected = false; m_rpcProxyObserverManager.notify(&INodeRpcProxyObserver::connectionStatusUpdated, m_connected); } void NodeRpcProxy::updateNodeStatus() { bool updateBlockchain = true; while (updateBlockchain) { updateBlockchainStatus(); updateBlockchain = !updatePoolStatus(); } } bool NodeRpcProxy::updatePoolStatus() { std::vector<crypto::Hash> knownTxs = getKnownTxsVector(); crypto::Hash tailBlock = m_lastKnowHash; bool isBcActual = false; std::vector<std::unique_ptr<ITransactionReader>> addedTxs; std::vector<crypto::Hash> deletedTxsIds; std::error_code ec = doGetPoolSymmetricDifference(std::move(knownTxs), tailBlock, isBcActual, addedTxs, deletedTxsIds); if (ec) { return true; } if (!isBcActual) { return false; } if (!addedTxs.empty() || !deletedTxsIds.empty()) { updatePoolState(addedTxs, deletedTxsIds); m_observerManager.notify(&INodeObserver::poolChanged); } return true; } void NodeRpcProxy::updateBlockchainStatus() { cn::COMMAND_RPC_GET_LAST_BLOCK_HEADER::request req = AUTO_VAL_INIT(req); cn::COMMAND_RPC_GET_LAST_BLOCK_HEADER::response rsp = AUTO_VAL_INIT(rsp); std::error_code ec = jsonRpcCommand("getlastblockheader", req, rsp); if (!ec) { crypto::Hash blockHash; if (!parse_hash256(rsp.block_header.hash, blockHash)) { return; } if (blockHash != m_lastKnowHash) { m_lastKnowHash = blockHash; m_nodeHeight.store(static_cast<uint32_t>(rsp.block_header.height), std::memory_order_relaxed); m_lastLocalBlockTimestamp.store(rsp.block_header.timestamp, std::memory_order_relaxed); m_observerManager.notify(&INodeObserver::localBlockchainUpdated, m_nodeHeight.load(std::memory_order_relaxed)); } } cn::COMMAND_RPC_GET_INFO::request getInfoReq = AUTO_VAL_INIT(getInfoReq); cn::COMMAND_RPC_GET_INFO::response getInfoResp = AUTO_VAL_INIT(getInfoResp); ec = jsonCommand("/getinfo", getInfoReq, getInfoResp); if (!ec) { //a quirk to let wallets work with previous versions daemons. //Previous daemons didn't have the 'last_known_block_index' parameter in RPC so it may have zero value. auto lastKnownBlockIndex = std::max(getInfoResp.last_known_block_index, m_nodeHeight.load(std::memory_order_relaxed)); if (m_networkHeight.load(std::memory_order_relaxed) != lastKnownBlockIndex) { m_networkHeight.store(lastKnownBlockIndex, std::memory_order_relaxed); m_observerManager.notify(&INodeObserver::lastKnownBlockHeightUpdated, m_networkHeight.load(std::memory_order_relaxed)); } updatePeerCount(getInfoResp.incoming_connections_count + getInfoResp.outgoing_connections_count); } if (m_connected != m_httpClient->isConnected()) { m_connected = m_httpClient->isConnected(); m_rpcProxyObserverManager.notify(&INodeRpcProxyObserver::connectionStatusUpdated, m_connected); } } void NodeRpcProxy::updatePeerCount(size_t peerCount) { if (peerCount != m_peerCount) { m_peerCount = peerCount; m_observerManager.notify(&INodeObserver::peerCountUpdated, m_peerCount.load(std::memory_order_relaxed)); } } void NodeRpcProxy::updatePoolState(const std::vector<std::unique_ptr<ITransactionReader>>& addedTxs, const std::vector<crypto::Hash>& deletedTxsIds) { for (const auto& hash : deletedTxsIds) { m_knownTxs.erase(hash); } for (const auto& tx : addedTxs) { Hash hash = tx->getTransactionHash(); m_knownTxs.emplace(std::move(hash)); } } std::vector<crypto::Hash> NodeRpcProxy::getKnownTxsVector() const { return std::vector<crypto::Hash>(m_knownTxs.begin(), m_knownTxs.end()); } bool NodeRpcProxy::addObserver(INodeObserver* observer) { return m_observerManager.add(observer); } bool NodeRpcProxy::removeObserver(INodeObserver* observer) { return m_observerManager.remove(observer); } bool NodeRpcProxy::addObserver(cn::INodeRpcProxyObserver* observer) { return m_rpcProxyObserverManager.add(observer); } bool NodeRpcProxy::removeObserver(cn::INodeRpcProxyObserver* observer) { return m_rpcProxyObserverManager.remove(observer); } size_t NodeRpcProxy::getPeerCount() const { return m_peerCount.load(std::memory_order_relaxed); } uint32_t NodeRpcProxy::getLastLocalBlockHeight() const { return m_nodeHeight.load(std::memory_order_relaxed); } uint32_t NodeRpcProxy::getLastKnownBlockHeight() const { return m_networkHeight.load(std::memory_order_relaxed); } uint32_t NodeRpcProxy::getLocalBlockCount() const { return m_nodeHeight.load(std::memory_order_relaxed); } uint32_t NodeRpcProxy::getKnownBlockCount() const { return m_networkHeight.load(std::memory_order_relaxed) + 1; } uint64_t NodeRpcProxy::getLastLocalBlockTimestamp() const { return m_lastLocalBlockTimestamp; } void NodeRpcProxy::relayTransaction(const cn::Transaction& transaction, const Callback& callback) { std::lock_guard<std::mutex> lock(m_mutex); if (m_state != STATE_INITIALIZED) { callback(make_error_code(error::NOT_INITIALIZED)); return; } scheduleRequest(std::bind(&NodeRpcProxy::doRelayTransaction, this, transaction), callback); } void NodeRpcProxy::getRandomOutsByAmounts(std::vector<uint64_t>&& amounts, uint64_t outsCount, std::vector<COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount>& outs, const Callback& callback) { std::lock_guard<std::mutex> lock(m_mutex); if (m_state != STATE_INITIALIZED) { callback(make_error_code(error::NOT_INITIALIZED)); return; } scheduleRequest(std::bind(&NodeRpcProxy::doGetRandomOutsByAmounts, this, std::move(amounts), outsCount, std::ref(outs)), callback); } void NodeRpcProxy::getNewBlocks(std::vector<crypto::Hash>&& knownBlockIds, std::vector<cn::block_complete_entry>& newBlocks, uint32_t& startHeight, const Callback& callback) { std::lock_guard<std::mutex> lock(m_mutex); if (m_state != STATE_INITIALIZED) { callback(make_error_code(error::NOT_INITIALIZED)); return; } scheduleRequest(std::bind(&NodeRpcProxy::doGetNewBlocks, this, std::move(knownBlockIds), std::ref(newBlocks), std::ref(startHeight)), callback); } void NodeRpcProxy::getTransactionOutsGlobalIndices(const crypto::Hash& transactionHash, std::vector<uint32_t>& outsGlobalIndices, const Callback& callback) { std::lock_guard<std::mutex> lock(m_mutex); if (m_state != STATE_INITIALIZED) { callback(make_error_code(error::NOT_INITIALIZED)); return; } scheduleRequest(std::bind(&NodeRpcProxy::doGetTransactionOutsGlobalIndices, this, transactionHash, std::ref(outsGlobalIndices)), callback); } void NodeRpcProxy::queryBlocks(std::vector<crypto::Hash>&& knownBlockIds, uint64_t timestamp, std::vector<BlockShortEntry>& newBlocks, uint32_t& startHeight, const Callback& callback) { std::lock_guard<std::mutex> lock(m_mutex); if (m_state != STATE_INITIALIZED) { callback(make_error_code(error::NOT_INITIALIZED)); return; } scheduleRequest(std::bind(&NodeRpcProxy::doQueryBlocksLite, this, std::move(knownBlockIds), timestamp, std::ref(newBlocks), std::ref(startHeight)), callback); } void NodeRpcProxy::getPoolSymmetricDifference(std::vector<crypto::Hash>&& knownPoolTxIds, crypto::Hash knownBlockId, bool& isBcActual, std::vector<std::unique_ptr<ITransactionReader>>& newTxs, std::vector<crypto::Hash>& deletedTxIds, const Callback& callback) { std::lock_guard<std::mutex> lock(m_mutex); if (m_state != STATE_INITIALIZED) { callback(make_error_code(error::NOT_INITIALIZED)); return; } scheduleRequest([this, knownPoolTxIds, knownBlockId, &isBcActual, &newTxs, &deletedTxIds] () mutable -> std::error_code { return this->doGetPoolSymmetricDifference(std::move(knownPoolTxIds), knownBlockId, isBcActual, newTxs, deletedTxIds); } , callback); } void NodeRpcProxy::getMultisignatureOutputByGlobalIndex(uint64_t amount, uint32_t gindex, MultisignatureOutput& out, const Callback& callback) { std::lock_guard<std::mutex> lock(m_mutex); if (m_state != STATE_INITIALIZED) { callback(make_error_code(error::NOT_INITIALIZED)); return; } // TODO NOT IMPLEMENTED callback(std::error_code()); } void NodeRpcProxy::getBlocks(const std::vector<uint32_t>& blockHeights, std::vector<std::vector<BlockDetails>>& blocks, const Callback& callback) { std::lock_guard<std::mutex> lock(m_mutex); if (m_state != STATE_INITIALIZED) { callback(make_error_code(error::NOT_INITIALIZED)); return; } // TODO NOT IMPLEMENTED callback(std::error_code()); } void NodeRpcProxy::getBlocks(uint64_t timestampBegin, uint64_t timestampEnd, uint32_t blocksNumberLimit, std::vector<BlockDetails>& blocks, uint32_t& blocksNumberWithinTimestamps, const Callback& callback) { std::lock_guard<std::mutex> lock(m_mutex); if (m_state != STATE_INITIALIZED) { callback(make_error_code(error::NOT_INITIALIZED)); return; } // TODO NOT IMPLEMENTED callback(std::error_code()); } void NodeRpcProxy::getBlocks(const std::vector<crypto::Hash>& blockHashes, std::vector<BlockDetails>& blocks, const Callback& callback) { std::lock_guard<std::mutex> lock(m_mutex); if (m_state != STATE_INITIALIZED) { callback(make_error_code(error::NOT_INITIALIZED)); return; } // TODO NOT IMPLEMENTED callback(std::error_code()); } void NodeRpcProxy::getTransactions(const std::vector<crypto::Hash>& transactionHashes, std::vector<TransactionDetails>& transactions, const Callback& callback) { std::lock_guard<std::mutex> lock(m_mutex); if (m_state != STATE_INITIALIZED) { callback(make_error_code(error::NOT_INITIALIZED)); return; } // TODO NOT IMPLEMENTED callback(std::error_code()); } void NodeRpcProxy::getPoolTransactions(uint64_t timestampBegin, uint64_t timestampEnd, uint32_t transactionsNumberLimit, std::vector<TransactionDetails>& transactions, uint64_t& transactionsNumberWithinTimestamps, const Callback& callback) { std::lock_guard<std::mutex> lock(m_mutex); if (m_state != STATE_INITIALIZED) { callback(make_error_code(error::NOT_INITIALIZED)); return; } // TODO NOT IMPLEMENTED callback(std::error_code()); } void NodeRpcProxy::getTransactionsByPaymentId(const crypto::Hash& paymentId, std::vector<TransactionDetails>& transactions, const Callback& callback) { std::lock_guard<std::mutex> lock(m_mutex); if (m_state != STATE_INITIALIZED) { callback(make_error_code(error::NOT_INITIALIZED)); return; } // TODO NOT IMPLEMENTED callback(std::error_code()); } void NodeRpcProxy::isSynchronized(bool& syncStatus, const Callback& callback) { std::lock_guard<std::mutex> lock(m_mutex); if (m_state != STATE_INITIALIZED) { callback(make_error_code(error::NOT_INITIALIZED)); return; } syncStatus = getPeerCount() > 0 && getLastLocalBlockHeight() >= getLastKnownBlockHeight(); callback(std::error_code()); } std::error_code NodeRpcProxy::doRelayTransaction(const cn::Transaction& transaction) { COMMAND_RPC_SEND_RAW_TX::request req; COMMAND_RPC_SEND_RAW_TX::response rsp; req.tx_as_hex = toHex(toBinaryArray(transaction)); return jsonCommand("/sendrawtransaction", req, rsp); } std::error_code NodeRpcProxy::doGetRandomOutsByAmounts(std::vector<uint64_t>& amounts, uint64_t outsCount, std::vector<COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount>& outs) { COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::request req = AUTO_VAL_INIT(req); COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::response rsp = AUTO_VAL_INIT(rsp); req.amounts = std::move(amounts); req.outs_count = outsCount; std::error_code ec = binaryCommand("/getrandom_outs.bin", req, rsp); if (!ec) { outs = std::move(rsp.outs); } return ec; } std::error_code NodeRpcProxy::doGetNewBlocks(std::vector<crypto::Hash>& knownBlockIds, std::vector<cn::block_complete_entry>& newBlocks, uint32_t& startHeight) { cn::COMMAND_RPC_GET_BLOCKS_FAST::request req = AUTO_VAL_INIT(req); cn::COMMAND_RPC_GET_BLOCKS_FAST::response rsp = AUTO_VAL_INIT(rsp); req.block_ids = std::move(knownBlockIds); std::error_code ec = binaryCommand("/getblocks.bin", req, rsp); if (!ec) { newBlocks = std::move(rsp.blocks); startHeight = static_cast<uint32_t>(rsp.start_height); } return ec; } std::error_code NodeRpcProxy::doGetTransactionOutsGlobalIndices(const crypto::Hash& transactionHash, std::vector<uint32_t>& outsGlobalIndices) { cn::COMMAND_RPC_GET_TX_GLOBAL_OUTPUTS_INDEXES::request req = AUTO_VAL_INIT(req); cn::COMMAND_RPC_GET_TX_GLOBAL_OUTPUTS_INDEXES::response rsp = AUTO_VAL_INIT(rsp); req.txid = transactionHash; std::error_code ec = binaryCommand("/get_o_indexes.bin", req, rsp); if (!ec) { outsGlobalIndices.clear(); for (auto idx : rsp.o_indexes) { outsGlobalIndices.push_back(static_cast<uint32_t>(idx)); } } return ec; } std::error_code NodeRpcProxy::doQueryBlocksLite(const std::vector<crypto::Hash>& knownBlockIds, uint64_t timestamp, std::vector<cn::BlockShortEntry>& newBlocks, uint32_t& startHeight) { cn::COMMAND_RPC_QUERY_BLOCKS_LITE::request req = AUTO_VAL_INIT(req); cn::COMMAND_RPC_QUERY_BLOCKS_LITE::response rsp = AUTO_VAL_INIT(rsp); req.blockIds = knownBlockIds; req.timestamp = timestamp; std::error_code ec = binaryCommand("/queryblockslite.bin", req, rsp); if (ec) { return ec; } startHeight = static_cast<uint32_t>(rsp.startHeight); for (auto& item: rsp.items) { BlockShortEntry bse; bse.hasBlock = false; bse.blockHash = std::move(item.blockId); if (!item.block.empty()) { if (!fromBinaryArray(bse.block, asBinaryArray(item.block))) { return std::make_error_code(std::errc::invalid_argument); } bse.hasBlock = true; } for (const auto& txp: item.txPrefixes) { TransactionShortInfo tsi; tsi.txId = txp.txHash; tsi.txPrefix = txp.txPrefix; bse.txsShortInfo.push_back(std::move(tsi)); } newBlocks.push_back(std::move(bse)); } return std::error_code(); } std::error_code NodeRpcProxy::doGetPoolSymmetricDifference(std::vector<crypto::Hash>&& knownPoolTxIds, crypto::Hash knownBlockId, bool& isBcActual, std::vector<std::unique_ptr<ITransactionReader>>& newTxs, std::vector<crypto::Hash>& deletedTxIds) { cn::COMMAND_RPC_GET_POOL_CHANGES_LITE::request req = AUTO_VAL_INIT(req); cn::COMMAND_RPC_GET_POOL_CHANGES_LITE::response rsp = AUTO_VAL_INIT(rsp); req.tailBlockId = knownBlockId; req.knownTxsIds = knownPoolTxIds; std::error_code ec = binaryCommand("/get_pool_changes_lite.bin", req, rsp); if (ec) { return ec; } isBcActual = rsp.isTailBlockActual; deletedTxIds = std::move(rsp.deletedTxsIds); for (const auto& tpi : rsp.addedTxs) { newTxs.push_back(createTransactionPrefix(tpi.txPrefix, tpi.txHash)); } return ec; } std::error_code NodeRpcProxy::doGetTransaction(const crypto::Hash &transactionHash, cn::Transaction &transaction) { COMMAND_RPC_GET_TRANSACTIONS::request req = AUTO_VAL_INIT(req); COMMAND_RPC_GET_TRANSACTIONS::response resp = AUTO_VAL_INIT(resp); req.txs_hashes.push_back(common::podToHex(transactionHash)); std::error_code ec = jsonCommand("/gettransactions", req, resp); if (ec) { return ec; } if (resp.missed_tx.size() > 0) { return make_error_code(cn::error::REQUEST_ERROR); } BinaryArray tx_blob; if (!common::fromHex(resp.txs_as_hex[0], tx_blob)) { return make_error_code(error::INTERNAL_NODE_ERROR); } crypto::Hash tx_hash = NULL_HASH; crypto::Hash tx_prefixt_hash = NULL_HASH; if (!parseAndValidateTransactionFromBinaryArray(tx_blob, transaction, tx_hash, tx_prefixt_hash) || tx_hash != transactionHash) { return make_error_code(error::INTERNAL_NODE_ERROR); } return ec; } void NodeRpcProxy::getTransaction(const crypto::Hash &transactionHash, cn::Transaction &transaction, const Callback &callback) { std::lock_guard<std::mutex> lock(m_mutex); if (m_state != STATE_INITIALIZED) { callback(make_error_code(error::NOT_INITIALIZED)); return; } scheduleRequest(std::bind(&NodeRpcProxy::doGetTransaction, this, std::cref(transactionHash), std::ref(transaction)), callback); } void NodeRpcProxy::scheduleRequest(std::function<std::error_code()>&& procedure, const Callback& callback) { // callback is located on stack, so copy it inside binder class Wrapper { public: Wrapper(std::function<void(std::function<std::error_code()>&, Callback&)>&& _func, std::function<std::error_code()>&& _procedure, const Callback& _callback) : func(std::move(_func)), procedure(std::move(_procedure)), callback(std::move(_callback)) { } Wrapper(const Wrapper& other) : func(other.func), procedure(other.procedure), callback(other.callback) { } Wrapper(Wrapper&& other) // must be noexcept : func(std::move(other.func)), procedure(std::move(other.procedure)), callback(std::move(other.callback)) { } void operator()() { func(procedure, callback); } private: std::function<void(std::function<std::error_code()>&, Callback&)> func; std::function<std::error_code()> procedure; Callback callback; }; assert(m_dispatcher != nullptr && m_context_group != nullptr); m_dispatcher->remoteSpawn(Wrapper([this](std::function<std::error_code()>& procedure, Callback& callback) { m_context_group->spawn(Wrapper([this](std::function<std::error_code()>& procedure, const Callback& callback) { if (m_stop) { callback(std::make_error_code(std::errc::operation_canceled)); } else { std::error_code ec = procedure(); if (m_connected != m_httpClient->isConnected()) { m_connected = m_httpClient->isConnected(); m_rpcProxyObserverManager.notify(&INodeRpcProxyObserver::connectionStatusUpdated, m_connected); } callback(m_stop ? std::make_error_code(std::errc::operation_canceled) : ec); } }, std::move(procedure), std::move(callback))); }, std::move(procedure), callback)); } template <typename Request, typename Response> std::error_code NodeRpcProxy::binaryCommand(const std::string& url, const Request& req, Response& res) { std::error_code ec; try { EventLock eventLock(*m_httpEvent); invokeBinaryCommand(*m_httpClient, url, req, res); ec = interpretResponseStatus(res.status); } catch (const ConnectException&) { ec = make_error_code(error::CONNECT_ERROR); } catch (const std::exception&) { ec = make_error_code(error::NETWORK_ERROR); } return ec; } template <typename Request, typename Response> std::error_code NodeRpcProxy::jsonCommand(const std::string& url, const Request& req, Response& res) { std::error_code ec; try { EventLock eventLock(*m_httpEvent); invokeJsonCommand(*m_httpClient, url, req, res); ec = interpretResponseStatus(res.status); } catch (const ConnectException&) { ec = make_error_code(error::CONNECT_ERROR); } catch (const std::exception&) { ec = make_error_code(error::NETWORK_ERROR); } return ec; } template <typename Request, typename Response> std::error_code NodeRpcProxy::jsonRpcCommand(const std::string& method, const Request& req, Response& res) { std::error_code ec = make_error_code(error::INTERNAL_NODE_ERROR); try { EventLock eventLock(*m_httpEvent); JsonRpc::JsonRpcRequest jsReq; jsReq.setMethod(method); jsReq.setParams(req); HttpRequest httpReq; HttpResponse httpRes; httpReq.setUrl("/json_rpc"); httpReq.setBody(jsReq.getBody()); m_httpClient->request(httpReq, httpRes); JsonRpc::JsonRpcResponse jsRes; if (httpRes.getStatus() == HttpResponse::STATUS_200) { jsRes.parse(httpRes.getBody()); if (jsRes.getResult(res)) { ec = interpretResponseStatus(res.status); } } } catch (const ConnectException&) { ec = make_error_code(error::CONNECT_ERROR); } catch (const std::exception&) { ec = make_error_code(error::NETWORK_ERROR); } return ec; } }
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- /** Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * @file RichTextEditor.h * @author Owner: Alexander Remen (alexr) */ #ifndef RICHTEXTEDITOR_H #define RICHTEXTEDITOR_H #include "adjunct/desktop_pi/DesktopColorChooser.h" #include "adjunct/desktop_pi/DesktopFontChooser.h" #include "adjunct/m2_ui/util/ComposeFontList.h" #include "adjunct/m2_ui/widgets/RichTextEditorListener.h" #include "modules/documentedit/OpDocumentEdit.h" #include "adjunct/quick_toolkit/widgets/QuickOpWidgetWrapper.h" class OpToolbar; class OpBrowserView; class DesktopWindow; class DesktopFileChooser; class Upload_Multipart; class HTML_Element; class RichTextEditor : public OpWidget , public OpColorChooserListener , public OpDocumentEditListener , public OpFontChooserListener , public OpLoadingListener , public OpMailClientListener { public: /** Public static constructor */ static OP_STATUS Construct(RichTextEditor** obj); /** Initialize the rich text editor * @param Parent DesktopWindow* * @param is_HTML - whether the content is HTML or plain text (when starting) * @param RichTextEditorListener * @param message_id - for creating unique URLs */ OP_STATUS Init(DesktopWindow* parent_window, BOOL is_HTML, RichTextEditorListener* listener, UINT32 message_id); /** Initializes the font dropdown in the richt text editor * call this when the toolbar has been reset, otherwise it will be empty */ OP_STATUS InitFontDropdown(); // OpInputContext virtual BOOL OnInputAction(OpInputAction* action); virtual const char* GetInputContextName() {return "Rich Text Editor";} virtual Type GetType() {return WIDGET_TYPE_RICH_TEXT_EDITOR;} //OpColorChooserListener virtual void OnColorSelected(COLORREF color); //OpDocumentEditListener virtual void OnCaretMoved() { g_input_manager->UpdateAllInputStates(); UpdateFontDropdownSelection(); } virtual void OnTextChanged() { m_listener->OnTextChanged(); } virtual void OnTextDirectionChanged (BOOL to_rtl) { m_is_rtl = to_rtl; if (m_listener) m_listener->OnTextDirectionChanged(to_rtl);} // OpMailClientListener virtual void GetExternalEmbedPermission(OpWindowCommander* commander, BOOL& has_permission) { has_permission = TRUE; } virtual void OnExternalEmbendBlocked(OpWindowCommander* commander) {} //DesktopFontChooser virtual void OnFontSelected(FontAtt& font, COLORREF color); /** Gets whether the current formatting is plain text or HTML * @return TRUE if HTML formatting, FALSE if plaintext */ BOOL IsHTML() const { return m_is_HTML_message; } /** Get the multipart/related of the current document in the rich text editor * @param - returns the multipart related with the HTML part * @param - the charset you want to use */ OP_STATUS GetEncodedHTMLPart(OpAutoPtr<Upload_Multipart>& html_multipart, const OpStringC8 &charset_to_use); /** Get the HTML source of the current document in the rich text editor * @param content - returns the HTML source code for the * @param body_only - whether to include the head section or not */ OP_STATUS GetHTMLSource(OpString &content, BOOL body_only = FALSE) const; /** Get the plain text equivalent of the current document in the rich text editor * @param equivalent - returns the plain text equivalent */ OP_STATUS GetTextEquivalent(OpString& equivalent) const; /** Insert some HTML in the documentedit * @param source_code - the raw HTML to insert into the documentedit */ void InsertHTML(OpString& source_code); /** Insert a link in the documentedit * @param title - the text that should be linkified * @param address - the URL address */ void InsertLink(OpString& title, OpString& address); /** Insert an image to the documentedit * @param image_url - the url to the image to insert into the documentedit */ void InsertImage(OpString& image_url); /** Sets the focus to the documentedit */ void SetFocusToBody(); /** Sets the content in the documentedit and updates the view * @param content - the content to start with in the rich text editor * @param body_only - whether this content is only the body or has some styling in the head section * @param context_id - if there are images, you need to specify the context_id of the images */ OP_STATUS SetMailContentAndUpdateView(const OpStringC &content, BOOL body_only, URL_CONTEXT_ID context_id = 0); /** Load some plaintext in the documentedit * @param body - the plain text to load */ OP_STATUS SetPlainTextBody(const OpStringC& body); /** Set the text direction in the rich text editor * @param direction - AccountTypes::DIR_AUTOMATIC, DIR_LEFT_TO_RIGHT or DIR_RIGHT_TO_LEFT * @param update_body - whether to update the window or not (eg. not necessary if updated a bit later) * @param force_keep_auto_detecting - changing the direction would normally turn off autodetection, this overrides that */ void SetDirection(int direction, BOOL update_body, BOOL force_keep_auto_detecting = FALSE); /** Append the signature to the text. If this function has already been called * - ie. the signature is already been set, it will try to find it first in the logical tree and replace it * @param signature in HTML or plain text * @param is_HTML_signature whether the signature is in HTML or not * @param update_view should be FALSE if you call SetMailContentAndUpdateView right after with append_signature = TRUE */ OP_STATUS SetSignature(const OpStringC signature, BOOL is_HTML_signature, BOOL update_view = TRUE); /** Toggle between HTML and plain text * @param update_view whether we should update the view or it will be done shortly after by something else */ void SwitchHTML(BOOL update_view = 1); /** The rich text editor will append m_signature the next time it updates the content */ void UpdateSignature() { m_update_signature = TRUE; } /** OnLayout */ virtual void OnLayout(); /** To make DesktopWindowSpy::GetTargetBrowserView work */ OpBrowserView* GetBrowserView() {return m_HTML_compose_edit;} /** Changes the skin to match dialog skin, and forces the formatting toolbar to be visible all the time */ void SetEmbeddedInDialog(); /** Returns the preferred width of this widget which is when the HTML formatting toolbar doesn't wrap */ unsigned GetPreferredWidth(); /** Functions that implements OpLoadingListener * Only used to do stuff when the first reflow is done in OnLoadingFinished() */ virtual void OnLoadingFinished(OpWindowCommander* commander, LoadingFinishStatus status); virtual void OnUrlChanged(OpWindowCommander* commander, URL& url) {} // NOTE: This will be removed from OpLoadingListener soon (CORE-35579), don't add anything here! virtual void OnUrlChanged(OpWindowCommander* commander, const uni_char* url) {} virtual void OnStartLoading(OpWindowCommander* commander) {} virtual void OnLoadingProgress(OpWindowCommander* commander, const LoadingInformation* info) {} virtual void OnAuthenticationRequired(OpWindowCommander* commander, OpAuthenticationCallback* callback) {} virtual void OnAuthenticationCancelled(OpWindowCommander* commander, URL_ID authid) {} virtual void OnStartUploading(OpWindowCommander* commander) {} virtual void OnUploadingFinished(OpWindowCommander* commander, LoadingFinishStatus status) {} virtual void OnLoadingCreated(OpWindowCommander* commander) {} virtual void OnUndisplay(OpWindowCommander* commander) {} virtual BOOL OnLoadingFailed(OpWindowCommander* commander, int msg_id, const uni_char* url) { return FALSE; } virtual void OnXmlParseFailure(OpWindowCommander*) {} #ifdef DOC_SEARCH_SUGGESTIONS_SUPPORT virtual void OnSearchSuggestionsRequested(OpWindowCommander* commander, const uni_char* url, OpSearchSuggestionsCallback* callback) {} #endif private: /** Sets the mail content to a URL, after having created valid HTML * @param content - the mail content to use (has to be plain text if m_is_HTML_message is FALSE) * @param url - the url where the content will be written to * @param body_only - if the function should add a <head> and a <style> section or not * @param charset - the charset to use when writing the 8bit content */ OP_STATUS SetMailContentToURL(const OpStringC &content, URL& url, BOOL body_only, const OpStringC8 &charset); OP_STATUS GetDefaultFont(OpString& default_font, INT32 &font_size) const; OP_STATUS UpdateFontDropdownSelection(); // Private constructor RichTextEditor() : m_parent_window(NULL) , m_is_HTML_message(FALSE) , m_update_signature(FALSE) , m_listener(NULL) , m_HTML_formatting_toolbar(NULL) , m_HTML_compose_edit(NULL) , m_draft_number(0) , m_message_id(0) , m_context_id(0) , m_document_edit(NULL) , m_is_rtl(FALSE) , m_autodetect_direction(TRUE) {}; DesktopWindow* m_parent_window; BOOL m_is_HTML_message; OpString m_signature; BOOL m_update_signature; RichTextEditorListener* m_listener; OpToolbar* m_HTML_formatting_toolbar; OpBrowserView* m_HTML_compose_edit; ComposeFontList m_composefont_list; // these 2 are required to make unique draft urls: UINT32 m_draft_number; UINT32 m_message_id; URL_CONTEXT_ID m_context_id; OpDocumentEdit* m_document_edit; BOOL m_is_rtl; BOOL m_autodetect_direction; }; #endif //RICHTEXTEDITOR_H
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #include "Utils.h" #include <sound/SoundException.h> #include <boost/lexical_cast.hpp> #ifndef NDEBUG std::string slResultToString (SLresult result) { switch (result) { case SL_RESULT_SUCCESS: return "SL_RESULT_SUCCESS"; case SL_RESULT_PRECONDITIONS_VIOLATED: return "SL_RESULT_PRECONDITIONS_VIOLATED"; case SL_RESULT_PARAMETER_INVALID: return "SL_RESULT_PARAMETER_INVALID"; case SL_RESULT_MEMORY_FAILURE: return "SL_RESULT_MEMORY_FAILURE"; case SL_RESULT_RESOURCE_ERROR: return "SL_RESULT_RESOURCE_ERROR"; case SL_RESULT_RESOURCE_LOST: return "SL_RESULT_RESOURCE_LOST"; case SL_RESULT_IO_ERROR: return "SL_RESULT_IO_ERROR"; case SL_RESULT_BUFFER_INSUFFICIENT: return "SL_RESULT_BUFFER_INSUFFICIENT"; case SL_RESULT_CONTENT_CORRUPTED: return "SL_RESULT_CONTENT_CORRUPTED"; case SL_RESULT_CONTENT_UNSUPPORTED: return "SL_RESULT_CONTENT_UNSUPPORTED"; case SL_RESULT_CONTENT_NOT_FOUND: return "SL_RESULT_CONTENT_NOT_FOUND"; case SL_RESULT_PERMISSION_DENIED: return "SL_RESULT_PERMISSION_DENIED"; case SL_RESULT_FEATURE_UNSUPPORTED: return "SL_RESULT_FEATURE_UNSUPPORTED"; case SL_RESULT_INTERNAL_ERROR: return "SL_RESULT_INTERNAL_ERROR"; case SL_RESULT_UNKNOWN_ERROR: return "SL_RESULT_UNKNOWN_ERROR"; case SL_RESULT_OPERATION_ABORTED: return "SL_RESULT_OPERATION_ABORTED"; case SL_RESULT_CONTROL_LOST: return "SL_RESULT_CONTROL_LOST"; } return "UNKNOWN result!"; } #else std::string slResultToString (SLresult result) { return ""; } #endif /****************************************************************************/ void soundThrowImpl (const char *file, long line, const char *function, SLresult result, std::string const &msg) { if (result != SL_RESULT_SUCCESS) { throw Sound::SoundException (std::string ("SoundException@ ") + std::string (file) + ":" + boost::lexical_cast <std::string> (line) + " " + std::string (function) + " " + msg + " " + slResultToString (result)); } }
#include<iostream> #include<cmath> #include<algorithm> using namespace std; int main(){ int a[3]; for(int i=0;i<3;++i){ cin>>a[i]; } sort(a,a+3); if(!(a[0]+a[1]<a[2]||a[0]<a[2]-a[1])){ if(sqrt(a[0])+sqrt(a[1])==sqrt(a[2])){ cout<<"yes"<<endl; return 0; }else{ cout<<"no"<<endl; return 0; } }else{ cout<<"not a triangle"<<endl; return 0; } }
#include <iostream> #include <map> #include <string> #include "timer.h" #ifndef NTIMER namespace timer { bool Timer::enabled = false; std::ostream *Timer::out = &std::cout; std::map<std::string, Timer> Timer::_timers; } // namespace timer #endif
#include <stdio.h> #include <windows.h> double time_measure(int mode) { static double PCFreq = 0.0; static __int64 CounterStart = 0; if (mode == 1) // start { LARGE_INTEGER li; if (!QueryPerformanceFrequency(&li)) printf("QueryPerformanceFrequency failed!\n"); PCFreq = double(li.QuadPart) / 1000.0; QueryPerformanceCounter(&li); CounterStart = li.QuadPart; return(-1.0); } else if (mode == 2) // end { LARGE_INTEGER li; QueryPerformanceCounter(&li); return double(li.QuadPart - CounterStart) / PCFreq; } }
#include <Servo.h> const int TrigPinFront = 10; const int EchoPinFront = 9; const int TrigPinBack = 11; const int EchoPinBack = 12; const int SteerPin = 6; const int WheelPin = 7; const int LEDFront = 5; const int LEDBack = 4; int directio = 90; int speeds = 90; Servo Steer; Servo Wheel; bool error = false; int reading = 68; int EFront = 0; int EBack = 0; void setup() { Steer.attach(SteerPin); Wheel.attach(WheelPin); pinMode(TrigPinFront, OUTPUT); pinMode(EchoPinFront, INPUT); pinMode(TrigPinBack, OUTPUT); pinMode(EchoPinBack, INPUT); pinMode(LEDFront, OUTPUT); pinMode(LEDBack, OUTPUT); Serial.begin(9600); Wheel.write(30); Steer.write(90); } //enum Dir { Left, Straight, Right }; int getdistance(int TPin,int EPin) { long duration; int distance; digitalWrite(TPin, LOW); delayMicroseconds(2); digitalWrite(TPin, HIGH); delayMicroseconds(10); digitalWrite(TPin, LOW); duration = pulseIn(EPin, HIGH); distance = int(duration*0.034)>>1; //Serial.println(distance); return distance; } void loop() { int disFront = getdistance(TrigPinFront, EchoPinFront); int disBack = getdistance(TrigPinBack, EchoPinBack); if(disFront < 50 && disBack < 50 && disFront != 0 && disBack !=0) { EFront++; EBack++; } else if(disFront < 50 && disFront != 0 && disBack !=0) { EFront++; EBack = 0; } else if(disBack < 50 && disFront != 0 && disBack !=0) { EFront = 0; EBack++; } else { EFront = 0; EBack = 0; } if(EFront > 9 && EBack > 9) { digitalWrite(LEDFront, HIGH); digitalWrite(LEDBack, HIGH); speeds = 90; directio = 90; error = true; Serial.println(disBack); } else if(EFront > 9) { digitalWrite(LEDFront, HIGH); digitalWrite(LEDBack, LOW); speeds = 70; directio = 90; error = true; } else if(EBack > 9) { digitalWrite(LEDFront, LOW); digitalWrite(LEDBack, HIGH); speeds = 105; directio = 90; error = true; } else if(error) { error = false; digitalWrite(LEDFront, LOW); digitalWrite(LEDBack, LOW); speeds = 90; directio = 90; reading = 68; } else { error = false; speeds = ((reading>>4)<<2) + 74; directio = ((reading & 7)<<3) + 58; //Serial.println(directio); } Wheel.write(speeds); Steer.write(directio); delay(20); } void serialEvent(){ //statements if(Serial.available() > 0) { reading = Serial.read(); } }
// Copyright (c) 2012-2017 The Cryptonote developers // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <cstddef> #include <cstring> #include <fstream> #include <string> #include <vector> #include "crypto/crypto.h" #include "crypto/hash.h" #include "crypto-tests.h" #include "../Io.h" using namespace std; typedef crypto::Hash chash; bool operator !=(const crypto::EllipticCurveScalar &a, const crypto::EllipticCurveScalar &b) { return 0 != memcmp(&a, &b, sizeof(crypto::EllipticCurveScalar)); } bool operator !=(const crypto::EllipticCurvePoint &a, const crypto::EllipticCurvePoint &b) { return 0 != memcmp(&a, &b, sizeof(crypto::EllipticCurvePoint)); } bool operator !=(const crypto::KeyDerivation &a, const crypto::KeyDerivation &b) { return 0 != memcmp(&a, &b, sizeof(crypto::KeyDerivation)); } int main(int argc, char *argv[]) { fstream input; string cmd; size_t test = 0; bool error = false; setup_random(); if (argc != 2) { cerr << "invalid arguments" << endl; return 1; } input.open(argv[1], ios_base::in); for (;;) { ++test; input.exceptions(ios_base::badbit); if (!(input >> cmd)) { break; } input.exceptions(ios_base::badbit | ios_base::failbit | ios_base::eofbit); if (cmd == "check_scalar") { crypto::EllipticCurveScalar scalar; bool expected, actual; get(input, scalar, expected); actual = check_scalar(scalar); if (expected != actual) { goto error; } } else if (cmd == "random_scalar") { crypto::EllipticCurveScalar expected, actual; get(input, expected); random_scalar(actual); if (expected != actual) { goto error; } } else if (cmd == "hash_to_scalar") { vector<char> data; crypto::EllipticCurveScalar expected, actual; get(input, data, expected); crypto::hash_to_scalar(data.data(), data.size(), actual); if (expected != actual) { goto error; } } else if (cmd == "generate_keys") { crypto::PublicKey expected1, actual1; crypto::SecretKey expected2, actual2; get(input, expected1, expected2); generate_keys(actual1, actual2); if (expected1 != actual1 || expected2 != actual2) { goto error; } } else if (cmd == "check_key") { crypto::PublicKey key; bool expected, actual; get(input, key, expected); actual = check_key(key); if (expected != actual) { goto error; } } else if (cmd == "secret_key_to_public_key") { crypto::SecretKey sec; bool expected1, actual1; crypto::PublicKey expected2, actual2; get(input, sec, expected1); if (expected1) { get(input, expected2); } actual1 = secret_key_to_public_key(sec, actual2); if (expected1 != actual1 || (expected1 && expected2 != actual2)) { goto error; } } else if (cmd == "generate_key_derivation") { crypto::PublicKey key1; crypto::SecretKey key2; bool expected1, actual1; crypto::KeyDerivation expected2, actual2; get(input, key1, key2, expected1); if (expected1) { get(input, expected2); } actual1 = generate_key_derivation(key1, key2, actual2); if (expected1 != actual1 || (expected1 && expected2 != actual2)) { goto error; } } else if (cmd == "derive_public_key") { crypto::KeyDerivation derivation; size_t output_index; crypto::PublicKey base; bool expected1, actual1; crypto::PublicKey expected2, actual2; get(input, derivation, output_index, base, expected1); if (expected1) { get(input, expected2); } actual1 = derive_public_key(derivation, output_index, base, actual2); if (expected1 != actual1 || (expected1 && expected2 != actual2)) { goto error; } } else if (cmd == "derive_secret_key") { crypto::KeyDerivation derivation; size_t output_index; crypto::SecretKey base; crypto::SecretKey expected, actual; get(input, derivation, output_index, base, expected); derive_secret_key(derivation, output_index, base, actual); if (expected != actual) { goto error; } } else if (cmd == "underive_public_key") { crypto::KeyDerivation derivation; size_t output_index; crypto::PublicKey derived_key; bool expected1, actual1; crypto::PublicKey expected2, actual2; get(input, derivation, output_index, derived_key, expected1); if (expected1) { get(input, expected2); } actual1 = underive_public_key(derivation, output_index, derived_key, actual2); if (expected1 != actual1 || (expected1 && expected2 != actual2)) { goto error; } } else if (cmd == "generate_signature") { chash prefix_hash; crypto::PublicKey pub; crypto::SecretKey sec; crypto::Signature expected, actual; get(input, prefix_hash, pub, sec, expected); generate_signature(prefix_hash, pub, sec, actual); if (expected != actual) { goto error; } } else if (cmd == "check_signature") { chash prefix_hash; crypto::PublicKey pub; crypto::Signature sig; bool expected, actual; get(input, prefix_hash, pub, sig, expected); actual = check_signature(prefix_hash, pub, sig); if (expected != actual) { goto error; } } else if (cmd == "hash_to_point") { chash h; crypto::EllipticCurvePoint expected, actual; get(input, h, expected); hash_to_point(h, actual); if (expected != actual) { goto error; } } else if (cmd == "hash_to_ec") { crypto::PublicKey key; crypto::EllipticCurvePoint expected, actual; get(input, key, expected); hash_to_ec(key, actual); if (expected != actual) { goto error; } } else if (cmd == "generate_key_image") { crypto::PublicKey pub; crypto::SecretKey sec; crypto::KeyImage expected, actual; get(input, pub, sec, expected); generate_key_image(pub, sec, actual); if (expected != actual) { goto error; } } else if (cmd == "generate_ring_signature") { chash prefix_hash; crypto::KeyImage image; vector<crypto::PublicKey> vpubs; vector<const crypto::PublicKey *> pubs; size_t pubs_count; crypto::SecretKey sec; size_t sec_index; vector<crypto::Signature> expected, actual; size_t i; get(input, prefix_hash, image, pubs_count); vpubs.resize(pubs_count); pubs.resize(pubs_count); for (i = 0; i < pubs_count; i++) { get(input, vpubs[i]); pubs[i] = &vpubs[i]; } get(input, sec, sec_index); expected.resize(pubs_count); getvar(input, pubs_count * sizeof(crypto::Signature), expected.data()); actual.resize(pubs_count); generate_ring_signature(prefix_hash, image, pubs.data(), pubs_count, sec, sec_index, actual.data()); if (expected != actual) { goto error; } } else if (cmd == "check_ring_signature") { chash prefix_hash; crypto::KeyImage image; vector<crypto::PublicKey> vpubs; vector<const crypto::PublicKey *> pubs; size_t pubs_count; vector<crypto::Signature> sigs; bool expected, actual; size_t i; get(input, prefix_hash, image, pubs_count); vpubs.resize(pubs_count); pubs.resize(pubs_count); for (i = 0; i < pubs_count; i++) { get(input, vpubs[i]); pubs[i] = &vpubs[i]; } sigs.resize(pubs_count); getvar(input, pubs_count * sizeof(crypto::Signature), sigs.data()); get(input, expected); actual = check_ring_signature(prefix_hash, image, pubs.data(), pubs_count, sigs.data()); if (expected != actual) { goto error; } } else { throw ios_base::failure("Unknown function: " + cmd); } continue; error: cerr << "Wrong result on test " << test << endl; error = true; } return error ? 1 : 0; }
int solution(vector<int> &A, vector<int> &B, vector<int> &C) { // write your code in C++14 (g++ 6.2.0) int N = A.size(); int M = C.size(); int beg = 1; int end = M; // M=5, N=4 int answer = -1; while (beg <= end){ int mid = (beg + end) / 2; // 2 vector<int> prefix_sum(2*M+1, 0); for (int i=0; i < mid; i++) // i=0~1 prefix_sum[C[i]]++; // prefix_sum[C[0]]: prefix_sum[4]++ // prefix_sum[C[1]]: prefix_sum[6]++ // prefix_sum: [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0] for (int i=1; i <= 2 * M; i++) prefix_sum[i] += prefix_sum[i - 1]; // prefix_sum: [0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 2] int failed=0; for (int i=0; i < N; i++) if (prefix_sum[B[i]] == prefix_sum[A[i] - 1]) // means between idx B[i] and idx A[i], there's no new nail failed = 1; if (failed){ beg = mid + 1; } else { end = mid - 1; answer = mid; } } return answer; } //// N^2 solution // you can use includes, for example: // #include <algorithm> // you can write to stdout for debugging purposes, e.g. // cout << "this is a debug message" << endl; int solution(vector<int> &A, vector<int> &B, vector<int> &C) { // write your code in C++14 (g++ 6.2.0) int N = A.size(); int M = C.size(); vector<bool> nailed(N,0); for (int i=0; i<M; i++) { for (int j=0; j<N; j++){ if (C[i]>=A[j] && C[i]<=B[j]) nailed[j]=1; } int cnt = 0; for (bool n:nailed){ if(n) cnt++; else break; } if (cnt==L) return (i+1); } return -1; } // you can use includes, for example: // #include <algorithm> // you can write to stdout for debugging purposes, e.g. // cout << "this is a debug message" << endl; #include <algorithm> #include <numeric> //bool zz(size_t i1, size_t i2, vector<int> &C) {return C[i1] < C[i2];} int getMinIndex(int startPlank, int endPlank, vector<int> &C, vector<size_t> &idx,int preIndex) { int min = 0; int max = C.size() - 1; int minIndex = -1; while (min <= max) { int mid = (min + max) / 2; if (C[mid] < startPlank) min = mid + 1; else if (C[mid] > endPlank) max = mid - 1; else { max = mid - 1; minIndex = mid; } } if (minIndex == -1) return -1; int minIndexOrigin = idx[minIndex]; //find the smallest original position of nail that can nail the plank for (int i = minIndex; i < C.size(); i++) { if (C[i] > endPlank) break; if (minIndexOrigin>idx[i]) minIndexOrigin = idx[i]; // we need the maximal index of nails to nail every plank, so the // smaller index can be omitted if (minIndexOrigin <= preIndex) return preIndex; } return minIndexOrigin; } int solution(vector<int> &A, vector<int> &B, vector<int> &C) { // write your code in C++14 (g++ 6.2.0) int N = A.size(); int M = C.size(); // sorting C vector<size_t> idx(C.size()); iota(idx.begin(), idx.end(), 0); // create a [0,1,...,C.size()-1] array // sort indexes based on comparing values in C sort(idx.begin(), idx.end(), [&C](size_t i1, size_t i2) {return C[i1] < C[i2];}); sort(C.begin(), C.end()); //for(auto i:idx) cout<<i<<endl; int result = 0; for (int i = 0; i < N; i++) { //find the earlist position that can nail each plank, and the max value for all planks is the result result = getMinIndex(A[i], B[i], C, idx, result); if (result == -1) return -1; } return result + 1; }
// Byte order, big-endian, little-endian #include <cstdint> #include <iomanip> #include <iostream> #include <vector> using ::std::cout; using ::std::endl; using ::std::hex; union Int_bytes { int32_t value; uint8_t bytes[sizeof(int32_t)]; }; int main() { const int32_t test_value{0x01020304}; // #1 Int_bytes a{test_value}; cout << hex; cout << "a.value: " << a.value << endl; cout << "a.bytes[0]: " << static_cast<int32_t>(a.bytes[0]) << endl; // #2 int32_t byte1 = test_value & 0x000000ff; int32_t byte2 = (test_value & 0x0000ff00) >> 8; int32_t byte3 = (test_value & 0x00ff0000) >> 16; int32_t byte4 = (test_value & 0xff000000) >> 24; cout << "byte1: " << static_cast<int32_t>(byte1) << endl; cout << "byte2: " << static_cast<int32_t>(byte2) << endl; cout << "byte3: " << static_cast<int32_t>(byte3) << endl; cout << "byte4: " << static_cast<int32_t>(byte4) << endl; // #3 std::vector<uint8_t> bytes; bytes.push_back(test_value >> 24); bytes.push_back(test_value >> 16); bytes.push_back(test_value >> 8); bytes.push_back(test_value); for (const auto& byte : bytes) { cout << static_cast<int32_t>(byte) << " "; } cout << endl; }
#ifndef UISHADER_H #define UISHADER_H #include "abstractshader.h" class UiShader : public AbstractShader { public: UiShader(const std::string &vertexFile = "ui.vert", const std::string &fragmentFile = "ui.frag"); void loadProjectionMatrix(const Matrix4 &matrix); protected: void getUniforms(); private: GLuint _locationProjectionMatrix; }; #endif // UISHADER_H
#ifndef __UTILS_H__ #define __UTILS_H__ #include "types.h" #include <string> extern "C" void bindTriangles(float* dev_triangle_p, unsigned int num_triangles); extern "C" void RayTraceImage(unsigned int*, int, int, int, float3, float3, float3, float3, float3, float3, float3, float3); void loadObj(const std::string filename, TriangleMesh &mesh, int scale); #endif
#include <math.h> #include "pageLib.h" int BYTE_OFFSET = 1 + sizeof(int); /** * Initializes a page using the given slot size */ void init_fixed_len_page(Page *page, int page_size, int slot_size) { page->data = (void *)malloc(page_size); page->page_size = page_size; page->slot_size = slot_size; int slot_bytes = sizeof(int) + (int)ceil((1.0)*page_size/slot_size/8); int slot_available = (page_size)/(slot_size) - (int)ceil(1.0*slot_bytes/slot_size); int *slot_loc = (int *)page->data + page_size - BYTE_OFFSET; *slot_loc = slot_available; } /** * Calculates the maximal number of records that fit in a page */ int fixed_len_page_capacity(Page *page) {; int *slot_loc = (int *)page->data + page->page_size - BYTE_OFFSET; if (!(*slot_loc)) { int slot_bytes = sizeof(int) + (int)ceil((1.0)*page->page_size/page->slot_size/8); int slot_available = (page->page_size)/(page->slot_size) - (int)ceil(1.0*slot_bytes/page->slot_size); int *slot_loc = (int *)page->data + page->page_size - BYTE_OFFSET; *slot_loc = slot_available; } return *slot_loc; } /** * Check if a slot is occupied */ bool hasData(Page* page, int slot) { int slot_byte = slot / sizeof(char *); int slot_pos = slot % sizeof(char *); char *slot_ptr = (char *)page->data+page->page_size-slot_byte-BYTE_OFFSET; if (slot <= fixed_len_page_capacity(page)) { //read slot if it has something there if ((*slot_ptr & (1<<slot_pos))) { return true; } } return false; }; /** * Calculate the free space (number of free slots) in the page */ int fixed_len_page_freeslots(Page *page) { int page_count = 0; bool res; for (int i = 0; i < fixed_len_page_capacity(page); i++) { if (!(hasData(page, i))) { page_count++; } } return page_count; } /** * Write a record into a given slot. */ void write_fixed_len_page(Page *page, int slot, Record *r) { int slot_byte = slot / sizeof(char *); int slot_pos = slot % sizeof(char *); char *slot_ptr = (char *)page->data+page->page_size-slot_byte-BYTE_OFFSET; if (slot <= fixed_len_page_capacity(page)) { fixed_len_write(r, (void *)((char *)page->data + slot*page->slot_size)); *slot_ptr = *slot_ptr | (1<<slot_pos); } }; /** * Write a record into a given slot. */ bool write_fixed_len_page_strict(Page *page, int slot, Record *r) { int slot_byte = slot / sizeof(char *); int slot_pos = slot % sizeof(char *); char *slot_ptr = (char *)page->data+page->page_size-slot_byte-BYTE_OFFSET; if (slot <= fixed_len_page_capacity(page)) { if (!(*slot_ptr & (1<<slot_pos))) { fixed_len_write(r, (void *)((char *)page->data + slot*page->slot_size)); *slot_ptr = *slot_ptr | (1<<slot_pos); return true; } } return false; }; /** * Read a record from the page from a given slot. */ void read_fixed_len_page(Page *page, int slot, Record *r) { int slot_byte = slot / sizeof(char *); int slot_pos = slot % sizeof(char *); char *slot_ptr = (char *)page->data+page->page_size-slot_byte-BYTE_OFFSET; if (slot <= fixed_len_page_capacity(page)) { //read slot if it has something there if ((*slot_ptr & (1<<slot_pos))) { fixed_len_read((void *)((char *)page->data + slot*page->slot_size), page->slot_size, r); } } }; /** * Add a record to the page * Returns: * record slot offset if successful, * -1 if unsuccessful (page full) */ int add_fixed_len_page(Page *page, Record *r) { //find first free slot int slot_num=-1; bool res; for (int i = 0; i < fixed_len_page_capacity(page); i++) { res = write_fixed_len_page_strict(page, i, r); if (res) { slot_num = i; break; } } return slot_num; } /** * Zeros a slot entry */ void remove_entry(Page* page, int slot) { int slot_byte = slot / sizeof(char *); int slot_pos = slot % sizeof(char *); char *slot_ptr = (char *)page->data+page->page_size-slot_byte-BYTE_OFFSET; char mask=0; //remove entry and zero out data if (slot <= fixed_len_page_capacity(page)) { mask = (255<<slot_pos+1 | 255>>8-slot_pos); *slot_ptr = *slot_ptr & mask; memset ( (char *)page->data + slot*page->slot_size, 0, page->slot_size); } }; /* *Zero out data in the entire page */ void wipe_data(Page* page) { memset ( (char *)page->data, 0, page->page_size-sizeof(int)); };
#ifndef ORDERS_H #define ORDERS_H #include "Order.h" class Orders { public: enum Priority { ATTACK, ECONOMY }; private: std::vector<Order> attack_orders; std::vector<Order> build_orders; Priority priority; public: Orders(); ~Orders(); const std::vector<Order> GetAttackOrders() { return attack_orders; } const std::vector<Order> GetBuildOrders() const { return build_orders; } /* Add an order to the orders list at the specified position. If posistion is invalid, adds the order at the end. */ void AddAttackOrder(Order o, int num = -1); /* Add an order to the orders list at the specified position. If posistion is invalid, adds the order at the end. */ void AddBuildOrder(Order o, int num = -1); }; #endif
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "10976" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif int number; while(~scanf("%d",&number)){ int x[number+1],y[number+1]; x[0]=0; y[0]=number; int check=1,i,ans=0; for(i=1;i<number+1;i=i+1){ y[i]=y[i-1]+1; x[i]=y[i]*number; if(x[i]%check==0){ x[i]=x[i]/check; ans++; } else{ x[i]=0; } check++; } printf("%d\n",ans ); for(i=0;i<number+1;i=i+1){ if(x[i]!=0){ printf("1/%d = 1/%d + 1/%d\n",number,x[i],y[i] ); } } } return 0; }
/**************************************************************************** Copyright (C) 2002-2014 Gilles Debunne. All rights reserved. This file is part of the QGLViewer library version 2.6.3. http://www.libqglviewer.com - contact@libqglviewer.com This file may be used under the terms of the GNU General Public License versions 2.0 or 3.0 as published by the Free Software Foundation and appearing in the LICENSE file included in the packaging of this file. In addition, as a special exception, Gilles Debunne gives you certain additional rights, described in the file GPL_EXCEPTION in this package. libQGLViewer uses dual licensing. Commercial/proprietary software must purchase a libQGLViewer Commercial License. This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. *****************************************************************************/ #include "domUtils.h" #include "camera.h" #include "qglviewer.h" #include "manipulatedCameraFrame.h" using namespace std; using namespace qglviewer; /*! Default constructor. sceneCenter() is set to (0,0,0) and sceneRadius() is set to 1.0. type() is Camera::PERSPECTIVE, with a \c M_PI/4 fieldOfView(). See IODistance(), physicalDistanceToScreen(), physicalScreenWidth() and focusDistance() documentations for default stereo parameter values. */ Camera::Camera() : frame_(NULL), fieldOfView_(M_PI/4.0), modelViewMatrixIsUpToDate_(false), projectionMatrixIsUpToDate_(false) { // #CONNECTION# Camera copy constructor interpolationKfi_ = new KeyFrameInterpolator; // Requires the interpolationKfi_ setFrame(new ManipulatedCameraFrame()); // #CONNECTION# All these default values identical in initFromDOMElement. // Requires fieldOfView() to define focusDistance() setSceneRadius(1.0); // Initial value (only scaled after this) orthoCoef_ = tan(fieldOfView()/2.0); // Also defines the pivotPoint(), which changes orthoCoef_. Requires a frame(). setSceneCenter(Vec(0.0, 0.0, 0.0)); // Requires fieldOfView() when called with ORTHOGRAPHIC. Attention to projectionMatrix_ below. setType(PERSPECTIVE); // #CONNECTION# initFromDOMElement default values setZNearCoefficient(0.005); setZClippingCoefficient(sqrt(3.0)); // Dummy values setScreenWidthAndHeight(600, 400); // Stereo parameters setIODistance(0.062); setPhysicalScreenWidth(0.5); // focusDistance is set from setFieldOfView() // #CONNECTION# Camera copy constructor for (unsigned short j=0; j<16; ++j) { modelViewMatrix_[j] = ((j%5 == 0) ? 1.0 : 0.0); // #CONNECTION# computeProjectionMatrix() is lazy and assumes 0.0 almost everywhere. projectionMatrix_[j] = 0.0; } computeProjectionMatrix(); } /*! Virtual destructor. The frame() is deleted, but the different keyFrameInterpolator() are \e not deleted (in case they are shared). */ Camera::~Camera() { delete frame_; delete interpolationKfi_; } /*! Copy constructor. Performs a deep copy using operator=(). */ Camera::Camera(const Camera& camera) : QObject(), frame_(NULL) { // #CONNECTION# Camera constructor interpolationKfi_ = new KeyFrameInterpolator; // Requires the interpolationKfi_ setFrame(new ManipulatedCameraFrame(*camera.frame())); for (unsigned short j=0; j<16; ++j) { modelViewMatrix_[j] = ((j%5 == 0) ? 1.0 : 0.0); // #CONNECTION# computeProjectionMatrix() is lazy and assumes 0.0 almost everywhere. projectionMatrix_[j] = 0.0; } (*this)=camera; } /*! Equal operator. All the parameters of \p camera are copied. The frame() pointer is not modified, but its Frame::position() and Frame::orientation() are set to those of \p camera. \attention The Camera screenWidth() and screenHeight() are set to those of \p camera. If your Camera is associated with a QGLViewer, you should update these value after the call to this method: \code *(camera()) = otherCamera; camera()->setScreenWidthAndHeight(width(), height()); \endcode The same applies to sceneCenter() and sceneRadius(), if needed. */ Camera& Camera::operator=(const Camera& camera) { setScreenWidthAndHeight(camera.screenWidth(), camera.screenHeight()); setFieldOfView(camera.fieldOfView()); setSceneRadius(camera.sceneRadius()); setSceneCenter(camera.sceneCenter()); setZNearCoefficient(camera.zNearCoefficient()); setZClippingCoefficient(camera.zClippingCoefficient()); setType(camera.type()); // Stereo parameters setIODistance(camera.IODistance()); setFocusDistance(camera.focusDistance()); setPhysicalScreenWidth(camera.physicalScreenWidth()); orthoCoef_ = camera.orthoCoef_; projectionMatrixIsUpToDate_ = false; // frame_ and interpolationKfi_ pointers are not shared. frame_->setReferenceFrame(NULL); frame_->setPosition(camera.position()); frame_->setOrientation(camera.orientation()); interpolationKfi_->resetInterpolation(); kfi_ = camera.kfi_; computeProjectionMatrix(); computeModelViewMatrix(); return *this; } /*! Sets Camera screenWidth() and screenHeight() (expressed in pixels). You should not call this method when the Camera is associated with a QGLViewer, since the latter automatically updates these values when it is resized (hence overwritting your values). Non-positive dimension are silently replaced by a 1 pixel value to ensure frustrum coherence. If your Camera is used without a QGLViewer (offscreen rendering, shadow maps), use setAspectRatio() instead to define the projection matrix. */ void Camera::setScreenWidthAndHeight(int width, int height) { // Prevent negative and zero dimensions that would cause divisions by zero. screenWidth_ = width > 0 ? width : 1; screenHeight_ = height > 0 ? height : 1; projectionMatrixIsUpToDate_ = false; } /*! Returns the near clipping plane distance used by the Camera projection matrix. The clipping planes' positions depend on the sceneRadius() and sceneCenter() rather than being fixed small-enough and large-enough values. A good scene dimension approximation will hence result in an optimal precision of the z-buffer. The near clipping plane is positioned at a distance equal to zClippingCoefficient() * sceneRadius() in front of the sceneCenter(): \code zNear = distanceToSceneCenter() - zClippingCoefficient()*sceneRadius(); \endcode In order to prevent negative or too small zNear() values (which would degrade the z precision), zNearCoefficient() is used when the Camera is inside the sceneRadius() sphere: \code const qreal zMin = zNearCoefficient() * zClippingCoefficient() * sceneRadius(); if (zNear < zMin) zNear = zMin; // With an ORTHOGRAPHIC type, the value is simply clamped to 0.0 \endcode See also the zFar(), zClippingCoefficient() and zNearCoefficient() documentations. If you need a completely different zNear computation, overload the zNear() and zFar() methods in a new class that publicly inherits from Camera and use QGLViewer::setCamera(): \code class myCamera :: public qglviewer::Camera { virtual qreal Camera::zNear() const { return 0.001; }; virtual qreal Camera::zFar() const { return 100.0; }; } \endcode See the <a href="../examples/standardCamera.html">standardCamera example</a> for an application. \attention The value is always positive although the clipping plane is positioned at a negative z value in the Camera coordinate system. This follows the \c gluPerspective standard. */ qreal Camera::zNear() const { const qreal zNearScene = zClippingCoefficient() * sceneRadius(); qreal z = distanceToSceneCenter() - zNearScene; // Prevents negative or null zNear values. const qreal zMin = zNearCoefficient() * zNearScene; if (z < zMin) switch (type()) { case Camera::PERSPECTIVE : z = zMin; break; case Camera::ORTHOGRAPHIC : z = 0.0; break; } return z; } /*! Returns the far clipping plane distance used by the Camera projection matrix. The far clipping plane is positioned at a distance equal to zClippingCoefficient() * sceneRadius() behind the sceneCenter(): \code zFar = distanceToSceneCenter() + zClippingCoefficient()*sceneRadius(); \endcode See the zNear() documentation for details. */ qreal Camera::zFar() const { return distanceToSceneCenter() + zClippingCoefficient() * sceneRadius(); } /*! Sets the vertical fieldOfView() of the Camera (in radians). Note that focusDistance() is set to sceneRadius() / tan(fieldOfView()/2) by this method. */ void Camera::setFieldOfView(qreal fov) { fieldOfView_ = fov; setFocusDistance(sceneRadius() / tan(fov/2.0)); projectionMatrixIsUpToDate_ = false; } /*! Defines the Camera type(). Changing the camera Type alters the viewport and the objects' sizes can be changed. This method garantees that the two frustum match in a plane normal to viewDirection(), passing through the pivotPoint(). Prefix the type with \c Camera if needed, as in: \code camera()->setType(Camera::ORTHOGRAPHIC); // or even qglviewer::Camera::ORTHOGRAPHIC if you do not use namespace \endcode */ void Camera::setType(Type type) { // make ORTHOGRAPHIC frustum fit PERSPECTIVE (at least in plane normal to viewDirection(), passing // through RAP). Done only when CHANGING type since orthoCoef_ may have been changed with a // setPivotPoint() in the meantime. if ( (type == Camera::ORTHOGRAPHIC) && (type_ == Camera::PERSPECTIVE) ) orthoCoef_ = tan(fieldOfView()/2.0); type_ = type; projectionMatrixIsUpToDate_ = false; } /*! Sets the Camera frame(). If you want to move the Camera, use setPosition() and setOrientation() or one of the Camera positioning methods (lookAt(), fitSphere(), showEntireScene()...) instead. If you want to save the Camera position(), there's no need to call this method either. Use addKeyFrameToPath() and playPath() instead. This method is actually mainly useful if you derive the ManipulatedCameraFrame class and want to use an instance of your new class to move the Camera. A \c NULL \p mcf pointer will silently be ignored. The calling method is responsible for deleting the previous frame() pointer if needed in order to prevent memory leaks. */ void Camera::setFrame(ManipulatedCameraFrame* const mcf) { if (!mcf) return; if (frame_) { disconnect(frame_, SIGNAL(modified()), this, SLOT(onFrameModified())); } frame_ = mcf; interpolationKfi_->setFrame(frame()); connect(frame_, SIGNAL(modified()), this, SLOT(onFrameModified())); onFrameModified(); } /*! Returns the distance from the Camera center to sceneCenter(), projected along the Camera Z axis. Used by zNear() and zFar() to optimize the Z range. */ qreal Camera::distanceToSceneCenter() const { return fabs((frame()->coordinatesOf(sceneCenter())).z); } /*! Returns the \p halfWidth and \p halfHeight of the Camera orthographic frustum. These values are only valid and used when the Camera is of type() Camera::ORTHOGRAPHIC. They are expressed in OpenGL units and are used by loadProjectionMatrix() to define the projection matrix using: \code glOrtho( -halfWidth, halfWidth, -halfHeight, halfHeight, zNear(), zFar() ) \endcode These values are proportional to the Camera (z projected) distance to the pivotPoint(). When zooming on the object, the Camera is translated forward \e and its frustum is narrowed, making the object appear bigger on screen, as intuitively expected. Overload this method to change this behavior if desired, as is done in the <a href="../examples/standardCamera.html">standardCamera example</a>. */ void Camera::getOrthoWidthHeight(GLdouble& halfWidth, GLdouble& halfHeight) const { const qreal dist = orthoCoef_ * fabs(cameraCoordinatesOf(pivotPoint()).z); //#CONNECTION# fitScreenRegion halfWidth = dist * ((aspectRatio() < 1.0) ? 1.0 : aspectRatio()); halfHeight = dist * ((aspectRatio() < 1.0) ? 1.0/aspectRatio() : 1.0); } /*! Computes the projection matrix associated with the Camera. If type() is Camera::PERSPECTIVE, defines a \c GL_PROJECTION matrix similar to what would \c gluPerspective() do using the fieldOfView(), window aspectRatio(), zNear() and zFar() parameters. If type() is Camera::ORTHOGRAPHIC, the projection matrix is as what \c glOrtho() would do. Frustum's width and height are set using getOrthoWidthHeight(). Both types use zNear() and zFar() to place clipping planes. These values are determined from sceneRadius() and sceneCenter() so that they best fit the scene size. Use getProjectionMatrix() to retrieve this matrix. Overload loadProjectionMatrix() if you want your Camera to use an exotic projection matrix. \note You must call this method if your Camera is not associated with a QGLViewer and is used for offscreen computations (using (un)projectedCoordinatesOf() for instance). loadProjectionMatrix() does it otherwise. */ void Camera::computeProjectionMatrix() const { if (projectionMatrixIsUpToDate_) return; const qreal ZNear = zNear(); const qreal ZFar = zFar(); switch (type()) { case Camera::PERSPECTIVE: { // #CONNECTION# all non null coefficients were set to 0.0 in constructor. const qreal f = 1.0/tan(fieldOfView()/2.0); projectionMatrix_[0] = f/aspectRatio(); projectionMatrix_[5] = f; projectionMatrix_[10] = (ZNear + ZFar) / (ZNear - ZFar); projectionMatrix_[11] = -1.0; projectionMatrix_[14] = 2.0 * ZNear * ZFar / (ZNear - ZFar); projectionMatrix_[15] = 0.0; // same as gluPerspective( 180.0*fieldOfView()/M_PI, aspectRatio(), zNear(), zFar() ); break; } case Camera::ORTHOGRAPHIC: { GLdouble w, h; getOrthoWidthHeight(w,h); projectionMatrix_[0] = 1.0/w; projectionMatrix_[5] = 1.0/h; projectionMatrix_[10] = -2.0/(ZFar - ZNear); projectionMatrix_[11] = 0.0; projectionMatrix_[14] = -(ZFar + ZNear)/(ZFar - ZNear); projectionMatrix_[15] = 1.0; // same as glOrtho( -w, w, -h, h, zNear(), zFar() ); break; } } projectionMatrixIsUpToDate_ = true; } /*! Computes the modelView matrix associated with the Camera's position() and orientation(). This matrix converts from the world coordinates system to the Camera coordinates system, so that coordinates can then be projected on screen using the projection matrix (see computeProjectionMatrix()). Use getModelViewMatrix() to retrieve this matrix. \note You must call this method if your Camera is not associated with a QGLViewer and is used for offscreen computations (using (un)projectedCoordinatesOf() for instance). loadModelViewMatrix() does it otherwise. */ void Camera::computeModelViewMatrix() const { if (modelViewMatrixIsUpToDate_) return; const Quaternion q = frame()->orientation(); const qreal q00 = 2.0 * q[0] * q[0]; const qreal q11 = 2.0 * q[1] * q[1]; const qreal q22 = 2.0 * q[2] * q[2]; const qreal q01 = 2.0 * q[0] * q[1]; const qreal q02 = 2.0 * q[0] * q[2]; const qreal q03 = 2.0 * q[0] * q[3]; const qreal q12 = 2.0 * q[1] * q[2]; const qreal q13 = 2.0 * q[1] * q[3]; const qreal q23 = 2.0 * q[2] * q[3]; modelViewMatrix_[0] = 1.0 - q11 - q22; modelViewMatrix_[1] = q01 - q23; modelViewMatrix_[2] = q02 + q13; modelViewMatrix_[3] = 0.0; modelViewMatrix_[4] = q01 + q23; modelViewMatrix_[5] = 1.0 - q22 - q00; modelViewMatrix_[6] = q12 - q03; modelViewMatrix_[7] = 0.0; modelViewMatrix_[8] = q02 - q13; modelViewMatrix_[9] = q12 + q03; modelViewMatrix_[10] = 1.0 - q11 - q00; modelViewMatrix_[11] = 0.0; const Vec t = q.inverseRotate(frame()->position()); modelViewMatrix_[12] = -t.x; modelViewMatrix_[13] = -t.y; modelViewMatrix_[14] = -t.z; modelViewMatrix_[15] = 1.0; modelViewMatrixIsUpToDate_ = true; } /*! Loads the OpenGL \c GL_PROJECTION matrix with the Camera projection matrix. The Camera projection matrix is computed using computeProjectionMatrix(). When \p reset is \c true (default), the method clears the previous projection matrix by calling \c glLoadIdentity before setting the matrix. Setting \p reset to \c false is useful for \c GL_SELECT mode, to combine the pushed matrix with a picking matrix. See QGLViewer::beginSelection() for details. This method is used by QGLViewer::preDraw() (called before user's QGLViewer::draw() method) to set the \c GL_PROJECTION matrix according to the viewer's QGLViewer::camera() settings. Use getProjectionMatrix() to retrieve this matrix. Overload this method if you want your Camera to use an exotic projection matrix. See also loadModelViewMatrix(). \attention \c glMatrixMode is set to \c GL_PROJECTION. \attention If you use several OpenGL contexts and bypass the Qt main refresh loop, you should call QGLWidget::makeCurrent() before this method in order to activate the right OpenGL context. */ void Camera::loadProjectionMatrix(bool reset) const { // WARNING: makeCurrent must be called by every calling method glMatrixMode(GL_PROJECTION); if (reset) glLoadIdentity(); computeProjectionMatrix(); glMultMatrixd(projectionMatrix_); } /*! Loads the OpenGL \c GL_MODELVIEW matrix with the modelView matrix corresponding to the Camera. Calls computeModelViewMatrix() to compute the Camera's modelView matrix. This method is used by QGLViewer::preDraw() (called before user's QGLViewer::draw() method) to set the \c GL_MODELVIEW matrix according to the viewer's QGLViewer::camera() position() and orientation(). As a result, the vertices used in QGLViewer::draw() can be defined in the so called world coordinate system. They are multiplied by this matrix to get converted to the Camera coordinate system, before getting projected using the \c GL_PROJECTION matrix (see loadProjectionMatrix()). When \p reset is \c true (default), the method loads (overwrites) the \c GL_MODELVIEW matrix. Setting \p reset to \c false simply calls \c glMultMatrixd (might be useful for some applications). Overload this method or simply call glLoadMatrixd() at the beginning of QGLViewer::draw() if you want your Camera to use an exotic modelView matrix. See also loadProjectionMatrix(). getModelViewMatrix() returns the 4x4 modelView matrix. \attention glMatrixMode is set to \c GL_MODELVIEW \attention If you use several OpenGL contexts and bypass the Qt main refresh loop, you should call QGLWidget::makeCurrent() before this method in order to activate the right OpenGL context. */ void Camera::loadModelViewMatrix(bool reset) const { // WARNING: makeCurrent must be called by every calling method glMatrixMode(GL_MODELVIEW); computeModelViewMatrix(); if (reset) glLoadMatrixd(modelViewMatrix_); else glMultMatrixd(modelViewMatrix_); } /*! Same as loadProjectionMatrix() but for a stereo setup. Only the Camera::PERSPECTIVE type() is supported for stereo mode. See QGLViewer::setStereoDisplay(). Uses focusDistance(), IODistance(), and physicalScreenWidth() to compute cameras offset and asymmetric frustums. When \p leftBuffer is \c true, computes the projection matrix associated to the left eye (right eye otherwise). See also loadModelViewMatrixStereo(). See the <a href="../examples/stereoViewer.html">stereoViewer</a> and the <a href="../examples/contribs.html#anaglyph">anaglyph</a> examples for an illustration. To retrieve this matrix, use a code like: \code glMatrixMode(GL_PROJECTION); glPushMatrix(); loadProjectionMatrixStereo(left_or_right); glGetDoublev(GL_PROJECTION_MATRIX, m); glPopMatrix(); \endcode Note that getProjectionMatrix() always returns the mono-vision matrix. \attention glMatrixMode is set to \c GL_PROJECTION. */ void Camera::loadProjectionMatrixStereo(bool leftBuffer) const { qreal left, right, bottom, top; qreal screenHalfWidth, halfWidth, side, shift, delta; glMatrixMode(GL_PROJECTION); glLoadIdentity(); switch (type()) { case Camera::PERSPECTIVE: // compute half width of screen, // corresponding to zero parallax plane to deduce decay of cameras screenHalfWidth = focusDistance() * tan(horizontalFieldOfView() / 2.0); shift = screenHalfWidth * IODistance() / physicalScreenWidth(); // should be * current y / y total // to take into account that the window doesn't cover the entire screen // compute half width of "view" at znear and the delta corresponding to // the shifted camera to deduce what to set for asymmetric frustums halfWidth = zNear() * tan(horizontalFieldOfView() / 2.0); delta = shift * zNear() / focusDistance(); side = leftBuffer ? -1.0 : 1.0; left = -halfWidth + side * delta; right = halfWidth + side * delta; top = halfWidth / aspectRatio(); bottom = -top; glFrustum(left, right, bottom, top, zNear(), zFar() ); break; case Camera::ORTHOGRAPHIC: qWarning("Camera::setProjectionMatrixStereo: Stereo not available with Ortho mode"); break; } } /*! Same as loadModelViewMatrix() but for a stereo setup. Only the Camera::PERSPECTIVE type() is supported for stereo mode. See QGLViewer::setStereoDisplay(). The modelView matrix is almost identical to the mono-vision one. It is simply translated along its horizontal axis by a value that depends on stereo parameters (see focusDistance(), IODistance(), and physicalScreenWidth()). When \p leftBuffer is \c true, computes the modelView matrix associated to the left eye (right eye otherwise). loadProjectionMatrixStereo() explains how to retrieve to resulting matrix. See the <a href="../examples/stereoViewer.html">stereoViewer</a> and the <a href="../examples/contribs.html#anaglyph">anaglyph</a> examples for an illustration. \attention glMatrixMode is set to \c GL_MODELVIEW. */ void Camera::loadModelViewMatrixStereo(bool leftBuffer) const { // WARNING: makeCurrent must be called by every calling method glMatrixMode(GL_MODELVIEW); qreal halfWidth = focusDistance() * tan(horizontalFieldOfView() / 2.0); qreal shift = halfWidth * IODistance() / physicalScreenWidth(); // * current window width / full screen width computeModelViewMatrix(); if (leftBuffer) modelViewMatrix_[12] -= shift; else modelViewMatrix_[12] += shift; glLoadMatrixd(modelViewMatrix_); } /*! Fills \p m with the Camera projection matrix values. Based on computeProjectionMatrix() to make sure the Camera projection matrix is up to date. This matrix only reflects the Camera's internal parameters and it may differ from the \c GL_PROJECTION matrix retrieved using \c glGetDoublev(GL_PROJECTION_MATRIX, m). It actually represents the state of the \c GL_PROJECTION after QGLViewer::preDraw(), at the beginning of QGLViewer::draw(). If you modified the \c GL_PROJECTION matrix (for instance using QGLViewer::startScreenCoordinatesSystem()), the two results differ. The result is an OpenGL 4x4 matrix, which is given in \e column-major order (see \c glMultMatrix man page for details). See also getModelViewMatrix() and setFromProjectionMatrix(). */ void Camera::getProjectionMatrix(GLdouble m[16]) const { computeProjectionMatrix(); for (unsigned short i=0; i<16; ++i) m[i] = projectionMatrix_[i]; } /*! Overloaded getProjectionMatrix(GLdouble m[16]) method using a \c GLfloat array instead. */ void Camera::getProjectionMatrix(GLfloat m[16]) const { static GLdouble mat[16]; getProjectionMatrix(mat); for (unsigned short i=0; i<16; ++i) m[i] = float(mat[i]); } /*! Fills \p m with the Camera modelView matrix values. First calls computeModelViewMatrix() to define the Camera modelView matrix. Note that this matrix may \e not be the one you would get from a \c glGetDoublev(GL_MODELVIEW_MATRIX, m). It actually represents the state of the \c GL_MODELVIEW after QGLViewer::preDraw(), at the \e beginning of QGLViewer::draw(). It converts from the world to the Camera coordinate system. As soon as you modify the \c GL_MODELVIEW in your QGLViewer::draw() method (using glTranslate, glRotate... or similar methods), the two matrices differ. The result is an OpenGL 4x4 matrix, which is given in \e column-major order (see \c glMultMatrix man page for details). See also getProjectionMatrix() and setFromModelViewMatrix(). */ void Camera::getModelViewMatrix(GLdouble m[16]) const { // May not be needed, but easier like this. // Prevents from retrieving matrix in stereo mode -> overwrites shifted value. computeModelViewMatrix(); for (unsigned short i=0; i<16; ++i) m[i] = modelViewMatrix_[i]; } /*! Overloaded getModelViewMatrix(GLdouble m[16]) method using a \c GLfloat array instead. */ void Camera::getModelViewMatrix(GLfloat m[16]) const { static GLdouble mat[16]; getModelViewMatrix(mat); for (unsigned short i=0; i<16; ++i) m[i] = float(mat[i]); } /*! Fills \p m with the product of the ModelView and Projection matrices. Calls getModelViewMatrix() and getProjectionMatrix() and then fills \p m with the product of these two matrices. */ void Camera::getModelViewProjectionMatrix(GLdouble m[16]) const { GLdouble mv[16]; GLdouble proj[16]; getModelViewMatrix(mv); getProjectionMatrix(proj); for (unsigned short i=0; i<4; ++i) { for (unsigned short j=0; j<4; ++j) { qreal sum = 0.0; for (unsigned short k=0; k<4; ++k) sum += proj[i+4*k]*mv[k+4*j]; m[i+4*j] = sum; } } } /*! Overloaded getModelViewProjectionMatrix(GLdouble m[16]) method using a \c GLfloat array instead. */ void Camera::getModelViewProjectionMatrix(GLfloat m[16]) const { static GLdouble mat[16]; getModelViewProjectionMatrix(mat); for (unsigned short i=0; i<16; ++i) m[i] = float(mat[i]); } /*! Sets the sceneRadius() value. Negative values are ignored. \attention This methods also sets focusDistance() to sceneRadius() / tan(fieldOfView()/2) and flySpeed() to 1% of sceneRadius(). */ void Camera::setSceneRadius(qreal radius) { if (radius <= 0.0) { qWarning("Scene radius must be positive - Ignoring value"); return; } sceneRadius_ = radius; projectionMatrixIsUpToDate_ = false; setFocusDistance(sceneRadius() / tan(fieldOfView()/2.0)); frame()->setFlySpeed(0.01*sceneRadius()); } /*! Similar to setSceneRadius() and setSceneCenter(), but the scene limits are defined by a (world axis aligned) bounding box. */ void Camera::setSceneBoundingBox(const Vec& min, const Vec& max) { setSceneCenter((min+max)/2.0); setSceneRadius(0.5*(max-min).norm()); } /*! Sets the sceneCenter(). \attention This method also sets the pivotPoint() to sceneCenter(). */ void Camera::setSceneCenter(const Vec& center) { sceneCenter_ = center; setPivotPoint(sceneCenter()); projectionMatrixIsUpToDate_ = false; } /*! setSceneCenter() to the result of pointUnderPixel(\p pixel). Returns \c true if a pointUnderPixel() was found and sceneCenter() was actually changed. See also setPivotPointFromPixel(). See the pointUnderPixel() documentation. */ bool Camera::setSceneCenterFromPixel(const QPoint& pixel) { bool found; Vec point = pointUnderPixel(pixel, found); if (found) setSceneCenter(point); return found; } #ifndef DOXYGEN void Camera::setRevolveAroundPoint(const Vec& point) { qWarning("setRevolveAroundPoint() is deprecated, use setPivotPoint() instead"); setPivotPoint(point); } bool Camera::setRevolveAroundPointFromPixel(const QPoint& pixel) { qWarning("setRevolveAroundPointFromPixel() is deprecated, use setPivotPointFromPixel() instead"); return setPivotPointFromPixel(pixel); } Vec Camera::revolveAroundPoint() const { qWarning("revolveAroundPoint() is deprecated, use pivotPoint() instead"); return pivotPoint(); } #endif /*! Changes the pivotPoint() to \p point (defined in the world coordinate system). */ void Camera::setPivotPoint(const Vec& point) { const qreal prevDist = fabs(cameraCoordinatesOf(pivotPoint()).z); // If frame's RAP is set directly, projectionMatrixIsUpToDate_ should also be // set to false to ensure proper recomputation of the ORTHO projection matrix. frame()->setPivotPoint(point); // orthoCoef_ is used to compensate for changes of the pivotPoint, so that the image does // not change when the pivotPoint is changed in ORTHOGRAPHIC mode. const qreal newDist = fabs(cameraCoordinatesOf(pivotPoint()).z); // Prevents division by zero when rap is set to camera position if ((prevDist > 1E-9) && (newDist > 1E-9)) orthoCoef_ *= prevDist / newDist; projectionMatrixIsUpToDate_ = false; } /*! The pivotPoint() is set to the point located under \p pixel on screen. Returns \c true if a pointUnderPixel() was found. If no point was found under \p pixel, the pivotPoint() is left unchanged. \p pixel is expressed in Qt format (origin in the upper left corner of the window). See pointUnderPixel(). See also setSceneCenterFromPixel(). */ bool Camera::setPivotPointFromPixel(const QPoint& pixel) { bool found; Vec point = pointUnderPixel(pixel, found); if (found) setPivotPoint(point); return found; } /*! Returns the ratio between pixel and OpenGL units at \p position. A line of \c n * pixelGLRatio() OpenGL units, located at \p position in the world coordinates system, will be projected with a length of \c n pixels on screen. Use this method to scale objects so that they have a constant pixel size on screen. The following code will draw a 20 pixel line, starting at sceneCenter() and always directed along the screen vertical direction: \code glBegin(GL_LINES); glVertex3fv(sceneCenter()); glVertex3fv(sceneCenter() + 20 * pixelGLRatio(sceneCenter()) * camera()->upVector()); glEnd(); \endcode */ qreal Camera::pixelGLRatio(const Vec& position) const { switch (type()) { case Camera::PERSPECTIVE : return 2.0 * fabs((frame()->coordinatesOf(position)).z) * tan(fieldOfView()/2.0) / screenHeight(); case Camera::ORTHOGRAPHIC : { GLdouble w, h; getOrthoWidthHeight(w,h); return 2.0 * h / screenHeight(); } } // Bad compilers complain return 1.0; } /*! Changes the Camera fieldOfView() so that the entire scene (defined by QGLViewer::sceneCenter() and QGLViewer::sceneRadius()) is visible from the Camera position(). The position() and orientation() of the Camera are not modified and you first have to orientate the Camera in order to actually see the scene (see lookAt(), showEntireScene() or fitSphere()). This method is especially useful for \e shadow \e maps computation. Use the Camera positioning tools (setPosition(), lookAt()) to position a Camera at the light position. Then use this method to define the fieldOfView() so that the shadow map resolution is optimally used: \code // The light camera needs size hints in order to optimize its fieldOfView lightCamera->setSceneRadius(sceneRadius()); lightCamera->setSceneCenter(sceneCenter()); // Place the light camera. lightCamera->setPosition(lightFrame->position()); lightCamera->lookAt(sceneCenter()); lightCamera->setFOVToFitScene(); \endcode See the (soon available) shadowMap contribution example for a practical implementation. \attention The fieldOfView() is clamped to M_PI/2.0. This happens when the Camera is at a distance lower than sqrt(2.0) * sceneRadius() from the sceneCenter(). It optimizes the shadow map resolution, although it may miss some parts of the scene. */ void Camera::setFOVToFitScene() { if (distanceToSceneCenter() > sqrt(2.0)*sceneRadius()) setFieldOfView(2.0 * asin(sceneRadius() / distanceToSceneCenter())); else setFieldOfView(M_PI / 2.0); } /*! Makes the Camera smoothly zoom on the pointUnderPixel() \p pixel. Nothing happens if no pointUnderPixel() is found. Otherwise a KeyFrameInterpolator is created that animates the Camera on a one second path that brings the Camera closer to the point under \p pixel. See also interpolateToFitScene(). */ void Camera::interpolateToZoomOnPixel(const QPoint& pixel) { const qreal coef = 0.1; bool found; Vec target = pointUnderPixel(pixel, found); if (!found) return; if (interpolationKfi_->interpolationIsStarted()) interpolationKfi_->stopInterpolation(); interpolationKfi_->deletePath(); interpolationKfi_->addKeyFrame(*(frame())); interpolationKfi_->addKeyFrame(Frame(0.3*frame()->position() + 0.7*target, frame()->orientation()), 0.4); // Small hack: attach a temporary frame to take advantage of lookAt without modifying frame static ManipulatedCameraFrame* tempFrame = new ManipulatedCameraFrame(); ManipulatedCameraFrame* const originalFrame = frame(); tempFrame->setPosition(coef*frame()->position() + (1.0-coef)*target); tempFrame->setOrientation(frame()->orientation()); setFrame(tempFrame); lookAt(target); setFrame(originalFrame); interpolationKfi_->addKeyFrame(*(tempFrame), 1.0); interpolationKfi_->startInterpolation(); } /*! Interpolates the Camera on a one second KeyFrameInterpolator path so that the entire scene fits the screen at the end. The scene is defined by its sceneCenter() and its sceneRadius(). See showEntireScene(). The orientation() of the Camera is not modified. See also interpolateToZoomOnPixel(). */ void Camera::interpolateToFitScene() { if (interpolationKfi_->interpolationIsStarted()) interpolationKfi_->stopInterpolation(); interpolationKfi_->deletePath(); interpolationKfi_->addKeyFrame(*(frame())); // Small hack: attach a temporary frame to take advantage of lookAt without modifying frame static ManipulatedCameraFrame* tempFrame = new ManipulatedCameraFrame(); ManipulatedCameraFrame* const originalFrame = frame(); tempFrame->setPosition(frame()->position()); tempFrame->setOrientation(frame()->orientation()); setFrame(tempFrame); showEntireScene(); setFrame(originalFrame); interpolationKfi_->addKeyFrame(*(tempFrame)); interpolationKfi_->startInterpolation(); } /*! Smoothly interpolates the Camera on a KeyFrameInterpolator path so that it goes to \p fr. \p fr is expressed in world coordinates. \p duration tunes the interpolation speed (default is 1 second). See also interpolateToFitScene() and interpolateToZoomOnPixel(). */ void Camera::interpolateTo(const Frame& fr, qreal duration) { if (interpolationKfi_->interpolationIsStarted()) interpolationKfi_->stopInterpolation(); interpolationKfi_->deletePath(); interpolationKfi_->addKeyFrame(*(frame())); interpolationKfi_->addKeyFrame(fr, duration); interpolationKfi_->startInterpolation(); } /*! Returns the coordinates of the 3D point located at pixel (x,y) on screen. Calls a \c glReadPixel to get the pixel depth and applies an unprojectedCoordinatesOf() to the result. \p found indicates whether a point was found or not (i.e. background pixel, result's depth is zFar() in that case). \p x and \p y are expressed in pixel units with an origin in the upper left corner. Use screenHeight() - y to convert to OpenGL standard. \attention This method assumes that a GL context is available, and that its content was drawn using the Camera (i.e. using its projection and modelview matrices). This method hence cannot be used for offscreen Camera computations. Use cameraCoordinatesOf() and worldCoordinatesOf() to perform similar operations in that case. \note The precision of the z-Buffer highly depends on how the zNear() and zFar() values are fitted to your scene. Loose boundaries will result in imprecision along the viewing direction. */ Vec Camera::pointUnderPixel(const QPoint& pixel, bool& found) const { float depth; // Qt uses upper corner for its origin while GL uses the lower corner. glReadPixels(pixel.x(), screenHeight()-1-pixel.y(), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth); found = depth < 1.0; Vec point(pixel.x(), pixel.y(), depth); point = unprojectedCoordinatesOf(point); return point; } /*! Moves the Camera so that the entire scene is visible. Simply calls fitSphere() on a sphere defined by sceneCenter() and sceneRadius(). You will typically use this method in QGLViewer::init() after you defined a new sceneRadius(). */ void Camera::showEntireScene() { fitSphere(sceneCenter(), sceneRadius()); } /*! Moves the Camera so that its sceneCenter() is projected on the center of the window. The orientation() and fieldOfView() are unchanged. Simply projects the current position on a line passing through sceneCenter(). See also showEntireScene().*/ void Camera::centerScene() { frame()->projectOnLine(sceneCenter(), viewDirection()); } /*! Sets the Camera orientation(), so that it looks at point \p target (defined in the world coordinate system). The Camera position() is not modified. Simply setViewDirection(). See also setUpVector(), setOrientation(), showEntireScene(), fitSphere() and fitBoundingBox(). */ void Camera::lookAt(const Vec& target) { setViewDirection(target - position()); } /*! Moves the Camera so that the sphere defined by (\p center, \p radius) is visible and fits in the frustum. The Camera is simply translated to center the sphere in the screen and make it fit the frustum. Its orientation() and its fieldOfView() are unchanged. You should therefore orientate the Camera before you call this method. See lookAt(), setOrientation() and setUpVector(). */ void Camera::fitSphere(const Vec& center, qreal radius) { qreal distance = 0.0; switch (type()) { case Camera::PERSPECTIVE : { const qreal yview = radius / sin(fieldOfView() / 2.0); const qreal xview = radius / sin(horizontalFieldOfView() / 2.0); distance = qMax(xview, yview); break; } case Camera::ORTHOGRAPHIC : { distance = ((center-pivotPoint()) * viewDirection()) + (radius / orthoCoef_); break; } } Vec newPos(center - distance * viewDirection()); frame()->setPositionWithConstraint(newPos); } /*! Moves the Camera so that the (world axis aligned) bounding box (\p min, \p max) is entirely visible, using fitSphere(). */ void Camera::fitBoundingBox(const Vec& min, const Vec& max) { qreal diameter = qMax(fabs(max[1]-min[1]), fabs(max[0]-min[0])); diameter = qMax(fabs(max[2]-min[2]), diameter); fitSphere(0.5*(min+max), 0.5*diameter); } /*! Moves the Camera so that the rectangular screen region defined by \p rectangle (pixel units, with origin in the upper left corner) fits the screen. The Camera is translated (its orientation() is unchanged) so that \p rectangle is entirely visible. Since the pixel coordinates only define a \e frustum in 3D, it's the intersection of this frustum with a plane (orthogonal to the viewDirection() and passing through the sceneCenter()) that is used to define the 3D rectangle that is eventually fitted. */ void Camera::fitScreenRegion(const QRect& rectangle) { const Vec vd = viewDirection(); const qreal distToPlane = distanceToSceneCenter(); const QPoint center = rectangle.center(); Vec orig, dir; convertClickToLine( center, orig, dir ); Vec newCenter = orig + distToPlane / (dir*vd) * dir; convertClickToLine( QPoint(rectangle.x(), center.y()), orig, dir ); const Vec pointX = orig + distToPlane / (dir*vd) * dir; convertClickToLine( QPoint(center.x(), rectangle.y()), orig, dir ); const Vec pointY = orig + distToPlane / (dir*vd) * dir; qreal distance = 0.0; switch (type()) { case Camera::PERSPECTIVE : { const qreal distX = (pointX-newCenter).norm() / sin(horizontalFieldOfView()/2.0); const qreal distY = (pointY-newCenter).norm() / sin(fieldOfView()/2.0); distance = qMax(distX, distY); break; } case Camera::ORTHOGRAPHIC : { const qreal dist = ((newCenter-pivotPoint()) * vd); //#CONNECTION# getOrthoWidthHeight const qreal distX = (pointX-newCenter).norm() / orthoCoef_ / ((aspectRatio() < 1.0) ? 1.0 : aspectRatio()); const qreal distY = (pointY-newCenter).norm() / orthoCoef_ / ((aspectRatio() < 1.0) ? 1.0/aspectRatio() : 1.0); distance = dist + qMax(distX, distY); break; } } Vec newPos(newCenter - distance * vd); frame()->setPositionWithConstraint(newPos); } /*! Rotates the Camera so that its upVector() becomes \p up (defined in the world coordinate system). The Camera is rotated around an axis orthogonal to \p up and to the current upVector() direction. Use this method in order to define the Camera horizontal plane. When \p noMove is set to \c false, the orientation modification is compensated by a translation, so that the pivotPoint() stays projected at the same position on screen. This is especially useful when the Camera is used as an observer of the scene (default mouse binding). When \p noMove is \c true (default), the Camera position() is left unchanged, which is an intuitive behavior when the Camera is in a walkthrough fly mode (see the QGLViewer::MOVE_FORWARD and QGLViewer::MOVE_BACKWARD QGLViewer::MouseAction). The frame()'s ManipulatedCameraFrame::sceneUpVector() is set accordingly. See also setViewDirection(), lookAt() and setOrientation(). */ void Camera::setUpVector(const Vec& up, bool noMove) { Quaternion q(Vec(0.0, 1.0, 0.0), frame()->transformOf(up)); if (!noMove) frame()->setPosition(pivotPoint() - (frame()->orientation()*q).rotate(frame()->coordinatesOf(pivotPoint()))); frame()->rotate(q); // Useful in fly mode to keep the horizontal direction. frame()->updateSceneUpVector(); } /*! Sets the orientation() of the Camera using polar coordinates. \p theta rotates the Camera around its Y axis, and \e then \p phi rotates it around its X axis. The polar coordinates are defined in the world coordinates system: \p theta = \p phi = 0 means that the Camera is directed towards the world Z axis. Both angles are expressed in radians. See also setUpVector(). The position() of the Camera is unchanged, you may want to call showEntireScene() after this method to move the Camera. This method can be useful to create Quicktime VR panoramic sequences, see the QGLViewer::saveSnapshot() documentation for details. */ void Camera::setOrientation(qreal theta, qreal phi) { Vec axis(0.0, 1.0, 0.0); const Quaternion rot1(axis, theta); axis = Vec(-cos(theta), 0.0, sin(theta)); const Quaternion rot2(axis, phi); setOrientation(rot1 * rot2); } /*! Sets the Camera orientation(), defined in the world coordinate system. */ void Camera::setOrientation(const Quaternion& q) { frame()->setOrientation(q); frame()->updateSceneUpVector(); } /*! Rotates the Camera so that its viewDirection() is \p direction (defined in the world coordinate system). The Camera position() is not modified. The Camera is rotated so that the horizon (defined by its upVector()) is preserved. See also lookAt() and setUpVector(). */ void Camera::setViewDirection(const Vec& direction) { if (direction.squaredNorm() < 1E-10) return; Vec xAxis = direction ^ upVector(); if (xAxis.squaredNorm() < 1E-10) { // target is aligned with upVector, this means a rotation around X axis // X axis is then unchanged, let's keep it ! xAxis = frame()->inverseTransformOf(Vec(1.0, 0.0, 0.0)); } Quaternion q; q.setFromRotatedBasis(xAxis, xAxis^direction, -direction); frame()->setOrientationWithConstraint(q); } // Compute a 3 by 3 determinant. static qreal det(qreal m00,qreal m01,qreal m02, qreal m10,qreal m11,qreal m12, qreal m20,qreal m21,qreal m22) { return m00*m11*m22 + m01*m12*m20 + m02*m10*m21 - m20*m11*m02 - m10*m01*m22 - m00*m21*m12; } // Computes the index of element [i][j] in a \c qreal matrix[3][4]. static inline unsigned int ind(unsigned int i, unsigned int j) { return (i*4+j); } /*! Returns the Camera position (the eye), defined in the world coordinate system. Use setPosition() to set the Camera position. Other convenient methods are showEntireScene() or fitSphere(). Actually returns \c frame()->position(). This position corresponds to the projection center of a Camera::PERSPECTIVE Camera. It is not located in the image plane, which is at a zNear() distance ahead. */ Vec Camera::position() const { return frame()->position(); } /*! Returns the normalized up vector of the Camera, defined in the world coordinate system. Set using setUpVector() or setOrientation(). It is orthogonal to viewDirection() and to rightVector(). It corresponds to the Y axis of the associated frame() (actually returns frame()->inverseTransformOf(Vec(0.0, 1.0, 0.0)) ). */ Vec Camera::upVector() const { return frame()->inverseTransformOf(Vec(0.0, 1.0, 0.0)); } /*! Returns the normalized view direction of the Camera, defined in the world coordinate system. Change this value using setViewDirection(), lookAt() or setOrientation(). It is orthogonal to upVector() and to rightVector(). This corresponds to the negative Z axis of the frame() ( frame()->inverseTransformOf(Vec(0.0, 0.0, -1.0)) ). */ Vec Camera::viewDirection() const { return frame()->inverseTransformOf(Vec(0.0, 0.0, -1.0)); } /*! Returns the normalized right vector of the Camera, defined in the world coordinate system. This vector lies in the Camera horizontal plane, directed along the X axis (orthogonal to upVector() and to viewDirection()). Set using setUpVector(), lookAt() or setOrientation(). Simply returns frame()->inverseTransformOf(Vec(1.0, 0.0, 0.0)). */ Vec Camera::rightVector() const { return frame()->inverseTransformOf(Vec(1.0, 0.0, 0.0)); } /*! Returns the Camera orientation, defined in the world coordinate system. Actually returns \c frame()->orientation(). Use setOrientation(), setUpVector() or lookAt() to set the Camera orientation. */ Quaternion Camera::orientation() const { return frame()->orientation(); } /*! Sets the Camera position() (the eye), defined in the world coordinate system. */ void Camera::setPosition(const Vec& pos) { frame()->setPosition(pos); } /*! Returns the Camera frame coordinates of a point \p src defined in world coordinates. worldCoordinatesOf() performs the inverse transformation. Note that the point coordinates are simply converted in a different coordinate system. They are not projected on screen. Use projectedCoordinatesOf() for that. */ Vec Camera::cameraCoordinatesOf(const Vec& src) const { return frame()->coordinatesOf(src); } /*! Returns the world coordinates of the point whose position \p src is defined in the Camera coordinate system. cameraCoordinatesOf() performs the inverse transformation. */ Vec Camera::worldCoordinatesOf(const Vec& src) const { return frame()->inverseCoordinatesOf(src); } /*! Returns the fly speed of the Camera. Simply returns frame()->flySpeed(). See the ManipulatedCameraFrame::flySpeed() documentation. This value is only meaningful when the MouseAction bindings is QGLViewer::MOVE_FORWARD or QGLViewer::MOVE_BACKWARD. Set to 1% of the sceneRadius() by setSceneRadius(). See also setFlySpeed(). */ qreal Camera::flySpeed() const { return frame()->flySpeed(); } /*! Sets the Camera flySpeed(). \attention This value is modified by setSceneRadius(). */ void Camera::setFlySpeed(qreal speed) { frame()->setFlySpeed(speed); } /*! The point the Camera pivots around with the QGLViewer::ROTATE mouse binding. Defined in world coordinate system. Default value is the sceneCenter(). \attention setSceneCenter() changes this value. */ Vec Camera::pivotPoint() const { return frame()->pivotPoint(); } /*! Sets the Camera's position() and orientation() from an OpenGL ModelView matrix. This enables a Camera initialisation from an other OpenGL application. \p modelView is a 16 GLdouble vector representing a valid OpenGL ModelView matrix, such as one can get using: \code GLdouble mvm[16]; glGetDoublev(GL_MODELVIEW_MATRIX, mvm); myCamera->setFromModelViewMatrix(mvm); \endcode After this method has been called, getModelViewMatrix() returns a matrix equivalent to \p modelView. Only the orientation() and position() of the Camera are modified. \note If you defined your matrix as \c GLdouble \c mvm[4][4], pass \c &(mvm[0][0]) as a parameter. */ void Camera::setFromModelViewMatrix(const GLdouble* const modelViewMatrix) { // Get upper left (rotation) matrix qreal upperLeft[3][3]; for (int i=0; i<3; ++i) for (int j=0; j<3; ++j) upperLeft[i][j] = modelViewMatrix[i*4+j]; // Transform upperLeft into the associated Quaternion Quaternion q; q.setFromRotationMatrix(upperLeft); setOrientation(q); setPosition(-q.rotate(Vec(modelViewMatrix[12], modelViewMatrix[13], modelViewMatrix[14]))); } /*! Defines the Camera position(), orientation() and fieldOfView() from a projection matrix. \p matrix has to be given in the format used by vision algorithm. It has 3 lines and 4 columns. It transforms a point from the world homogeneous coordinate system (4 coordinates: \c sx, \c sy, \c sz and \c s) into a point in the screen homogeneous coordinate system (3 coordinates: \c sx, \c sy, and \c s, where \c x and \c y are the pixel coordinates on the screen). Its three lines correspond to the homogeneous coordinates of the normals to the planes x=0, y=0 and z=0, defined in the Camera coordinate system. The elements of the matrix are ordered in line major order: you can call \c setFromProjectionMatrix(&(matrix[0][0])) if you defined your matrix as a \c qreal \c matrix[3][4]. \attention Passing the result of getProjectionMatrix() or getModelViewMatrix() to this method is not possible (purposefully incompatible matrix dimensions). \p matrix is more likely to be the product of these two matrices, without the last line. Use setFromModelViewMatrix() to set position() and orientation() from a \c GL_MODELVIEW matrix. fieldOfView() can also be retrieved from a \e perspective \c GL_PROJECTION matrix using 2.0 * atan(1.0/projectionMatrix[5]). This code was written by Sylvain Paris. */ void Camera::setFromProjectionMatrix(const qreal matrix[12]) { // The 3 lines of the matrix are the normals to the planes x=0, y=0, z=0 // in the camera CS. As we normalize them, we do not need the 4th coordinate. Vec line_0(matrix[ind(0,0)],matrix[ind(0,1)],matrix[ind(0,2)]); Vec line_1(matrix[ind(1,0)],matrix[ind(1,1)],matrix[ind(1,2)]); Vec line_2(matrix[ind(2,0)],matrix[ind(2,1)],matrix[ind(2,2)]); line_0.normalize(); line_1.normalize(); line_2.normalize(); // The camera position is at (0,0,0) in the camera CS so it is the // intersection of the 3 planes. It can be seen as the kernel // of the 3x4 projection matrix. We calculate it through 4 dimensional // vectorial product. We go directly into 3D that is to say we directly // divide the first 3 coordinates by the 4th one. // We derive the 4 dimensional vectorial product formula from the // computation of a 4x4 determinant that is developped according to // its 4th column. This implies some 3x3 determinants. const Vec cam_pos = Vec(det(matrix[ind(0,1)],matrix[ind(0,2)],matrix[ind(0,3)], matrix[ind(1,1)],matrix[ind(1,2)],matrix[ind(1,3)], matrix[ind(2,1)],matrix[ind(2,2)],matrix[ind(2,3)]), -det(matrix[ind(0,0)],matrix[ind(0,2)],matrix[ind(0,3)], matrix[ind(1,0)],matrix[ind(1,2)],matrix[ind(1,3)], matrix[ind(2,0)],matrix[ind(2,2)],matrix[ind(2,3)]), det(matrix[ind(0,0)],matrix[ind(0,1)],matrix[ind(0,3)], matrix[ind(1,0)],matrix[ind(1,1)],matrix[ind(1,3)], matrix[ind(2,0)],matrix[ind(2,1)],matrix[ind(2,3)])) / (-det(matrix[ind(0,0)],matrix[ind(0,1)],matrix[ind(0,2)], matrix[ind(1,0)],matrix[ind(1,1)],matrix[ind(1,2)], matrix[ind(2,0)],matrix[ind(2,1)],matrix[ind(2,2)])); // We compute the rotation matrix column by column. // GL Z axis is front facing. Vec column_2 = -line_2; // X-axis is almost like line_0 but should be orthogonal to the Z axis. Vec column_0 = ((column_2^line_0)^column_2); column_0.normalize(); // Y-axis is almost like line_1 but should be orthogonal to the Z axis. // Moreover line_1 is downward oriented as the screen CS. Vec column_1 = -((column_2^line_1)^column_2); column_1.normalize(); qreal rot[3][3]; rot[0][0] = column_0[0]; rot[1][0] = column_0[1]; rot[2][0] = column_0[2]; rot[0][1] = column_1[0]; rot[1][1] = column_1[1]; rot[2][1] = column_1[2]; rot[0][2] = column_2[0]; rot[1][2] = column_2[1]; rot[2][2] = column_2[2]; // We compute the field of view // line_1^column_0 -> vector of intersection line between // y_screen=0 and x_camera=0 plane. // column_2*(...) -> cos of the angle between Z vector et y_screen=0 plane // * 2 -> field of view = 2 * half angle // We need some intermediate values. Vec dummy = line_1^column_0; dummy.normalize(); qreal fov = acos(column_2*dummy) * 2.0; // We set the camera. Quaternion q; q.setFromRotationMatrix(rot); setOrientation(q); setPosition(cam_pos); setFieldOfView(fov); } /* // persp : projectionMatrix_[0] = f/aspectRatio(); void Camera::setFromProjectionMatrix(const GLdouble* projectionMatrix) { QString message; if ((fabs(projectionMatrix[1]) > 1E-3) || (fabs(projectionMatrix[2]) > 1E-3) || (fabs(projectionMatrix[3]) > 1E-3) || (fabs(projectionMatrix[4]) > 1E-3) || (fabs(projectionMatrix[6]) > 1E-3) || (fabs(projectionMatrix[7]) > 1E-3) || (fabs(projectionMatrix[8]) > 1E-3) || (fabs(projectionMatrix[9]) > 1E-3)) message = "Non null coefficient in projection matrix - Aborting"; else if ((fabs(projectionMatrix[11]+1.0) < 1E-5) && (fabs(projectionMatrix[15]) < 1E-5)) { if (projectionMatrix[5] < 1E-4) message="Negative field of view in Camera::setFromProjectionMatrix"; else setType(Camera::PERSPECTIVE); } else if ((fabs(projectionMatrix[11]) < 1E-5) && (fabs(projectionMatrix[15]-1.0) < 1E-5)) setType(Camera::ORTHOGRAPHIC); else message = "Unable to determine camera type in setFromProjectionMatrix - Aborting"; if (!message.isEmpty()) { qWarning(message); return; } switch (type()) { case Camera::PERSPECTIVE: { setFieldOfView(2.0 * atan(1.0/projectionMatrix[5])); const qreal far = projectionMatrix[14] / (2.0 * (1.0 + projectionMatrix[10])); const qreal near = (projectionMatrix[10]+1.0) / (projectionMatrix[10]-1.0) * far; setSceneRadius((far-near)/2.0); setSceneCenter(position() + (near + sceneRadius())*viewDirection()); break; } case Camera::ORTHOGRAPHIC: { GLdouble w, h; getOrthoWidthHeight(w,h); projectionMatrix_[0] = 1.0/w; projectionMatrix_[5] = 1.0/h; projectionMatrix_[10] = -2.0/(ZFar - ZNear); projectionMatrix_[11] = 0.0; projectionMatrix_[14] = -(ZFar + ZNear)/(ZFar - ZNear); projectionMatrix_[15] = 1.0; // same as glOrtho( -w, w, -h, h, zNear(), zFar() ); break; } } } */ ///////////////////////// Camera to world transform /////////////////////// /*! Same as cameraCoordinatesOf(), but with \c qreal[3] parameters (\p src and \p res may be identical pointers). */ void Camera::getCameraCoordinatesOf(const qreal src[3], qreal res[3]) const { Vec r = cameraCoordinatesOf(Vec(src)); for (int i=0; i<3; ++i) res[i] = r[i]; } /*! Same as worldCoordinatesOf(), but with \c qreal[3] parameters (\p src and \p res may be identical pointers). */ void Camera::getWorldCoordinatesOf(const qreal src[3], qreal res[3]) const { Vec r = worldCoordinatesOf(Vec(src)); for (int i=0; i<3; ++i) res[i] = r[i]; } /*! Fills \p viewport with the Camera OpenGL viewport. This method is mainly used in conjunction with \c gluProject, which requires such a viewport. Returned values are (0, screenHeight(), screenWidth(), - screenHeight()), so that the origin is located in the \e upper left corner of the window (Qt style coordinate system). */ void Camera::getViewport(GLint viewport[4]) const { viewport[0] = 0; viewport[1] = screenHeight(); viewport[2] = screenWidth(); viewport[3] = -screenHeight(); } /*! Returns the screen projected coordinates of a point \p src defined in the \p frame coordinate system. When \p frame in \c NULL (default), \p src is expressed in the world coordinate system. The x and y coordinates of the returned Vec are expressed in pixel, (0,0) being the \e upper left corner of the window. The z coordinate ranges between 0.0 (near plane) and 1.0 (excluded, far plane). See the \c gluProject man page for details. unprojectedCoordinatesOf() performs the inverse transformation. See the <a href="../examples/screenCoordSystem.html">screenCoordSystem example</a>. This method only uses the intrinsic Camera parameters (see getModelViewMatrix(), getProjectionMatrix() and getViewport()) and is completely independent of the OpenGL \c GL_MODELVIEW, \c GL_PROJECTION and viewport matrices. You can hence define a virtual Camera and use this method to compute projections out of a classical rendering context. \attention However, if your Camera is not attached to a QGLViewer (used for offscreen computations for instance), make sure the Camera matrices are updated before calling this method. Call computeModelViewMatrix() and computeProjectionMatrix() to do so. If you call this method several times with no change in the matrices, consider precomputing the projection times modelview matrix to save computation time if required (\c P x \c M in the \c gluProject man page). Here is the code corresponding to what this method does (kindly submitted by Robert W. Kuhn) : \code Vec project(Vec point) { GLint Viewport[4]; GLdouble Projection[16], Modelview[16]; GLdouble matrix[16]; // Precomputation begin glGetIntegerv(GL_VIEWPORT , Viewport); glGetDoublev (GL_MODELVIEW_MATRIX , Modelview); glGetDoublev (GL_PROJECTION_MATRIX, Projection); for (unsigned short m=0; m<4; ++m) { for (unsigned short l=0; l<4; ++l) { qreal sum = 0.0; for (unsigned short k=0; k<4; ++k) sum += Projection[l+4*k]*Modelview[k+4*m]; matrix[l+4*m] = sum; } } // Precomputation end GLdouble v[4], vs[4]; v[0]=point[0]; v[1]=point[1]; v[2]=point[2]; v[3]=1.0; vs[0]=matrix[0 ]*v[0] + matrix[4 ]*v[1] + matrix[8 ]*v[2] + matrix[12 ]*v[3]; vs[1]=matrix[1 ]*v[0] + matrix[5 ]*v[1] + matrix[9 ]*v[2] + matrix[13 ]*v[3]; vs[2]=matrix[2 ]*v[0] + matrix[6 ]*v[1] + matrix[10]*v[2] + matrix[14 ]*v[3]; vs[3]=matrix[3 ]*v[0] + matrix[7 ]*v[1] + matrix[11]*v[2] + matrix[15 ]*v[3]; vs[0] /= vs[3]; vs[1] /= vs[3]; vs[2] /= vs[3]; vs[0] = vs[0] * 0.5 + 0.5; vs[1] = vs[1] * 0.5 + 0.5; vs[2] = vs[2] * 0.5 + 0.5; vs[0] = vs[0] * Viewport[2] + Viewport[0]; vs[1] = vs[1] * Viewport[3] + Viewport[1]; return Vec(vs[0], Viewport[3]-vs[1], vs[2]); } \endcode */ Vec Camera::projectedCoordinatesOf(const Vec& src, const Frame* frame) const { GLdouble x,y,z; static GLint viewport[4]; getViewport(viewport); if (frame) { const Vec tmp = frame->inverseCoordinatesOf(src); gluProject(tmp.x,tmp.y,tmp.z, modelViewMatrix_, projectionMatrix_, viewport, &x,&y,&z); } else gluProject(src.x,src.y,src.z, modelViewMatrix_, projectionMatrix_, viewport, &x,&y,&z); return Vec(x,y,z); } /*! Returns the world unprojected coordinates of a point \p src defined in the screen coordinate system. The \p src.x and \p src.y input values are expressed in pixels, (0,0) being the \e upper left corner of the window. \p src.z is a depth value ranging in [0..1[ (respectively corresponding to the near and far planes). Note that src.z is \e not a linear interpolation between zNear and zFar. /code src.z = zFar() / (zFar() - zNear()) * (1.0 - zNear() / z); /endcode Where z is the distance from the point you project to the camera, along the viewDirection(). See the \c gluUnProject man page for details. The result is expressed in the \p frame coordinate system. When \p frame is \c NULL (default), the result is expressed in the world coordinates system. The possible \p frame Frame::referenceFrame() are taken into account. projectedCoordinatesOf() performs the inverse transformation. This method only uses the intrinsic Camera parameters (see getModelViewMatrix(), getProjectionMatrix() and getViewport()) and is completely independent of the OpenGL \c GL_MODELVIEW, \c GL_PROJECTION and viewport matrices. You can hence define a virtual Camera and use this method to compute un-projections out of a classical rendering context. \attention However, if your Camera is not attached to a QGLViewer (used for offscreen computations for instance), make sure the Camera matrices are updated before calling this method (use computeModelViewMatrix(), computeProjectionMatrix()). See also setScreenWidthAndHeight(). This method is not computationally optimized. If you call it several times with no change in the matrices, you should buffer the entire inverse projection matrix (modelview, projection and then viewport) to speed-up the queries. See the \c gluUnProject man page for details. */ Vec Camera::unprojectedCoordinatesOf(const Vec& src, const Frame* frame) const { GLdouble x,y,z; static GLint viewport[4]; getViewport(viewport); gluUnProject(src.x,src.y,src.z, modelViewMatrix_, projectionMatrix_, viewport, &x,&y,&z); if (frame) return frame->coordinatesOf(Vec(x,y,z)); else return Vec(x,y,z); } /*! Same as projectedCoordinatesOf(), but with \c qreal parameters (\p src and \p res can be identical pointers). */ void Camera::getProjectedCoordinatesOf(const qreal src[3], qreal res[3], const Frame* frame) const { Vec r = projectedCoordinatesOf(Vec(src), frame); for (int i=0; i<3; ++i) res[i] = r[i]; } /*! Same as unprojectedCoordinatesOf(), but with \c qreal parameters (\p src and \p res can be identical pointers). */ void Camera::getUnprojectedCoordinatesOf(const qreal src[3], qreal res[3], const Frame* frame) const { Vec r = unprojectedCoordinatesOf(Vec(src), frame); for (int i=0; i<3; ++i) res[i] = r[i]; } ///////////////////////////////////// KFI ///////////////////////////////////////// /*! Returns the KeyFrameInterpolator that defines the Camera path number \p i. If path \p i is not defined for this index, the method returns a \c NULL pointer. */ KeyFrameInterpolator* Camera::keyFrameInterpolator(unsigned int i) const { if (kfi_.contains(i)) return kfi_[i]; else return NULL; } /*! Sets the KeyFrameInterpolator that defines the Camera path of index \p i. The previous keyFrameInterpolator() is lost and should be deleted by the calling method if needed. The KeyFrameInterpolator::interpolated() signal of \p kfi probably needs to be connected to the Camera's associated QGLViewer::update() slot, so that when the Camera position is interpolated using \p kfi, every interpolation step updates the display: \code myViewer.camera()->deletePath(3); myViewer.camera()->setKeyFrameInterpolator(3, myKeyFrameInterpolator); connect(myKeyFrameInterpolator, SIGNAL(interpolated()), myViewer, SLOT(update()); \endcode \note These connections are done automatically when a Camera is attached to a QGLViewer, or when a new KeyFrameInterpolator is defined using the QGLViewer::addKeyFrameKeyboardModifiers() and QGLViewer::pathKey() (default is Alt+F[1-12]). See the <a href="../keyboard.html">keyboard page</a> for details. */ void Camera::setKeyFrameInterpolator(unsigned int i, KeyFrameInterpolator* const kfi) { if (kfi) kfi_[i] = kfi; else kfi_.remove(i); } /*! Adds the current Camera position() and orientation() as a keyFrame to the path number \p i. This method can also be used if you simply want to save a Camera point of view (a path made of a single keyFrame). Use playPath() to make the Camera play the keyFrame path (resp. restore the point of view). Use deletePath() to clear the path. The default keyboard shortcut for this method is Alt+F[1-12]. Set QGLViewer::pathKey() and QGLViewer::addKeyFrameKeyboardModifiers(). If you use directly this method and the keyFrameInterpolator(i) does not exist, a new one is created. Its KeyFrameInterpolator::interpolated() signal should then be connected to the QGLViewer::update() slot (see setKeyFrameInterpolator()). */ void Camera::addKeyFrameToPath(unsigned int i) { if (!kfi_.contains(i)) setKeyFrameInterpolator(i, new KeyFrameInterpolator(frame())); kfi_[i]->addKeyFrame(*(frame())); } /*! Makes the Camera follow the path of keyFrameInterpolator() number \p i. If the interpolation is started, it stops it instead. This method silently ignores undefined (empty) paths (see keyFrameInterpolator()). The default keyboard shortcut for this method is F[1-12]. Set QGLViewer::pathKey() and QGLViewer::playPathKeyboardModifiers(). */ void Camera::playPath(unsigned int i) { if (kfi_.contains(i)) { if (kfi_[i]->interpolationIsStarted()) kfi_[i]->stopInterpolation(); else kfi_[i]->startInterpolation(); } } /*! Resets the path of the keyFrameInterpolator() number \p i. If this path is \e not being played (see playPath() and KeyFrameInterpolator::interpolationIsStarted()), resets it to its starting position (see KeyFrameInterpolator::resetInterpolation()). If the path is played, simply stops interpolation. */ void Camera::resetPath(unsigned int i) { if (kfi_.contains(i)) { if ((kfi_[i]->interpolationIsStarted())) kfi_[i]->stopInterpolation(); else { kfi_[i]->resetInterpolation(); kfi_[i]->interpolateAtTime(kfi_[i]->interpolationTime()); } } } /*! Deletes the keyFrameInterpolator() of index \p i. Disconnect the keyFrameInterpolator() KeyFrameInterpolator::interpolated() signal before deleting the keyFrameInterpolator() if needed: \code disconnect(camera()->keyFrameInterpolator(i), SIGNAL(interpolated()), this, SLOT(update())); camera()->deletePath(i); \endcode */ void Camera::deletePath(unsigned int i) { if (kfi_.contains(i)) { kfi_[i]->stopInterpolation(); delete kfi_[i]; kfi_.remove(i); } } /*! Draws all the Camera paths defined by the keyFrameInterpolator(). Simply calls KeyFrameInterpolator::drawPath() for all the defined paths. The path color is the current \c glColor(). \attention The OpenGL state is modified by this method: see KeyFrameInterpolator::drawPath(). */ void Camera::drawAllPaths() { for (QMap<unsigned int, KeyFrameInterpolator*>::ConstIterator it = kfi_.begin(), end=kfi_.end(); it != end; ++it) (it.value())->drawPath(3, 5, sceneRadius()); } //////////////////////////////////////////////////////////////////////////////// /*! Returns an XML \c QDomElement that represents the Camera. \p name is the name of the QDomElement tag. \p doc is the \c QDomDocument factory used to create QDomElement. Concatenates the Camera parameters, the ManipulatedCameraFrame::domElement() and the paths' KeyFrameInterpolator::domElement(). Use initFromDOMElement() to restore the Camera state from the resulting \c QDomElement. If you want to save the Camera state in a file, use: \code QDomDocument document("myCamera"); doc.appendChild( myCamera->domElement("Camera", document) ); QFile f("myCamera.xml"); if (f.open(IO_WriteOnly)) { QTextStream out(&f); document.save(out, 2); } \endcode Note that the QGLViewer::camera() is automatically saved by QGLViewer::saveStateToFile() when a QGLViewer is closed. Use QGLViewer::restoreStateFromFile() to restore it back. */ QDomElement Camera::domElement(const QString& name, QDomDocument& document) const { QDomElement de = document.createElement(name); QDomElement paramNode = document.createElement("Parameters"); paramNode.setAttribute("fieldOfView", QString::number(fieldOfView())); paramNode.setAttribute("zNearCoefficient", QString::number(zNearCoefficient())); paramNode.setAttribute("zClippingCoefficient", QString::number(zClippingCoefficient())); paramNode.setAttribute("orthoCoef", QString::number(orthoCoef_)); paramNode.setAttribute("sceneRadius", QString::number(sceneRadius())); paramNode.appendChild(sceneCenter().domElement("SceneCenter", document)); switch (type()) { case Camera::PERSPECTIVE : paramNode.setAttribute("Type", "PERSPECTIVE"); break; case Camera::ORTHOGRAPHIC : paramNode.setAttribute("Type", "ORTHOGRAPHIC"); break; } de.appendChild(paramNode); QDomElement stereoNode = document.createElement("Stereo"); stereoNode.setAttribute("IODist", QString::number(IODistance())); stereoNode.setAttribute("focusDistance", QString::number(focusDistance())); stereoNode.setAttribute("physScreenWidth", QString::number(physicalScreenWidth())); de.appendChild(stereoNode); de.appendChild(frame()->domElement("ManipulatedCameraFrame", document)); // KeyFrame paths for (QMap<unsigned int, KeyFrameInterpolator*>::ConstIterator it = kfi_.begin(), end=kfi_.end(); it != end; ++it) { QDomElement kfNode = (it.value())->domElement("KeyFrameInterpolator", document); kfNode.setAttribute("index", QString::number(it.key())); de.appendChild(kfNode); } return de; } /*! Restores the Camera state from a \c QDomElement created by domElement(). Use the following code to retrieve a Camera state from a file created using domElement(): \code // Load DOM from file QDomDocument document; QFile f("myCamera.xml"); if (f.open(IO_ReadOnly)) { document.setContent(&f); f.close(); } // Parse the DOM tree QDomElement main = document.documentElement(); myCamera->initFromDOMElement(main); \endcode The frame() pointer is not modified by this method. The frame() state is however modified. \attention The original keyFrameInterpolator() are deleted and should be copied first if they are shared. */ void Camera::initFromDOMElement(const QDomElement& element) { QDomElement child=element.firstChild().toElement(); QMutableMapIterator<unsigned int, KeyFrameInterpolator*> it(kfi_); while (it.hasNext()) { it.next(); deletePath(it.key()); } while (!child.isNull()) { if (child.tagName() == "Parameters") { // #CONNECTION# Default values set in constructor setFieldOfView(DomUtils::qrealFromDom(child, "fieldOfView", M_PI/4.0)); setZNearCoefficient(DomUtils::qrealFromDom(child, "zNearCoefficient", 0.005)); setZClippingCoefficient(DomUtils::qrealFromDom(child, "zClippingCoefficient", sqrt(3.0))); orthoCoef_ = DomUtils::qrealFromDom(child, "orthoCoef", tan(fieldOfView()/2.0)); setSceneRadius(DomUtils::qrealFromDom(child, "sceneRadius", sceneRadius())); setType(PERSPECTIVE); QString type = child.attribute("Type", "PERSPECTIVE"); if (type == "PERSPECTIVE") setType(Camera::PERSPECTIVE); if (type == "ORTHOGRAPHIC") setType(Camera::ORTHOGRAPHIC); QDomElement child2=child.firstChild().toElement(); while (!child2.isNull()) { /* Although the scene does not change when a camera is loaded, restore the saved center and radius values. Mainly useful when a the viewer is restored on startup, with possible additional cameras. */ if (child2.tagName() == "SceneCenter") setSceneCenter(Vec(child2)); child2 = child2.nextSibling().toElement(); } } if (child.tagName() == "ManipulatedCameraFrame") frame()->initFromDOMElement(child); if (child.tagName() == "Stereo") { setIODistance(DomUtils::qrealFromDom(child, "IODist", 0.062)); setFocusDistance(DomUtils::qrealFromDom(child, "focusDistance", focusDistance())); setPhysicalScreenWidth(DomUtils::qrealFromDom(child, "physScreenWidth", 0.5)); } if (child.tagName() == "KeyFrameInterpolator") { unsigned int index = DomUtils::uintFromDom(child, "index", 0); setKeyFrameInterpolator(index, new KeyFrameInterpolator(frame())); if (keyFrameInterpolator(index)) keyFrameInterpolator(index)->initFromDOMElement(child); } child = child.nextSibling().toElement(); } } /*! Gives the coefficients of a 3D half-line passing through the Camera eye and pixel (x,y). The origin of the half line (eye position) is stored in \p orig, while \p dir contains the properly oriented and normalized direction of the half line. \p x and \p y are expressed in Qt format (origin in the upper left corner). Use screenHeight() - y to convert to OpenGL units. This method is useful for analytical intersection in a selection method. See the <a href="../examples/select.html">select example</a> for an illustration. */ void Camera::convertClickToLine(const QPoint& pixel, Vec& orig, Vec& dir) const { switch (type()) { case Camera::PERSPECTIVE: orig = position(); dir = Vec( ((2.0 * pixel.x() / screenWidth()) - 1.0) * tan(fieldOfView()/2.0) * aspectRatio(), ((2.0 * (screenHeight()-pixel.y()) / screenHeight()) - 1.0) * tan(fieldOfView()/2.0), -1.0 ); dir = worldCoordinatesOf(dir) - orig; dir.normalize(); break; case Camera::ORTHOGRAPHIC: { GLdouble w,h; getOrthoWidthHeight(w,h); orig = Vec((2.0 * pixel.x() / screenWidth() - 1.0)*w, -(2.0 * pixel.y() / screenHeight() - 1.0)*h, 0.0); orig = worldCoordinatesOf(orig); dir = viewDirection(); break; } } } #ifndef DOXYGEN /*! This method has been deprecated in libQGLViewer version 2.2.0 */ void Camera::drawCamera(qreal, qreal, qreal) { qWarning("drawCamera is deprecated. Use Camera::draw() instead."); } #endif /*! Draws a representation of the Camera in the 3D world. The near and far planes are drawn as quads, the frustum is drawn using lines and the camera up vector is represented by an arrow to disambiguate the drawing. See the <a href="../examples/standardCamera.html">standardCamera example</a> for an illustration. Note that the current \c glColor and \c glPolygonMode are used to draw the near and far planes. See the <a href="../examples/frustumCulling.html">frustumCulling example</a> for an example of semi-transparent plane drawing. Similarly, the current \c glLineWidth and \c glColor is used to draw the frustum outline. When \p drawFarPlane is \c false, only the near plane is drawn. \p scale can be used to scale the drawing: a value of 1.0 (default) will draw the Camera's frustum at its actual size. This method assumes that the \c glMatrixMode is \c GL_MODELVIEW and that the current ModelView matrix corresponds to the world coordinate system (as it is at the beginning of QGLViewer::draw()). The Camera is then correctly positioned and orientated. \note The drawing of a QGLViewer's own QGLViewer::camera() should not be visible, but may create artefacts due to numerical imprecisions. */ void Camera::draw(bool drawFarPlane, qreal scale) const { glPushMatrix(); glMultMatrixd(frame()->worldMatrix()); // 0 is the upper left coordinates of the near corner, 1 for the far one Vec points[2]; points[0].z = scale * zNear(); points[1].z = scale * zFar(); switch (type()) { case Camera::PERSPECTIVE: { points[0].y = points[0].z * tan(fieldOfView()/2.0); points[0].x = points[0].y * aspectRatio(); const qreal ratio = points[1].z / points[0].z; points[1].y = ratio * points[0].y; points[1].x = ratio * points[0].x; break; } case Camera::ORTHOGRAPHIC: { GLdouble hw, hh; getOrthoWidthHeight(hw, hh); points[0].x = points[1].x = scale * qreal(hw); points[0].y = points[1].y = scale * qreal(hh); break; } } const int farIndex = drawFarPlane?1:0; // Near and (optionally) far plane(s) glBegin(GL_QUADS); for (int i=farIndex; i>=0; --i) { glNormal3d(0.0f, 0.0f, (i==0)?1.0f:-1.0f); glVertex3d( points[i].x, points[i].y, -points[i].z); glVertex3d(-points[i].x, points[i].y, -points[i].z); glVertex3d(-points[i].x, -points[i].y, -points[i].z); glVertex3d( points[i].x, -points[i].y, -points[i].z); } glEnd(); // Up arrow const qreal arrowHeight = 1.5 * points[0].y; const qreal baseHeight = 1.2 * points[0].y; const qreal arrowHalfWidth = 0.5 * points[0].x; const qreal baseHalfWidth = 0.3 * points[0].x; glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // Base glBegin(GL_QUADS); glVertex3d(-baseHalfWidth, points[0].y, -points[0].z); glVertex3d( baseHalfWidth, points[0].y, -points[0].z); glVertex3d( baseHalfWidth, baseHeight, -points[0].z); glVertex3d(-baseHalfWidth, baseHeight, -points[0].z); glEnd(); // Arrow glBegin(GL_TRIANGLES); glVertex3d( 0.0, arrowHeight, -points[0].z); glVertex3d(-arrowHalfWidth, baseHeight, -points[0].z); glVertex3d( arrowHalfWidth, baseHeight, -points[0].z); glEnd(); // Frustum lines switch (type()) { case Camera::PERSPECTIVE : glBegin(GL_LINES); glVertex3d(0.0, 0.0, 0.0); glVertex3d( points[farIndex].x, points[farIndex].y, -points[farIndex].z); glVertex3d(0.0, 0.0, 0.0); glVertex3d(-points[farIndex].x, points[farIndex].y, -points[farIndex].z); glVertex3d(0.0, 0.0, 0.0); glVertex3d(-points[farIndex].x, -points[farIndex].y, -points[farIndex].z); glVertex3d(0.0, 0.0, 0.0); glVertex3d( points[farIndex].x, -points[farIndex].y, -points[farIndex].z); glEnd(); break; case Camera::ORTHOGRAPHIC : if (drawFarPlane) { glBegin(GL_LINES); glVertex3d( points[0].x, points[0].y, -points[0].z); glVertex3d( points[1].x, points[1].y, -points[1].z); glVertex3d(-points[0].x, points[0].y, -points[0].z); glVertex3d(-points[1].x, points[1].y, -points[1].z); glVertex3d(-points[0].x, -points[0].y, -points[0].z); glVertex3d(-points[1].x, -points[1].y, -points[1].z); glVertex3d( points[0].x, -points[0].y, -points[0].z); glVertex3d( points[1].x, -points[1].y, -points[1].z); glEnd(); } } glPopMatrix(); } /*! Returns the 6 plane equations of the Camera frustum. The six 4-component vectors of \p coef respectively correspond to the left, right, near, far, top and bottom Camera frustum planes. Each vector holds a plane equation of the form: \code a*x + b*y + c*z + d = 0 \endcode where \c a, \c b, \c c and \c d are the 4 components of each vector, in that order. See the <a href="../examples/frustumCulling.html">frustumCulling example</a> for an application. This format is compatible with the \c glClipPlane() function. One camera frustum plane can hence be applied in an other viewer to visualize the culling results: \code // Retrieve plane equations GLdouble coef[6][4]; mainViewer->camera()->getFrustumPlanesCoefficients(coef); // These two additional clipping planes (which must have been enabled) // will reproduce the mainViewer's near and far clipping. glClipPlane(GL_CLIP_PLANE0, coef[2]); glClipPlane(GL_CLIP_PLANE1, coef[3]); \endcode */ void Camera::getFrustumPlanesCoefficients(GLdouble coef[6][4]) const { // Computed once and for all const Vec pos = position(); const Vec viewDir = viewDirection(); const Vec up = upVector(); const Vec right = rightVector(); const qreal posViewDir = pos * viewDir; static Vec normal[6]; static GLdouble dist[6]; switch (type()) { case Camera::PERSPECTIVE : { const qreal hhfov = horizontalFieldOfView() / 2.0; const qreal chhfov = cos(hhfov); const qreal shhfov = sin(hhfov); normal[0] = - shhfov * viewDir; normal[1] = normal[0] + chhfov * right; normal[0] = normal[0] - chhfov * right; normal[2] = -viewDir; normal[3] = viewDir; const qreal hfov = fieldOfView() / 2.0; const qreal chfov = cos(hfov); const qreal shfov = sin(hfov); normal[4] = - shfov * viewDir; normal[5] = normal[4] - chfov * up; normal[4] = normal[4] + chfov * up; for (int i=0; i<2; ++i) dist[i] = pos * normal[i]; for (int j=4; j<6; ++j) dist[j] = pos * normal[j]; // Natural equations are: // dist[0,1,4,5] = pos * normal[0,1,4,5]; // dist[2] = (pos + zNear() * viewDir) * normal[2]; // dist[3] = (pos + zFar() * viewDir) * normal[3]; // 2 times less computations using expanded/merged equations. Dir vectors are normalized. const qreal posRightCosHH = chhfov * pos * right; dist[0] = -shhfov * posViewDir; dist[1] = dist[0] + posRightCosHH; dist[0] = dist[0] - posRightCosHH; const qreal posUpCosH = chfov * pos * up; dist[4] = - shfov * posViewDir; dist[5] = dist[4] - posUpCosH; dist[4] = dist[4] + posUpCosH; break; } case Camera::ORTHOGRAPHIC : normal[0] = -right; normal[1] = right; normal[4] = up; normal[5] = -up; GLdouble hw, hh; getOrthoWidthHeight(hw, hh); dist[0] = (pos - hw * right) * normal[0]; dist[1] = (pos + hw * right) * normal[1]; dist[4] = (pos + hh * up) * normal[4]; dist[5] = (pos - hh * up) * normal[5]; break; } // Front and far planes are identical for both camera types. normal[2] = -viewDir; normal[3] = viewDir; dist[2] = -posViewDir - zNear(); dist[3] = posViewDir + zFar(); for (int i=0; i<6; ++i) { coef[i][0] = GLdouble(normal[i].x); coef[i][1] = GLdouble(normal[i].y); coef[i][2] = GLdouble(normal[i].z); coef[i][3] = dist[i]; } } void Camera::onFrameModified() { projectionMatrixIsUpToDate_ = false; modelViewMatrixIsUpToDate_ = false; }
#include "ovos.h" ovos::ovos() { type = "Tomato"; kol = 1; gmo = false; price = 10; } ovos::ovos(string str, double dob, bool boo, double doo, double shelf_lif) { type = str; kol = dob; gmo = boo; price = doo; shelf_life = shelf_lif; } void ovos::set_smth(bool boo) { gmo = boo; } bool ovos::get_smth() { return gmo; } void ovos::ust_bool() { bool boo; cin >> boo; set_smth(boo); } void ovos::print_msg() { cout << "Enter the name of vegetable, the amount in lb, the price for 1 lb of vegetable, GMO (if there is - 1, otherwise - 0) and shelf life of fruit:" << endl << endl;; } ovos ovos::operator=(ovos vo) { vo.set_type(type); vo.set_kol(kol); vo.set_smth(gmo); vo.set_price(price); vo.set_shelf_life(shelf_life); return vo; } bool ovos::operator==(vector<ovos>::iterator rf) { if (rf->get_type() == this->get_type()) return true; else return false; } ovos::~ovos(){}
//模板题,不再赘述 //此题注意,先求所有路径的权值总和, //然后将总权值减去 最小生成树求得的路径值相减 #include<cstdio> #include<algorithm> using namespace std; struct baka9 { int x,y,w;//分存每一条边前,后坐标与权值 }a[10100]; int num;//存边的数量 int pre[150];//存并查集中的祖先 int n,m; int tot,ans; bool cmp(baka9 aa,baka9 bb)//结构体sort排序必须自定义排序函数 { return aa.w<bb.w; } int find(int x)//查集 { if(pre[x]==x) return x; else return pre[x]=find(pre[x]); } void join(int x,int y)//并集 { int r1=find(x); int r2=find(y); if(r1 != r2) pre[r1]=r2; } void add(int xx,int yy,int ww) { a[++num].x=xx; a[num].y=yy; a[num].w=ww; } int main() { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) pre[i]=i; for(int i=1;i<=m;i++) { int xx,yy,ww; scanf("%d%d%d",&xx,&yy,&ww);//输入各边权值 tot+=ww; add(xx,yy,ww);//加入无向图 add(yy,xx,ww); } sort(a+1,a+num+1,cmp); int n1=0,i=1; while(n1++!=n)//循环找num条边,当找到n-1条边时停止 { while(find(a[i].x) == find(a[i].y) && i<=num) i++; join(a[i].x,a[i].y);//并集 ans+=a[i].w;//加和 } printf("%d",tot-ans);//减去 }
#include <algorithm> #include <fstream> #include <iostream> #include <sstream> #include <iomanip> #include <writefile.h> Matlab::WriteFile::WriteFile(const std::string& filename, bool save) : fileName_(filename.c_str()) , save_(save) { } Matlab::WriteFile::~WriteFile() { } void Matlab::WriteFile::addPlotObject(const PlotObject& object, uint figure) { figures_.push_back(std::make_pair(object, figure)); } void Matlab::WriteFile::setTitle(const std::string& title, const uint& figure) { titles_.push_back(std::make_pair(title, figure)); } void Matlab::WriteFile::createFile() { std::ostringstream os; const std::vector<uint> figureNumbers = findFigureNumbers(); std::cout << __LINE__ << "\n"; for (std::size_t i = 0; i < figureNumbers.size(); ++i) { std::cout << __LINE__ << "\n"; createFigure(figureNumbers[i], os); } std::ostringstream fileName; fileName << fileName_ << ".m"; createFile(fileName.str(), os.str()); } std::vector<uint> Matlab::WriteFile::findFigureNumbers() { std::vector<uint> figureNumbers; std::cout << figures_.size() << std::endl; for (std::size_t i = 0; i < figures_.size(); ++i) { // uint counter = 0; const uint figureNumber = figures_[i].second; if (std::find(figureNumbers.begin(), figureNumbers.end(), figureNumber) == figureNumbers.end()) figureNumbers.push_back(figureNumber); // for (std::size_t j = 0; j < figureNumbers.size(); ++j) // { // if (figureNumber == figureNumbers[j]) // { // ++counter; // } // } // if (counter == 0) // { // figureNumbers.push_back(figureNumber); // } } return figureNumbers; } void Matlab::WriteFile::createFigure(const uint& figure, std::ostringstream& os) { std::vector<PlotObject> plotObject; std::ostringstream fileName; std::ostringstream vectors; std::ostringstream legend; for (std::size_t i = 0; i < figures_.size(); ++i) { const uint figureNumber = figures_[i].second; if (figureNumber == figure) { PlotObject object = figures_[i].first; writeToFile(vectors, object); plotObject.push_back(object); } } fileName << fileName_ << "_figure_" << figure << "_" << plotObject[0].getLabel(Matlab::x) << "_" << plotObject[0].getLabel(Matlab::y); os << fileName.str() << "\n" << "figure(" << figure << ")\n" << plotObject[0].getPlotString() << "\n"; legend << "legend('" << plotObject[0].getLegend() << "'"; for (std::size_t i = 1; i < plotObject.size(); ++i) { os << "hold on" << "\n" << plotObject[i].getPlotString() << "\n"; legend << ",'" << plotObject[i].getLegend() << "'"; } legend << ")"; os << "xlabel('" << plotObject[0].getLabel(Matlab::x) << "')\n" << "ylabel('" << plotObject[0].getLabel(Matlab::y) << "')\n"; os << legend.str() << "\n"; if (save_) { os << "print('" << fileName.str() << "', '-dpng', '-r300')"; } os << "\n\n"; fileName << ".m"; createFile(fileName.str(), vectors.str()); } void Matlab::WriteFile::createFile(const std::string& fileName, const std::string& content) { std::ofstream printFile(fileName.c_str()); printFile << content; printFile.close(); } void Matlab::WriteFile::writeToFile(std::ostringstream& vectors, PlotObject& object) { { // x-axis std::vector<double> vectorX = object.getVector(Matlab::x); vectors << object.getVectorName(Matlab::x) << "_vec" << " = ["; std::vector<double>::const_iterator vector; for(vector = vectorX.begin(); vector != vectorX.end(); ++vector) { vectors << "\n" << *vector; } vectors << "\n]\n\n"; } { // y-axis std::vector<double> vectorY = object.getVector(Matlab::y); vectors << object.getVectorName(Matlab::y) << "_vec" << " = ["; std::vector<double>::const_iterator vector; for(vector = vectorY.begin(); vector != vectorY.end(); ++vector) { vectors << "\n" << *vector; } vectors << "\n]\n\n"; } }
// Created by: NW,JPB,CAL // 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 _Aspect_InteriorStyle_HeaderFile #define _Aspect_InteriorStyle_HeaderFile //! Interior types for primitive faces. enum Aspect_InteriorStyle { Aspect_IS_EMPTY = -1, //!< no interior Aspect_IS_SOLID = 0, //!< normally filled surface interior Aspect_IS_HATCH, //!< hatched surface interior Aspect_IS_HIDDENLINE, //!< interior is filled with viewer background color Aspect_IS_POINT, //!< display only vertices of surface (obsolete) // obsolete aliases Aspect_IS_HOLLOW = Aspect_IS_EMPTY, //!< transparent surface interior }; #endif // _Aspect_InteriorStyle_HeaderFile
// // PooledSessionImpl.h // // $Id: //poco/Main/Data/include/_Db/PooledSessionImpl.h#3 $ // // Library: Data // Package: SessionPooling // Module: PooledSessionImpl // // Definition of the PooledSessionImpl class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #pragma once #include "_Db/Data.h" #include "_Db/SessionImpl.h" #include "_Db/PooledSessionHolder.h" #include "_/AutoPtr.h" namespace _Db { class SessionPool; /** PooledSessionImpl is a decorator created by SessionPool that adds session pool management to SessionImpl objects. */ class _Db_API PooledSessionImpl: public SessionImpl { public: PooledSessionImpl(PooledSessionHolder* pHolder); /// Creates the PooledSessionImpl. ~PooledSessionImpl(); /// Destroys the PooledSessionImpl. // SessionImpl StatementImpl* createStatementImpl(); void begin(); void commit(); void rollback(); void open(const std::string& connect = ""); void close(); bool isConnected(); void setConnectionTimeout(std::size_t timeout); std::size_t getConnectionTimeout(); bool canTransact(); bool isTransaction(); void setTransactionIsolation(_::UInt32); _::UInt32 getTransactionIsolation(); bool hasTransactionIsolation(_::UInt32); bool isTransactionIsolation(_::UInt32); const std::string& connectorName() const; void setFeature(const std::string& name, bool state); bool getFeature(const std::string& name); void setProperty(const std::string& name, const _::Any& value); _::Any getProperty(const std::string& name); protected: SessionImpl* access() const; /*< Updates the last access timestamp, verifies validity of the session and returns the session if it is valid. Throws an SessionUnavailableException if the session is no longer valid. */ SessionImpl* impl() const; /// Returns a pointer to the SessionImpl. private: mutable _::AutoPtr<PooledSessionHolder> _pHolder; }; // // inlines // inline SessionImpl* PooledSessionImpl::impl() const { return _pHolder->session(); } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2010 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 DAPI_JIL_FILESYSTEM_SUPPORT #include "modules/device_api/jil/JILFSMgr.h" #include "modules/prefs/prefsmanager/collections/pc_files.h" #include "modules/prefsfile/prefsfile.h" #include "modules/prefsfile/prefssection.h" #include "modules/prefsfile/prefsentry.h" #include "modules/url/protocols/comm.h" #if defined OPERA_CONSOLE #include "modules/console/opconsoleengine.h" #endif // OPERA_CONSOLE #if PATHSEPCHAR == '/' #define INVALIDPATHSEPCHAR '\\' #else // PATHSEPCHAR != '/' #define INVALIDPATHSEPCHAR '/' #endif // PATHSEPCHAR JILFSMgr::JILFSMgr() : m_drive_monitor(NULL) , m_fs_mapping_manager() { } OP_STATUS JILFSMgr::Construct() { OpStatus::Ignore(ParseMappingFile()); // Mapping file parsing failed - ignore the error as mapping might be added later with proper API RETURN_IF_ERROR(OpStorageMonitor::Create(&m_drive_monitor, this)); m_drive_monitor->StartMonitoring(); return OpStatus::OK; } /* virtual */ JILFSMgr::~JILFSMgr() { if (m_drive_monitor) m_drive_monitor->StopMonitoring(); OP_DELETE(m_drive_monitor); } OP_STATUS JILFSMgr::OnStorageMounted(const StorageInfo &info) { if ((uni_strlen(info.mountpoint) == 1) && (info.mountpoint[0] == PATHSEPCHAR)) // Special handling for root of the filesystem return m_fs_mapping_manager.SetMounted(UNI_L(""), TRUE); else return m_fs_mapping_manager.SetMounted(info.mountpoint, TRUE); } OP_STATUS JILFSMgr::OnStorageUnmounted(const StorageInfo &info) { if ((uni_strlen(info.mountpoint) == 1) && (info.mountpoint[0] == PATHSEPCHAR)) // Special handling for root of the filesystem return m_fs_mapping_manager.SetMounted(UNI_L(""), FALSE); else return m_fs_mapping_manager.SetMounted(info.mountpoint, FALSE); } OP_STATUS JILFSMgr::FSMappingMgr::PopulateDataFromFile() { DeleteAll(); const OpFile *mapping_file = g_pcfiles->GetFile(PrefsCollectionFiles::DeviceSettingsFile); RETURN_VALUE_IF_NULL(mapping_file, OpStatus::ERR); PrefsFile drive_mapping(PREFS_INI, 0 ,0); RETURN_IF_LEAVE(drive_mapping.ConstructL()); RETURN_IF_LEAVE(drive_mapping.SetFileL(mapping_file)); RETURN_IF_LEAVE(drive_mapping.LoadAllL()); OpString section; section.Set("Mappings Info"); PrefsSection *prefs_section = NULL; RETURN_IF_LEAVE(prefs_section = drive_mapping.ReadSectionL(section)); RETURN_VALUE_IF_NULL(prefs_section, OpStatus::ERR); OpAutoPtr<PrefsSection> ap_prefs_section(prefs_section); const PrefsEntry *prefs_entry = prefs_section->FindEntry(UNI_L("Count")); //get mapping count RETURN_VALUE_IF_NULL(prefs_entry, OpStatus::ERR); int count = uni_atoi(prefs_entry->Value()); for (int cnt = 1; cnt < count + 1; ++cnt) // mappings are numerated starting from 1 { section.Empty(); RETURN_IF_ERROR(section.AppendFormat(UNI_L("Mapping %d"), cnt)); RETURN_IF_LEAVE(prefs_section = drive_mapping.ReadSectionL(section)); RETURN_VALUE_IF_NULL(prefs_section, OpStatus::ERR); ap_prefs_section.reset(prefs_section); const PrefsEntry *mnt_prefs_entry = prefs_section->FindEntry(UNI_L("Mount Point")); RETURN_VALUE_IF_NULL(mnt_prefs_entry, OpStatus::ERR); const uni_char *mount_point = mnt_prefs_entry->Value(); RETURN_VALUE_IF_NULL(mount_point, OpStatus::ERR); prefs_entry = prefs_section->Entries(); RETURN_VALUE_IF_NULL(prefs_entry, OpStatus::ERR); while (prefs_entry) { if (prefs_entry != mnt_prefs_entry) // For entries other than Mount Point entry... RETURN_IF_ERROR(AddData(mount_point, prefs_entry->Key(), prefs_entry->Value())); prefs_entry = prefs_entry->Suc(); } } return OpStatus::OK; } OP_STATUS JILFSMgr::ParseMappingFile() { return m_fs_mapping_manager.PopulateDataFromFile(); } OP_STATUS JILFSMgr::FSMappingMgr::CheckVirtualRootClash(const uni_char *virt) { OP_ASSERT(virt); OpAutoVector<OpString> virt_roots; GetData(NULL, &virt_roots, FALSE); for (UINT32 i = 0; i < virt_roots.GetCount(); ++i) { size_t target_len = MIN(uni_strlen(virt), static_cast<size_t>(virt_roots.Get(i)->Length())); if (uni_strncmp(virt, virt_roots.Get(i)->CStr(), target_len) == 0) { #ifdef OPERA_CONSOLE if (g_console->IsLogging()) { OpConsoleEngine::Message message(OpConsoleEngine::Gadget, OpConsoleEngine::Error); OpStatus::Ignore(message.message.Set(UNI_L("JIL filesystem: Invalid virtual roots! None of virtual roots may be subset of any other."))); TRAPD(result, g_console->PostMessageL(&message)); } #endif // OPERA_CONSOLE return OpStatus::ERR; } } return OpStatus::OK; } JILFSMgr::FSMappingMgr::MountPointInfo * JILFSMgr::FSMappingMgr::GetOrCreateMountPointInfo(const uni_char* mount_point_path) { OP_ASSERT(mount_point_path); MountPointInfo *mount_point_info; // Cast avoids compiler warnings and mount points will rather not have length in GBs. int length = static_cast<int>(uni_strlen(mount_point_path)); if (length > 0 && mount_point_path[length - 1] == PATHSEPCHAR) --length; OpString normalized_mount_point_path; RETURN_VALUE_IF_ERROR(normalized_mount_point_path.Set(mount_point_path, length), NULL); OP_STATUS status = m_mount_points.GetData(normalized_mount_point_path.CStr(), &mount_point_info); if (OpStatus::IsError(status)) { mount_point_info = OP_NEW(MountPointInfo, ()); OpAutoPtr<MountPointInfo> ap_mount_point_info(mount_point_info); if (!mount_point_info) return NULL; RETURN_VALUE_IF_ERROR(mount_point_info->mount_point.Set(normalized_mount_point_path.CStr()), NULL); RETURN_VALUE_IF_ERROR(m_mount_points.Add(mount_point_info->mount_point.CStr(), mount_point_info), NULL); ap_mount_point_info.release(); } return mount_point_info; } OP_STATUS JILFSMgr::FSMappingMgr::AddData(const uni_char *mount_point, const uni_char *real, const uni_char *virt, BOOL mounted /* = FALSE */) { OP_ASSERT(mount_point); OP_ASSERT(real); OP_ASSERT(virt); RETURN_IF_ERROR(CheckVirtualRootClash(virt)); OpString real_dir; RETURN_IF_ERROR(real_dir.Set(real)); JILFSMgr::ToSystemPathSeparator(real_dir.DataPtr()); MountPointInfo *mount_point_info = GetOrCreateMountPointInfo(mount_point); RETURN_OOM_IF_NULL(mount_point_info); MappingType *fs_mapping = OP_NEW(MappingType, ()); RETURN_OOM_IF_NULL(fs_mapping); OP_STATUS construct_status = fs_mapping->Construct(mount_point_info, real_dir.CStr(), virt); if (OpStatus::IsError(construct_status)) { OP_DELETE(fs_mapping); return construct_status; } fs_mapping->Into(&(mount_point_info->mappings)); if (mounted) mount_point_info->is_mounted = TRUE; return OpStatus::OK; } OP_STATUS JILFSMgr::FSMappingMgr::RemoveData(const uni_char *mount_point, const uni_char *real, const uni_char *virt) { OP_ASSERT(mount_point); OP_ASSERT((real && virt) || (!virt && !real)); OpString converted_real_dir; const uni_char *real_dir = real; if (real_dir) { RETURN_IF_ERROR(converted_real_dir.Set(real_dir)); JILFSMgr::ToSystemPathSeparator(converted_real_dir.DataPtr()); real_dir = converted_real_dir.CStr(); } OpString mount_point_stripped; const uni_char *normalized_mount_point = mount_point; int length = static_cast<int>(uni_strlen(mount_point)); if (uni_strrchr(mount_point, PATHSEPCHAR) == mount_point + length - 1) { RETURN_IF_ERROR(mount_point_stripped.Set(mount_point, length - 1)); normalized_mount_point = mount_point_stripped.CStr(); } MountPointInfo *mount_point_info; OP_STATUS status = m_mount_points.GetData(normalized_mount_point, &mount_point_info); if (OpStatus::IsError(status)) return OpStatus::ERR_FILE_NOT_FOUND; if (!real_dir && !virt) { mount_point_info->mappings.Clear(); return OpStatus::OK; } MappingType *mapping = mount_point_info->mappings.First(); while (mapping) { if (mapping->real.Compare(real_dir) == 0 && mapping->virt.Compare(virt) == 0) { MappingType *mapping_suc = mapping->Suc(); mapping->Out(); OP_DELETE(mapping); mapping = mapping_suc; } else mapping = mapping->Suc(); } return OpStatus::OK; } /* static */ void JILFSMgr::ToJILPathSeparator(uni_char* path) { #if PATHSEPCHAR != JILPATHSEPCHAR uni_char* p = path; while (*p != 0) { if (*p == PATHSEPCHAR) *p = JILPATHSEPCHAR; ++p; } #endif } /* static */ void JILFSMgr::ToSystemPathSeparator(uni_char* path) { uni_char* p = path; while (*p != 0) { if (*p == INVALIDPATHSEPCHAR) *p = PATHSEPCHAR; ++p; } } /* static */ OP_STATUS JILFSMgr::SafeJoinPath(OpString *result, const uni_char* path1, const uni_char* path2, uni_char path_separator) { OP_ASSERT(result); OP_ASSERT(path1); OP_ASSERT(path2); OP_ASSERT((path1[uni_strlen(path1) - 1] != PATHSEPCHAR) && (path1[uni_strlen(path1) - 1] != JILPATHSEPCHAR)); result->Empty(); // One can never be sure of the input here... if ((path2[0] != PATHSEPCHAR) && (path2[0] != JILPATHSEPCHAR)) RETURN_IF_ERROR(result->AppendFormat(UNI_L("%s%c%s"), path1, path_separator, path2)); else RETURN_IF_ERROR(result->AppendFormat(UNI_L("%s%s"), path1, path2)); return OpStatus::OK; } OP_STATUS JILFSMgr::MapRealToVirtual(const uni_char *real_path, OpString &virt_path) { RETURN_VALUE_IF_NULL(real_path, OpStatus::ERR); OpString found_virt; OP_STATUS find_status = m_fs_mapping_manager.FindVirtualFromReal(real_path, uni_strcmp, found_virt); // Check exact matching if (find_status == OpStatus::ERR_FILE_NOT_FOUND) { // Check partial matching if exact has not been found find_status = m_fs_mapping_manager.FindVirtualFromReal(real_path, CmpIfPathFromRoot, found_virt); } RETURN_IF_ERROR(find_status); OpString found_real; find_status = m_fs_mapping_manager.FindRealFromVirtual(found_virt, uni_strcmp, found_real); OP_ASSERT(find_status != OpStatus::ERR_FILE_NOT_FOUND); RETURN_IF_ERROR(find_status); RETURN_IF_ERROR(SafeJoinPath(&virt_path, found_virt.CStr(), real_path + found_real.Length(), JILPATHSEPCHAR)); return OpStatus::OK; } OP_STATUS JILFSMgr::MapVirtualToReal(const uni_char *virt_path, OpString &real_path) { RETURN_VALUE_IF_NULL(virt_path, OpStatus::ERR); OpString found_real; OP_STATUS find_status = m_fs_mapping_manager.FindRealFromVirtual(virt_path, uni_strcmp, found_real); // Check exact matching if (find_status == OpStatus::ERR_FILE_NOT_FOUND) { // Check partial matching if exact has not been found find_status = m_fs_mapping_manager.FindRealFromVirtual(virt_path, CmpIfPathFromRoot, found_real); } RETURN_IF_ERROR(find_status); OpString found_virtual; find_status = m_fs_mapping_manager.FindVirtualFromReal(found_real, uni_strcmp, found_virtual); OP_ASSERT(find_status != OpStatus::ERR_FILE_NOT_FOUND); RETURN_IF_ERROR(find_status); RETURN_IF_ERROR(SafeJoinPath(&real_path, found_real.CStr(), virt_path + found_virtual.Length(), PATHSEPCHAR)); return OpStatus::OK; } BOOL JILFSMgr::FSMappingMgr::FSMapping::IsActive() { if (mount_point_info->is_mounted) { OpString path; if (OpStatus::IsSuccess(SafeJoinPath(&path, mount_point_info->mount_point.CStr(), real, PATHSEPCHAR))) { OpFile file; if (OpStatus::IsSuccess(file.Construct(path))) { BOOL exists = FALSE; file.Exists(exists); return exists; } } } return FALSE; } OP_STATUS JILFSMgr::FSMappingMgr::SetMounted(const uni_char *mountpoint, BOOL mounted) { MountPointInfo *mount_point_info = GetOrCreateMountPointInfo(mountpoint); RETURN_OOM_IF_NULL(mount_point_info); mount_point_info->is_mounted = mounted; return OpStatus::OK; } OP_STATUS JILFSMgr::FSMappingMgr::FSMapping::Construct(MountPointInfo *mount_point_info_arg, const uni_char *real_path, const uni_char *virt_path) { OP_ASSERT(mount_point_info_arg); OP_ASSERT(real_path); OP_ASSERT(virt_path); mount_point_info = mount_point_info_arg; if (real_path[0] != PATHSEPCHAR) return OpStatus::ERR_PARSING_FAILED; int length = static_cast<int>(uni_strlen(real_path)); if (length > 0 && real_path[length - 1] == PATHSEPCHAR) --length; RETURN_IF_ERROR(real.Set(real_path, length)); length = static_cast<int>(uni_strlen(virt_path)); if (length > 1 && virt_path[length - 1] == JILPATHSEPCHAR) --length; return virt.Set(virt_path, length); } OP_STATUS JILFSMgr::FSMappingMgr::GetData(OpVector<OpString> *real, OpVector<OpString> *virt, BOOL active_only /* = TRUE */) { return m_data_grabber.CollectData(real, virt, active_only); } OP_STATUS JILFSMgr::FSMappingMgr::FSMappingDataGrabber::CollectData(OpVector<OpString> *real_path, OpVector<OpString> *virt_path, BOOL active_only) { if (real_path == NULL && virt_path == NULL) return OpStatus::ERR_NULL_POINTER; OpHashIterator *iter = m_mount_points->GetIterator(); if (!iter) return OpStatus::ERR; OpAutoPtr<OpHashIterator> ap_iter(iter); OP_STATUS status = OpStatus::OK; MountPointInfo *mount_point_info = NULL; status = iter->First(); while (OpStatus::IsSuccess(status) && (mount_point_info = static_cast<MountPointInfo *>(iter->GetData()))) { MappingType *mapping = mount_point_info->mappings.First(); while (mapping) { if ((active_only && mapping->IsActive()) || !active_only) { if (real_path) { OpString *path = OP_NEW(OpString, ()); RETURN_OOM_IF_NULL(path); OpAutoPtr<OpString> ap_path(path); RETURN_IF_ERROR(ap_path.get()->Set(mount_point_info->mount_point)); RETURN_IF_ERROR(ap_path.get()->Append(mapping->real)); RETURN_IF_ERROR(real_path->Add(ap_path.get())); ap_path.release(); } if (virt_path) { OpString *path = OP_NEW(OpString, ()); RETURN_OOM_IF_NULL(path); OpAutoPtr<OpString> ap_path(path); RETURN_IF_ERROR(ap_path.get()->Set(mapping->virt)); RETURN_IF_ERROR(virt_path->Add(ap_path.get())); ap_path.release(); } } mapping = mapping->Suc(); } status = iter->Next(); } return OpStatus::OK; } OP_STATUS JILFSMgr::FSMappingMgr::FSMappingDataGrabber::Find(int find_params, const uni_char *ref, int (*cmp)(const uni_char *, const uni_char *), OpString &result, BOOL active_only /* = TRUE */) { if (!ref || !cmp) return OpStatus::ERR_NULL_POINTER; OpHashIterator *iter = m_mount_points->GetIterator(); if (!iter) return OpStatus::ERR_NO_MEMORY; OpAutoPtr<OpHashIterator> ap_iter(iter); OP_STATUS status = iter->First(); result.Empty(); MountPointInfo *mount_point_info = NULL; while (OpStatus::IsSuccess(status) && (mount_point_info = static_cast<MountPointInfo *>(iter->GetData()))) { MappingType *mapping = mount_point_info->mappings.First(); while (mapping) { OpString compare; OpString ret; // Fill proper return values and compare patterns depending on type of find operation specified by find_params if (find_params & REAL) { RETURN_IF_ERROR(compare.AppendFormat(UNI_L("%s%s"), mount_point_info->mount_point.CStr(), mapping->real.CStr())); if ((find_params & MOUNT_POINT)) RETURN_IF_ERROR(ret.Set(mount_point_info->mount_point.CStr())); else RETURN_IF_ERROR(ret.Set(mapping->virt)); } else { RETURN_IF_ERROR(compare.Set(mapping->virt)); RETURN_IF_ERROR(ret.Set(mount_point_info->mount_point)); if (!(find_params & MOUNT_POINT)) RETURN_IF_ERROR(ret.Append(mapping->real)); } if (cmp(compare, ref) == 0 && (mapping->IsActive() || !active_only)) { result.Set(ret); return OpStatus::OK; } mapping = mapping->Suc(); } status = iter->Next(); } return OpStatus::ERR_FILE_NOT_FOUND; } OP_STATUS JILFSMgr::FSMappingMgr::FindMountPointFromVirtual(const uni_char *virt, int (*cmp_func)(const uni_char *, const uni_char *), OpString &result, BOOL active_only /* = TRUE */) { return m_data_grabber.Find(FSMappingDataGrabber::VIRTUAL | FSMappingDataGrabber::MOUNT_POINT, virt, cmp_func, result, active_only); } OP_STATUS JILFSMgr::FSMappingMgr::FindVirtualFromReal(const uni_char *real, int (*cmp_func)(const uni_char *, const uni_char *), OpString &result, BOOL active_only /* = TRUE */) { return m_data_grabber.Find(FSMappingDataGrabber::REAL, real, cmp_func, result, active_only); } OP_STATUS JILFSMgr::FSMappingMgr::FindRealFromVirtual(const uni_char *virt, int (*cmp_func)(const uni_char *, const uni_char *), OpString &result, BOOL active_only /* = TRUE */) { return m_data_grabber.Find(FSMappingDataGrabber::VIRTUAL, virt, cmp_func, result, active_only); } OP_STATUS JILFSMgr::GetFileSystemSize(const uni_char *fs, UINT64 *size) { if (!fs || !size) return OpStatus::ERR_NULL_POINTER; OpString mount_point; RETURN_IF_ERROR(m_fs_mapping_manager.FindMountPointFromVirtual(fs, uni_strcmp, mount_point)); StorageInfo info; info.mountpoint = mount_point; *size = m_drive_monitor->GetTotalSize(&info); return OpStatus::OK; } BOOL JILFSMgr::IsVirtualRoot(const uni_char *vr, BOOL part /* = FALSE */) { OpAutoVector<OpString> virt_dirs; RETURN_VALUE_IF_ERROR(m_fs_mapping_manager.GetData(NULL, &virt_dirs), FALSE); for (UINT32 cnt = 0; cnt < virt_dirs.GetCount(); ++cnt) { OP_ASSERT(virt_dirs.Get(cnt)); OpString *virt_dir = virt_dirs.Get(cnt); if (part) { if (virt_dir && (uni_strncmp(vr, virt_dir->CStr(), uni_strlen(vr)) == 0)) return TRUE; } else { if (virt_dir && ((uni_strcmp(vr, virt_dir->CStr()) == 0) || ((uni_strlen(vr) > 1) && ((vr[uni_strlen(vr) - 1] == JILPATHSEPCHAR && (uni_strncmp(vr, virt_dir->CStr(), uni_strlen(vr) - 1) == 0)) || (vr[uni_strlen(vr) - 1] != JILPATHSEPCHAR && (uni_strncmp(vr, virt_dir->CStr(), uni_strlen(virt_dir->CStr()) - 1) == 0)))) )) // ignore trailing '/' return TRUE; } } return FALSE; } OP_STATUS JILFSMgr::JILToSystemPath(const uni_char *jil_path, OpString &system_path) { OP_ASSERT(jil_path); if (!jil_path) return OpStatus::ERR_NULL_POINTER; RETURN_IF_ERROR(MapVirtualToReal(jil_path, system_path)); ToSystemPathSeparator(system_path.DataPtr()); return OpStatus::OK; } OP_STATUS JILFSMgr::SystemToJILPath(const uni_char *system_path, OpString &jil_path) { OP_ASSERT(system_path); if (!system_path) return OpStatus::ERR_NULL_POINTER; RETURN_IF_ERROR(MapRealToVirtual(system_path, jil_path)); ToJILPathSeparator(jil_path.DataPtr()); return OpStatus::OK; } BOOL JILFSMgr::IsFileAccessAllowed(URL url) { OP_ASSERT(url.Type() == URL_FILE); OpString sys_path; OpStringC path = url.GetAttribute(URL::KUniPath); return OpStatus::IsSuccess(JILToSystemPath(path, sys_path)); } #ifdef SELFTEST OP_STATUS JILFSMgr::SetActive(const uni_char *virt, BOOL active) { OpString mount_point; RETURN_IF_ERROR(m_fs_mapping_manager.FindMountPointFromVirtual(virt, uni_strcmp, mount_point, FALSE)); RETURN_IF_ERROR(m_fs_mapping_manager.SetMounted(mount_point.CStr(), active)); return OpStatus::OK; } OP_BOOLEAN JILFSMgr::FSMappingMgr::IsMounted(const uni_char *mount_point) { MountPointInfo *mount_point_info; RETURN_IF_ERROR(m_mount_points.GetData(mount_point, &mount_point_info)); return mount_point_info->is_mounted ? OpBoolean::IS_TRUE : OpBoolean::IS_FALSE; } #endif // SELFTEST #endif // DAPI_JIL_FILESYSTEM_SUPPORT
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/app18.unoproj.g.uno. // WARNING: Changes might be lost if you edit this file directly. #include <_root.app18_accessor_app18_Button_BackgroundColor.h> #include <app18.Button.h> #include <Uno.Bool.h> #include <Uno.Float4.h> #include <Uno.Object.h> #include <Uno.String.h> #include <Uno.Type.h> #include <Uno.UX.IPropertyListener.h> #include <Uno.UX.PropertyObject.h> #include <Uno.UX.Selector.h> static uString* STRINGS[1]; static uType* TYPES[2]; namespace g{ // internal sealed class app18_accessor_app18_Button_BackgroundColor :51 // { // static generated app18_accessor_app18_Button_BackgroundColor() :51 static void app18_accessor_app18_Button_BackgroundColor__cctor__fn(uType* __type) { ::g::Uno::UX::Selector_typeof()->Init(); app18_accessor_app18_Button_BackgroundColor::Singleton_ = app18_accessor_app18_Button_BackgroundColor::New1(); app18_accessor_app18_Button_BackgroundColor::_name_ = ::g::Uno::UX::Selector__op_Implicit(::STRINGS[0/*"BackgroundC...*/]); } static void app18_accessor_app18_Button_BackgroundColor_build(uType* type) { ::STRINGS[0] = uString::Const("BackgroundColor"); ::TYPES[0] = ::g::app18::Button_typeof(); ::TYPES[1] = ::g::Uno::Type_typeof(); type->SetFields(0, ::g::Uno::UX::Selector_typeof(), (uintptr_t)&app18_accessor_app18_Button_BackgroundColor::_name_, uFieldFlagsStatic, ::g::Uno::UX::PropertyAccessor_typeof(), (uintptr_t)&app18_accessor_app18_Button_BackgroundColor::Singleton_, uFieldFlagsStatic); } ::g::Uno::UX::PropertyAccessor_type* app18_accessor_app18_Button_BackgroundColor_typeof() { static uSStrong< ::g::Uno::UX::PropertyAccessor_type*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::UX::PropertyAccessor_typeof(); options.FieldCount = 2; options.ObjectSize = sizeof(app18_accessor_app18_Button_BackgroundColor); options.TypeSize = sizeof(::g::Uno::UX::PropertyAccessor_type); type = (::g::Uno::UX::PropertyAccessor_type*)uClassType::New("app18_accessor_app18_Button_BackgroundColor", options); type->fp_build_ = app18_accessor_app18_Button_BackgroundColor_build; type->fp_ctor_ = (void*)app18_accessor_app18_Button_BackgroundColor__New1_fn; type->fp_cctor_ = app18_accessor_app18_Button_BackgroundColor__cctor__fn; type->fp_GetAsObject = (void(*)(::g::Uno::UX::PropertyAccessor*, ::g::Uno::UX::PropertyObject*, uObject**))app18_accessor_app18_Button_BackgroundColor__GetAsObject_fn; type->fp_get_Name = (void(*)(::g::Uno::UX::PropertyAccessor*, ::g::Uno::UX::Selector*))app18_accessor_app18_Button_BackgroundColor__get_Name_fn; type->fp_get_PropertyType = (void(*)(::g::Uno::UX::PropertyAccessor*, uType**))app18_accessor_app18_Button_BackgroundColor__get_PropertyType_fn; type->fp_SetAsObject = (void(*)(::g::Uno::UX::PropertyAccessor*, ::g::Uno::UX::PropertyObject*, uObject*, uObject*))app18_accessor_app18_Button_BackgroundColor__SetAsObject_fn; type->fp_get_SupportsOriginSetter = (void(*)(::g::Uno::UX::PropertyAccessor*, bool*))app18_accessor_app18_Button_BackgroundColor__get_SupportsOriginSetter_fn; return type; } // public generated app18_accessor_app18_Button_BackgroundColor() :51 void app18_accessor_app18_Button_BackgroundColor__ctor_1_fn(app18_accessor_app18_Button_BackgroundColor* __this) { __this->ctor_1(); } // public override sealed object GetAsObject(Uno.UX.PropertyObject obj) :57 void app18_accessor_app18_Button_BackgroundColor__GetAsObject_fn(app18_accessor_app18_Button_BackgroundColor* __this, ::g::Uno::UX::PropertyObject* obj, uObject** __retval) { return *__retval = uBox(::g::Uno::Float4_typeof(), uPtr(uCast< ::g::app18::Button*>(obj, ::TYPES[0/*app18.Button*/]))->BackgroundColor()), void(); } // public override sealed Uno.UX.Selector get_Name() :54 void app18_accessor_app18_Button_BackgroundColor__get_Name_fn(app18_accessor_app18_Button_BackgroundColor* __this, ::g::Uno::UX::Selector* __retval) { return *__retval = app18_accessor_app18_Button_BackgroundColor::_name_, void(); } // public generated app18_accessor_app18_Button_BackgroundColor New() :51 void app18_accessor_app18_Button_BackgroundColor__New1_fn(app18_accessor_app18_Button_BackgroundColor** __retval) { *__retval = app18_accessor_app18_Button_BackgroundColor::New1(); } // public override sealed Uno.Type get_PropertyType() :56 void app18_accessor_app18_Button_BackgroundColor__get_PropertyType_fn(app18_accessor_app18_Button_BackgroundColor* __this, uType** __retval) { return *__retval = ::g::Uno::Float4_typeof(), void(); } // public override sealed void SetAsObject(Uno.UX.PropertyObject obj, object v, Uno.UX.IPropertyListener origin) :58 void app18_accessor_app18_Button_BackgroundColor__SetAsObject_fn(app18_accessor_app18_Button_BackgroundColor* __this, ::g::Uno::UX::PropertyObject* obj, uObject* v, uObject* origin) { uPtr(uCast< ::g::app18::Button*>(obj, ::TYPES[0/*app18.Button*/]))->SetBackgroundColor(uUnbox< ::g::Uno::Float4>(::g::Uno::Float4_typeof(), v), origin); } // public override sealed bool get_SupportsOriginSetter() :59 void app18_accessor_app18_Button_BackgroundColor__get_SupportsOriginSetter_fn(app18_accessor_app18_Button_BackgroundColor* __this, bool* __retval) { return *__retval = true, void(); } ::g::Uno::UX::Selector app18_accessor_app18_Button_BackgroundColor::_name_; uSStrong< ::g::Uno::UX::PropertyAccessor*> app18_accessor_app18_Button_BackgroundColor::Singleton_; // public generated app18_accessor_app18_Button_BackgroundColor() [instance] :51 void app18_accessor_app18_Button_BackgroundColor::ctor_1() { ctor_(); } // public generated app18_accessor_app18_Button_BackgroundColor New() [static] :51 app18_accessor_app18_Button_BackgroundColor* app18_accessor_app18_Button_BackgroundColor::New1() { app18_accessor_app18_Button_BackgroundColor* obj1 = (app18_accessor_app18_Button_BackgroundColor*)uNew(app18_accessor_app18_Button_BackgroundColor_typeof()); obj1->ctor_1(); return obj1; } // } } // ::g